File size: 4,842 Bytes
ed99773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398b807
ed99773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0354421
3183c8c
ed99773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49c8bbe
 
ed99773
 
5c38285
ed99773
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# app.py

import os
import requests
from datetime import datetime
import gradio as gr
from openai import OpenAI

# Load secrets from Hugging Face environment
openai_api_key = os.getenv("OPENAI_API_KEY")
weather_api_key = os.getenv("WEATHER_API_KEY")

client = OpenAI(api_key=openai_api_key)

top_cities = ["New York", "London", "Tokyo", "Paris", "Dubai", "Singapore", "Sydney", "Toronto", "Mumbai", "Berlin"]

def get_weather(city_name):
    url = "http://api.openweathermap.org/data/2.5/weather"
    params = {"q": city_name, "appid": weather_api_key, "units": "metric"}
    response = requests.get(url, params=params)
    data = response.json()
    if response.status_code == 200:
        return data["main"]["temp"], data["weather"][0]["description"], data["coord"]["lat"], data["coord"]["lon"]
    return None, None, None, None

def get_air_quality(lat, lon):
    url = "http://api.openweathermap.org/data/2.5/air_pollution"
    params = {"lat": lat, "lon": lon, "appid": weather_api_key}
    response = requests.get(url, params=params)
    data = response.json()
    if response.status_code == 200:
        aqi = data["list"][0]["main"]["aqi"]
        levels = {1: "Good 😊", 2: "Fair πŸ™‚", 3: "Moderate 😐", 4: "Poor 😷", 5: "Very Poor 😫"}
        return f"Air Quality Index: {aqi} ({levels.get(aqi, 'Unknown')})"
    return "❌ Could not retrieve air quality info."

def weather_chat(city, custom_city, user_query):
    selected_city = custom_city if custom_city else city
    temp, condition, lat, lon = get_weather(selected_city)
    if temp is None:
        return f"❌ Could not fetch weather for '{selected_city}'."
    report = f"The current temperature in {selected_city} is {temp}Β°C with {condition}."
    hour = datetime.now().hour
    time_context = "morning" if hour < 12 else "afternoon" if hour < 17 else "evening"
    alert = "⚠️ You may want to postpone any outdoor events." if "rain" in condition or "storm" in condition else ""
    aqi_info = get_air_quality(lat, lon)
    messages = [
        {"role": "system", "content": """You are a helpful weather assistant. Give Celsius responses.Do not answer questions not related to waether."""},
        {"role": "user", "content": f"{report}\nTime: {time_context}\n{aqi_info}\n{alert}\nUser asked: {user_query}"}
    ]
    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo", messages=messages, temperature=0, max_tokens=350
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"❌ OpenAI API Error: {e}"

def get_recommendation(city, custom_city):
    selected_city = custom_city if custom_city else city
    temp, condition, lat, lon = get_weather(selected_city)
    if temp is None:
        return f"❌ Could not fetch weather for '{selected_city}'."
    aqi = get_air_quality(lat, lon)
    hour = datetime.now().hour
    time_context = "morning" if hour < 12 else "afternoon" if hour < 17 else "evening"
    system_msg = "You are a weather lifestyle advisor. Based on temperature, weather, AQI, and time of day, suggest clothes, food, and activities."
    user_msg = f"City: {selected_city}\nTemperature: {temp}Β°C\nCondition: {condition}\nTime: {time_context}\nAir Quality: {aqi}"
    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": user_msg}],
            temperature=0.3,
            max_tokens=300,
            stop=["BYE"],
        )
        return f"{aqi}\n\n{response.choices[0].message.content}"
    except Exception as e:
        return f"❌ OpenAI API Error: {e}"

# Gradio Interface
with gr.Blocks(title="Weather Assistant Bot") as demo:
    with gr.Tabs():
        with gr.TabItem("🌦️ Weather Chat"):
            gr.Markdown("### Ask about current weather and get advice")
            city = gr.Dropdown(choices=top_cities, label="Select City")
            custom_city = gr.Textbox(label="Or Enter Your Own City")
            query = gr.Textbox(label="Enter Weather-related Question")
            output = gr.Textbox(label="Response", lines=8)
            btn = gr.Button("Get Weather Info")
            btn.click(fn=weather_chat, inputs=[city, custom_city, query], outputs=output)

        with gr.TabItem("🌫️ AQI & Lifestyle Tips"):
            gr.Markdown("### Check Air Quality and Get Personalized Recommendations")
            #city2 = gr.Dropdown(choices=top_cities, label="Select City")
            custom_city2 = gr.Textbox(label=" Enter Your Own City")
            aqi_output = gr.Textbox(label="AQI & Recommendation", lines=10)
            aqi_btn = gr.Button("Check AQI & Get Tips")
            aqi_btn.click(fn=get_recommendation, inputs=[custom_city2], outputs=aqi_output)

demo.launch()