🌀️ Weather Chatbot

Advanced AI-powered weather chatbot with real-time weather forecasts, alerts, and comprehensive weather information using natural language processing. Features real-time weather data for any city worldwide, 5-day weather forecasts with hourly breakdowns, weather alerts and severe weather warnings, natural language processing with OpenAI API, location-based services with IP detection, city comparison features, weather analytics and insights, and beautiful web interface.
Try Interactive Demo

πŸ“– Project Overview

Weather Chatbot is an advanced AI-powered weather chatbot that integrates OpenWeatherMap API and OpenAI API with Flask to create an intelligent weather information system. This project offers real-time weather data for any city worldwide, 5-day weather forecasts with hourly and daily breakdowns, weather alerts and severe weather warnings, natural language processing with OpenAI API for intelligent conversations, location-based services with IP-based and coordinate-based detection, city comparison features, weather analytics and insights, weather maps and visualization, multi-language support for 12+ languages, and beautiful responsive web interface. Perfect for weather applications, travel planning, weather monitoring, and businesses requiring intelligent weather information services.

⚑ Quick Facts

🎯 Type: Weather Chatbot with AI & NLP Capabilities
πŸ€– AI Features: OpenAI API, OpenWeatherMap API, Natural Language Processing, Location Detection, Weather Analytics
⚑ Setup Time: ~5 minutes
πŸ“¦ Backend: Python with Flask
🎨 Frontend: HTML5, CSS3, JavaScript
🧠 AI Model: OpenAI GPT-3.5 Turbo
πŸ“± Platform: Web Browser
πŸ”§ Technologies: Python, Flask, OpenWeatherMap API, OpenAI API, Requests
25+
Files
5000+
Lines of Code
20+
Advanced Features
200K
Context Tokens
Developer: Molla Samser | Website: rskworld.in | Email: help@rskworld.in
Difficulty Level: Intermediate - Perfect for developers learning Python, Flask, OpenWeatherMap API integration, OpenAI API integration, NLP, weather data processing, and weather chatbot development.

✨ Features

Core Features

🌀️ Real-time Weather Data

Get current weather conditions for any city worldwide including temperature, humidity, pressure, wind speed, and visibility.

πŸ“… 5-Day Weather Forecasts

Detailed weather predictions with hourly (3-hour intervals) and daily breakdowns for accurate planning.

⚠️ Weather Alerts

Real-time weather alerts and severe weather warnings for specific locations with custom alert thresholds.

πŸ—£οΈ Natural Language Processing

Chat interface powered by OpenAI API for intelligent weather conversations with intent detection and entity extraction.

Advanced Features

πŸ“ Location-based Services

IP-based and coordinate-based location detection with geocoding and reverse geocoding for automatic city detection.

πŸ™οΈ City Comparison

Compare weather conditions across multiple cities with temperature, humidity, wind speed, and condition analysis.

πŸ“Š Weather Analytics

Analyze weather patterns, trends, and generate insights with comfort index calculations and statistical analysis.

πŸ—ΊοΈ Weather Maps

Interactive weather visualization with multiple layers, radar data, precipitation tracking, and custom map generation.

🌐 Multi-language Support

Support for 12+ languages for weather queries in natural language including English, Hindi, Bengali, Spanish, French, German, Chinese, Japanese, Arabic, Portuguese, Russian, and Italian.

πŸ’¬ Fallback Support

Works seamlessly even without OpenAI API using keyword matching for reliable weather queries.

🧠 Conversation Memory

Persistent conversation context with session management for context-aware weather interactions.

πŸ’Ύ Chat History

Save and export conversation history as JSON for record-keeping and weather query analysis.

πŸ“ˆ Session Analytics

Track weather query statistics, popular cities, API usage, and performance metrics in real-time.

πŸ”’ Security Features

Rate limiting, input validation, CORS configuration, and security headers for secure and reliable operation.

⚑ Real-time Responses

Fast weather data retrieval with caching support and optimized API calls for smooth weather conversations.

πŸ”” Notifications System

Email, SMS, Webhook, and Push notifications for weather alerts and severe weather warnings.

πŸ› οΈ Technologies

Python

Core programming language for educational platform

Language

Flask

Python web framework for backend API

Framework

OpenWeatherMap API

Weather data provider for real-time weather information and forecasts

Weather API

OpenAI API

AI model integration for natural language processing and intelligent conversations

AI API

Requests

HTTP library for API calls to weather and AI services

HTTP

python-dotenv

Environment variable management for API keys and configuration

Config

Geolocation Services

IP-based and coordinate-based location detection for automatic city detection

Location

Modular Architecture

Clean, modular code structure for easy extension

Architecture

πŸ“¦ Installation Guide - Step by Step

⏱️ Installation Time: ~5 minutes

Follow these simple steps to set up the Weather Chatbot on your system.

πŸ“‹ Prerequisites

🐍 Python 3.8+

Python 3.8 or higher required for the weather chatbot

Download: Python

🌐 Web Browser

Modern web browser (Chrome, Firefox, Safari, Edge) for accessing the weather chatbot

Recommended: Latest version of Chrome or Firefox

🌀️ OpenWeatherMap API Key

Get your free API key from OpenWeatherMap (required for weather data)

Get Key: OpenWeatherMap API

πŸ€– OpenAI API Key

Get your API key from OpenAI Platform (optional, for enhanced NLP features)

Get Key: OpenAI Platform

🌐 Internet Connection

Required for Flask server and OpenAI API calls

πŸš€ Step-by-Step Installation

πŸ“Œ Step 1: Download or Clone the Project

Option A: Download ZIP

  1. Download the project ZIP file from the repository
  2. Extract it to your desired location (e.g., C:\Projects\weather-chatbot or ~/Projects/weather-chatbot)
  3. Navigate to the extracted folder

Option B: Clone with Git

git clone https://github.com/rskworld/weather-chatbot.git
cd weather-chatbot
βœ… Step 2: Install Python Dependencies

Install required Python packages using pip.

# Install dependencies
pip install -r requirements.txt
πŸ”‘ Step 3: Set Up API Keys

Configure your OpenWeatherMap and OpenAI API keys in the environment file.

  1. Copy .env.example to .env
  2. Edit .env and add your API keys:
    • OPENWEATHER_API_KEY=your-openweathermap-api-key-here (required)
    • OPENAI_API_KEY=sk-your-openai-key-here (optional, for enhanced NLP)
    • FLASK_ENV=development (optional)
    • PORT=5000 (optional, default is 5000)
  3. Get your free OpenWeatherMap API key from OpenWeatherMap API
  4. Get your OpenAI API key from OpenAI Platform (optional, for enhanced NLP)
  5. Make sure your API keys have sufficient credits for testing
πŸš€ Step 4: Start the Flask Server

Start the Flask backend server by running app.py.

# Start Flask server
python app.py

# The server will start on http://localhost:5000
🌐 Step 5: Open Frontend

Open the HTML file in your browser or use a local web server.

Method 1: Direct File Opening

  1. Open index.html in your browser

Method 2: Using Local Web Server (Recommended)

# In a new terminal, start HTTP server
python -m http.server 8000

# Then open: http://localhost:8000

βœ… Installation Complete!

Congratulations! You've successfully set up the Weather Chatbot. The chatbot is ready to use with all features including:

  • OpenWeatherMap API integration for real-time weather data
  • OpenAI API integration for intelligent natural language conversations (optional)
  • Real-time weather data for any city worldwide
  • 5-day weather forecasts with hourly and daily breakdowns
  • Weather alerts and severe weather warnings
  • Location-based services with IP and coordinate detection
  • City comparison features
  • Weather analytics and insights
  • Weather maps and visualization
  • Multi-language support for 12+ languages
  • Fallback keyword matching when OpenAI API is unavailable

Next Steps:

  1. Ensure the Flask server is running (Step 4)
  2. Open the frontend in your browser (Step 5)
  3. Start asking weather questions in natural language to test the chatbot
  4. Explore all the weather features, query options, and customization settings!

πŸ”§ Troubleshooting Installation

❌ API Key Issues

Solution: Ensure your .env file contains a valid OPENWEATHER_API_KEY from OpenWeatherMap (required) and optionally OPENAI_API_KEY starting with sk- (for enhanced NLP). Check API keys have sufficient credits.

❌ Flask Server Not Starting

Solution: Check Python version (3.8+), verify dependencies installed with pip install -r requirements.txt, ensure port 5000 is available.

❌ Connection Errors

Solution: Verify Flask server is running on port 5000, check script.js has correct API_BASE_URL, ensure CORS is enabled in Flask.

❌ Import Errors

Solution: Reinstall dependencies, check virtual environment is activated, verify all packages in requirements.txt are installed.

πŸ“š Usage Guide - Step by Step

🎯 Getting Started with Weather Chatbot

Step-by-Step Usage Instructions

πŸ“ Step 1: Start Backend Server

  1. Ensure Flask server is running: python run.py
  2. Check server status at http://localhost:5000
  3. You should see the Weather Chatbot interface

🌐 Step 2: Open Frontend

  1. Open http://localhost:5000 in your web browser
  2. You should see the Weather Chatbot interface with:
    • Chat messages area with markdown support
    • Text input field
    • Language selection dropdown
    • Quick action buttons for different languages
    • Features panel with chatbot capabilities
    • Statistics cards showing conversation stats
    • Send button

πŸ’¬ Step 3: Start Chatting

  1. Text Input: Type your weather query in natural language and press Enter or click Send
  2. Weather Queries: Ask about weather for any city worldwide
  3. Natural Language: Use conversational language like "What's the weather in New York?"
  4. Try These:
    • "What's the weather in London?"
    • "Weather forecast for Mumbai for next 5 days"
    • "Is it going to rain in Tokyo today?"
    • "Compare weather in New York and Los Angeles"
    • "Weather alert for my location"
    • "What's the temperature in Paris?"
  5. View Responses: The chatbot will provide detailed weather information with forecasts and insights

βš™οΈ Step 4: Explore Features

Try out the weather chatbot features:

  • Current Weather: Ask for current weather conditions in any city
  • Weather Forecasts: Request 5-day weather forecasts with hourly breakdowns
  • Weather Alerts: Get real-time weather alerts and severe weather warnings
  • City Comparison: Compare weather conditions across multiple cities
  • Location Detection: Ask for weather using "my location" or city names
  • Weather Analytics: Get weather insights and trend analysis

πŸ’» Using the Weather Chatbot

You can interact with the Weather Chatbot through the web interface:

# Example Weather Interactions User: "What's the weather in New York?" Bot: [Current weather data: Temperature 72Β°F, Sunny, Humidity 65%, Wind 10 mph] User: "Weather forecast for London next 5 days" Bot: [5-day forecast with hourly and daily breakdowns for London] User: "Is it going to rain in Tokyo today?" Bot: [Precipitation forecast: Light rain expected at 3 PM, 70% chance] User: "Compare weather in Mumbai and Delhi" Bot: [Weather comparison: Mumbai 85Β°F/Humid, Delhi 78Β°F/Dry, Wind differences] User: "Weather alert for my location" Bot: [Current alerts: None. Weather conditions normal]
# Quick Action Buttons - Current Weather: Get current conditions - Forecast: Get 5-day forecast - Alerts: Check weather alerts - Compare: Compare cities - Location: Use my location - Help: View help and examples

πŸ“Š Features Usage

🌀️ Current Weather

Get real-time weather conditions for any city worldwide with temperature, humidity, wind, and visibility

πŸ“… Weather Forecasts

Request 5-day weather forecasts with hourly (3-hour intervals) and daily breakdowns for accurate planning

⚠️ Weather Alerts

Get real-time weather alerts and severe weather warnings for specific locations with custom thresholds

πŸ“ Location Services

Automatic location detection using IP or coordinates for weather queries based on your location

πŸ™οΈ City Comparison

Compare weather conditions across multiple cities with temperature, humidity, wind speed analysis

πŸ“Š Weather Analytics

Get weather insights, trends, comfort index calculations, and statistical analysis

πŸ—ΊοΈ Weather Maps

View interactive weather maps with multiple layers, radar data, and precipitation tracking

🧠 Conversation Memory

Maintains context across weather queries for better understanding and follow-up questions

πŸš€ Advanced Features & Capabilities

The Weather Chatbot includes advanced weather capabilities, natural language processing, and weather information services. Here's what you can do:

🌀️ Weather Intelligence

The chatbot excels at understanding weather queries in natural language with intent detection, entity extraction, and intelligent responses. Ask about weather for any city worldwide using conversational language.

πŸ“Š Advanced Weather Analytics

Get comprehensive weather insights including temperature trends, precipitation predictions, comfort index calculations, and statistical analysis. Analyze weather patterns over time with detailed reports.

πŸ“ Location Intelligence

Automatic location detection using IP-based and coordinate-based geocoding. The chatbot understands location context and provides weather data for your area or any specified city.

πŸ—ΊοΈ Weather Visualization

Interactive weather maps with multiple layers, radar data, precipitation tracking, and custom map generation. Visualize weather conditions and trends with comprehensive mapping tools.

πŸ’» Code Examples

Basic Weather Chatbot Integration

// Python Flask backend - app.py from flask import Flask, request, jsonify from chatbot import Chatbot from weather_api import WeatherAPI app = Flask(__name__) chatbot = Chatbot() weather_api = WeatherAPI() @app.route('/chat', methods=['POST']) def chat(): data = request.json message = data.get('message', '') location = data.get('location') # Optional: city name or coordinates # Process weather query with NLP result = chatbot.process_message(message, location) # Get weather data if location is identified if result.get('location'): weather_data = weather_api.get_current_weather(result['location']) result['weather'] = weather_data return jsonify(result) @app.route('/forecast', methods=['POST']) def forecast(): data = request.json city = data.get('city', '') days = data.get('days', 5) forecast_data = weather_api.get_forecast(city, days) return jsonify(forecast_data) if __name__ == '__main__': app.run(debug=True, port=5000)

JavaScript Frontend Integration

// Frontend JavaScript - chatbot.js async function sendMessage(message, location = null) { const response = await fetch('http://localhost:5000/chat', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ message: message, location: location // Optional: city name or coordinates }) }); const data = await response.json(); return { response: data.response, weather: data.weather, location: data.location, forecast: data.forecast }; } // Usage sendMessage('What\'s the weather in New York?').then(result => { console.log('Chatbot:', result.response); console.log('Weather:', result.weather); console.log('Location:', result.location); });

Complete Weather Chatbot Example

// Weather Chatbot Class class WeatherChatbot { constructor(apiUrl) { this.apiUrl = apiUrl || 'http://localhost:5000/chat'; this.conversationHistory = []; this.currentLocation = null; } async sendMessage(message, location = null) { const response = await fetch(this.apiUrl, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ message: message, location: location }) }); const data = await response.json(); // Update conversation history this.conversationHistory.push( {role: 'user', content: message, location: data.location}, {role: 'assistant', content: data.response, weather: data.weather} ); // Update current location if (data.location) { this.currentLocation = data.location; } return { response: data.response, weather: data.weather, location: data.location, forecast: data.forecast }; } async getForecast(city, days = 5) { const response = await fetch('http://localhost:5000/forecast', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ city: city, days: days }) }); return await response.json(); } clearHistory() { this.conversationHistory = []; } } // Usage const chatbot = new WeatherChatbot(); chatbot.sendMessage('What\'s the weather in New York?').then(result => { console.log('Chatbot:', result.response); console.log('Weather:', result.weather); console.log('Location:', result.location); });

Configuration Example

// Frontend config - chatbot.js const ChatbotConfig = { api: { baseUrl: 'http://localhost:5000', endpoints: { chat: '/chat', forecast: '/forecast', alerts: '/alerts', compare: '/compare' } }, weather: { defaultUnits: 'metric', // metric, imperial, kelvin defaultCity: 'London', autoLocation: true }, model: { default: 'gpt-3.5-turbo', maxTokens: 1024, temperature: 0.7 }, ui: { animationDuration: 300, messageDelay: 500 } }; // Access configuration console.log(ChatbotConfig.weather.defaultUnits);
# Backend config - config.py import os from dotenv import load_dotenv load_dotenv() class Config: OPENWEATHER_API_KEY = os.getenv('OPENWEATHER_API_KEY') OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') # Optional DEFAULT_MODEL = 'gpt-3.5-turbo' DEFAULT_MAX_TOKENS = 1024 DEFAULT_TEMPERATURE = 0.7 WEATHER_UNITS = os.getenv('WEATHER_UNITS', 'metric') # metric, imperial, kelvin DEFAULT_CITY = os.getenv('DEFAULT_CITY', 'London') SUPPORTED_LANGUAGES = ['en', 'hi', 'bn', 'es', 'fr', 'de', 'zh', 'ja', 'ar', 'pt', 'ru', 'it'] DEFAULT_LANGUAGE = 'en'

πŸ”— API Integration

Weather & AI API Integration

The application integrates with OpenWeatherMap API for real-time weather data and OpenAI's GPT API for advanced NLP and natural language weather queries. The backend uses Python Flask to handle API calls, weather data processing, location detection, and natural language processing, while the frontend uses JavaScript for user interactions and weather data rendering.

Available APIs & Technologies

API/Technology Type Description
OpenWeatherMap API Weather API Real-time weather data and forecasts for any city worldwide
OpenAI GPT API AI API Advanced NLP for natural language weather queries
Geolocation API Location API IP-based and coordinate-based location detection
Flask REST API Backend Python Flask server for weather API endpoints
LocalStorage Browser API Store settings and weather conversation history
Web Speech API Browser API Voice input/output for weather queries

Backend API Endpoints

# Flask Backend - app.py @app.route('/chat', methods=['POST']) def chat(): data = request.json message = data.get('message', '') location = data.get('location') result = chatbot.process_message(message, location) return jsonify(result) @app.route('/weather', methods=['POST']) def get_weather(): data = request.json city = data.get('city', '') weather_data = weather_api.get_current_weather(city) return jsonify({ 'weather': weather_data, 'city': city, 'location': weather_data.get('location') }) @app.route('/forecast', methods=['POST']) def get_forecast(): data = request.json city = data.get('city', '') days = data.get('days', 5) forecast_data = weather_api.get_forecast(city, days) return jsonify({ 'forecast': forecast_data, 'city': city, 'days': days }) @app.route('/alerts', methods=['POST']) def get_alerts(): data = request.json city = data.get('city', '') alerts_data = weather_api.get_alerts(city) return jsonify({ 'alerts': alerts_data, 'city': city }) @app.route('/compare', methods=['POST']) def compare_cities(): data = request.json cities = data.get('cities', []) comparison_data = weather_api.compare_cities(cities) return jsonify({ 'comparison': comparison_data, 'cities': cities }) @app.route('/health', methods=['GET']) def health(): return jsonify({ 'status': 'healthy', 'openweather_configured': bool(os.getenv('OPENWEATHER_API_KEY')), 'openai_configured': bool(os.getenv('OPENAI_API_KEY')) })
// Frontend JavaScript - API Integration async function sendMessage(message, location = null) { try { const response = await fetch('http://localhost:5000/chat', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ message: message, location: location // null for auto-detection }) }); if (!response.ok) { throw new Error('API request failed'); } const data = await response.json(); return { response: data.response, weather: data.weather, location: data.location, forecast: data.forecast }; } catch (error) { console.error('Error:', error); return {error: error.message}; } } // Get weather for a city async function getWeather(city) { const response = await fetch('http://localhost:5000/weather', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({city: city}) }); return await response.json(); } // Get forecast for a city async function getForecast(city, days = 5) { const response = await fetch('http://localhost:5000/forecast', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ city: city, days: days }) }); return await response.json(); } // Compare cities async function compareCities(cities) { const response = await fetch('http://localhost:5000/compare', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({cities: cities}) }); return await response.json(); }

Browser Compatibility

// Check Weather Chatbot API Connection async function checkHealth() { try { const response = await fetch('http://localhost:5000/health'); const data = await response.json(); console.log('Server Status:', data.status); console.log('OpenWeatherMap Configured:', data.openweather_configured); console.log('OpenAI Configured:', data.openai_configured); return data.openweather_configured && data.openai_configured; } catch (error) { console.error('Health check failed:', error); return false; } } // Get weather alerts for a city async function getAlerts(city) { const response = await fetch('http://localhost:5000/alerts', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({city: city}) }); return await response.json(); } // Recommended setup: // - Backend: Python 3.8+ with Flask, requests, openai, python-dotenv // - Frontend: Modern browsers (Chrome, Edge, Safari, Firefox) // - Voice Features: Chrome/Edge for Web Speech API support // - Weather API: OpenWeatherMap API key (required) // - NLP API: OpenAI API key (optional, for enhanced NLP)

βš™οΈ Configuration

Configuration in this application is handled through environment variables and settings files:

Environment Variables

Create a .env file in the project root (copy from .env.example):

# .env file OPENWEATHER_API_KEY=your-openweathermap-api-key-here OPENAI_API_KEY=sk-your-openai-api-key-here FLASK_ENV=development SECRET_KEY=your-secret-key-here PORT=5000 WEATHER_UNITS=metric DEFAULT_CITY=London

Note: Get your API keys from OpenWeatherMap (required) and OpenAI Platform (optional). Never commit your .env file to version control.

Python Configuration (config.py)

The config.py file contains configuration settings:

# config.py import os from dotenv import load_dotenv load_dotenv() class Config: OPENWEATHER_API_KEY = os.getenv('OPENWEATHER_API_KEY') OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') # Optional DEFAULT_MODEL = 'gpt-3.5-turbo' DEFAULT_MAX_TOKENS = 1024 DEFAULT_TEMPERATURE = 0.7 WEATHER_UNITS = os.getenv('WEATHER_UNITS', 'metric') # metric, imperial, kelvin DEFAULT_CITY = os.getenv('DEFAULT_CITY', 'London') SUPPORTED_LANGUAGES = ['en', 'hi', 'bn', 'es', 'fr', 'de', 'zh', 'ja', 'ar', 'pt', 'ru', 'it'] DEFAULT_LANGUAGE = 'en'

Frontend Configuration

Edit script.js to configure API endpoint:

// script.js const API_BASE_URL = 'http://localhost:5000'; const DEFAULT_MODEL = 'gpt-3.5-turbo'; const DEFAULT_MAX_TOKENS = 1024; const DEFAULT_TEMPERATURE = 0.7; const WEATHER_UNITS = 'metric'; // metric, imperial, kelvin const DEFAULT_CITY = 'London'; const AUTO_LOCATION = true;

Browser LocalStorage Settings

User settings are automatically saved to browser's local storage:

// Settings are saved automatically localStorage.setItem('weatherChatbotSettings', JSON.stringify({ model: 'gpt-3.5-turbo', maxTokens: 1024, temperature: 0.7, weatherUnits: 'metric', defaultCity: 'London', autoLocation: true, weatherAlerts: true, voiceEnabled: false })); // Load settings const settings = JSON.parse(localStorage.getItem('weatherChatbotSettings'));

Runtime Configuration

Configure settings through the web interface:

  • Weather Units: Select preferred units (metric, imperial, kelvin)
  • Default City: Set default city for weather queries
  • Auto Location: Enable/disable automatic location detection
  • Weather Alerts: Enable/disable weather alerts and warnings
  • Voice Input/Output: Enable/disable voice functionality
  • Language: Select preferred language for weather queries (12+ languages supported)

All settings are saved automatically and persist across browser sessions.

πŸ“ Project Structure

The Weather Chatbot follows a clean, organized structure for easy navigation and maintenance.

weather-chatbot/
β”œβ”€β”€ weather-chatbot/
β”‚   β”œβ”€β”€ templates/
β”‚   β”‚   └── index.html      # Main HTML interface
β”‚   β”œβ”€β”€ static/
β”‚   β”‚   β”œβ”€β”€ css/
β”‚   β”‚   β”‚   └── style.css   # Modern styling
β”‚   β”‚   └── js/
β”‚   β”‚       └── script.js   # Frontend logic
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ geolocation.py  # Location detection
β”‚   β”‚   β”œβ”€β”€ weather_utils.py # Weather data processing
β”‚   β”‚   β”œβ”€β”€ advanced_nlp.py # NLP processing
β”‚   β”‚   β”œβ”€β”€ analytics.py    # Weather analytics
β”‚   β”‚   β”œβ”€β”€ comparison.py   # City comparison
β”‚   β”‚   β”œβ”€β”€ weather_maps.py # Weather maps
β”‚   β”‚   └── ...             # Other utility modules
β”‚   β”œβ”€β”€ app.py              # Flask backend server
β”‚   β”œβ”€β”€ config.py           # Configuration settings
β”‚   β”œβ”€β”€ chatbot.py          # Chatbot logic
β”‚   β”œβ”€β”€ weather_api.py      # Weather API integration
β”‚   β”œβ”€β”€ run.py              # Application runner
β”‚   └── requirements.txt    # Python dependencies
β”œβ”€β”€ demo/
β”‚   β”œβ”€β”€ index.html          # Documentation page
β”‚   β”œβ”€β”€ demo.html           # Interactive demo
β”‚   β”œβ”€β”€ style.css           # Demo styling
β”‚   └── script.js           # Demo scripts
β”œβ”€β”€ .env                    # Environment variables
└── README.md               # Project documentation

πŸ“„ Frontend Files

Location: weather-chatbot/templates/ and weather-chatbot/static/

  • templates/index.html - Main UI interface with weather chat
  • static/css/style.css - Modern gradient styling
  • static/js/script.js - JavaScript functionality

🐍 Backend Files

Location: weather-chatbot/

  • app.py - Flask server & API endpoints
  • config.py - Configuration settings
  • chatbot.py - Chatbot logic with OpenAI integration
  • weather_api.py - OpenWeatherMap API integration
  • run.py - Application entry point
  • utils/geolocation.py - Location detection services
  • utils/weather_utils.py - Weather data processing
  • utils/advanced_nlp.py - Natural language processing
  • utils/comparison.py - City comparison features
  • utils/analytics.py - Weather analytics

βš™οΈ Configuration

Setup: Configure these files for your environment

  • .env - Environment variables (API keys)
  • requirements.txt - Python dependencies
  • config.py - Application configuration

πŸ”§ Troubleshooting

API Key Issues

  • Ensure your .env file contains a valid OPENWEATHER_API_KEY from OpenWeatherMap
  • Optionally add OPENAI_API_KEY starting with sk- for enhanced NLP features
  • Check that the API keys are correctly formatted and not expired
  • Verify your OpenWeatherMap API key has sufficient credits
  • If using OpenAI API, verify it has sufficient credits in OpenAI Platform
  • Make sure the .env file is in the project root directory
  • Restart the Flask server after updating the API keys

Flask Server Issues

  • Server not starting: Check Python version (3.8+), verify dependencies installed with pip install -r requirements.txt
  • Port 5000 in use: Change port in .env file or stop other applications using port 5000
  • Import errors: Ensure virtual environment is activated, reinstall dependencies
  • CORS errors: Verify Flask-CORS is installed and enabled in app.py
  • Connection refused: Check firewall settings, ensure server is running on correct port

Frontend Connection Issues

  • Failed to fetch: Ensure Flask server is running, check API_BASE_URL in chatbot.js
  • CORS errors: Make sure Flask-CORS is installed and configured in backend
  • Server offline indicator: Check server status at http://localhost:5000
  • Port mismatch: Verify frontend API_BASE_URL matches backend port
  • Weather data not loading: Check OpenWeatherMap API key validity and internet connection
  • NLP not working: Check OpenAI API key if using enhanced NLP features

Common Issues

  • API key not found: Create .env file from .env.example and add your API keys
  • Module not found: Install dependencies with pip install -r requirements.txt
  • Weather API errors: Check OpenWeatherMap API key validity, verify credits, check API status
  • Location detection not working: Check internet connection and geolocation service availability
  • Response errors: Check API key validity, verify credits, check OpenWeatherMap/OpenAI API status
  • Forecast not loading: Verify OpenWeatherMap API key has forecast access enabled
  • Voice features not working: Check browser compatibility (Chrome/Edge recommended)
  • City not found: Verify city name spelling or use coordinates instead

πŸ“‹ Requirements

Backend Requirements: - Python 3.8 or higher - Flask web framework - OpenAI Python SDK (optional, for enhanced NLP) - Flask-CORS for CORS support - Requests library for HTTP calls - python-dotenv for environment variables Frontend Requirements: - Modern Web Browser (Chrome, Edge, Safari, Firefox) - JavaScript ES6+ support - LocalStorage API - Web Speech API (for voice features, optional) API Requirements: - OpenWeatherMap API Key (required, get from openweathermap.org/api) - OpenAI API Key (optional, for enhanced NLP, get from platform.openai.com) - Active internet connection for API calls Python Dependencies (see requirements.txt): - flask - flask-cors - requests - openai (optional) - python-dotenv Optional Dependencies: - Voice features require Web Speech API (Chrome/Edge recommended) - OpenAI API for enhanced natural language processing

Browser Compatibility: Chrome, Edge, Safari, or Firefox (Chrome/Edge recommended for voice features).

Python Version: Python 3.8 or higher required for backend server.

Internet Connection: Required for OpenWeatherMap API calls, OpenAI API calls (if enabled), and CDN resources.

🎯 Use Cases

🌍 Weather Information

Get real-time weather data for any city worldwide with natural language queries

πŸ“… Travel Planning

Compare weather conditions across multiple cities to help with travel planning

⚠️ Weather Monitoring

Receive real-time weather alerts and severe weather warnings for specific locations

πŸ“± Mobile Apps

Integrate weather chatbot capabilities into mobile applications

🌐 Website Integration

Add weather chatbot support to websites for weather information services

πŸ“Š Weather Analytics

Analyze weather patterns, trends, and generate insights for weather monitoring

πŸ—ΊοΈ Weather Maps

Interactive weather visualization with multiple layers and radar data

πŸ‘₯ Business Applications

Integrate weather chatbot into business applications for weather-dependent operations

πŸ’¬ Support

For support, questions, or more projects:

πŸ“„ License

This project is provided as-is for educational and development purposes.

MIT License - See LICENSE file for details.