Poojashetty357 commited on
Commit
ed99773
Β·
verified Β·
1 Parent(s): 88642ad

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -0
app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
+ import os
4
+ import requests
5
+ from datetime import datetime
6
+ import gradio as gr
7
+ from openai import OpenAI
8
+
9
+ # Load secrets from Hugging Face environment
10
+ openai_api_key = os.getenv("OPENAI_API_KEY")
11
+ weather_api_key = os.getenv("WEATHER_API_KEY")
12
+
13
+ client = OpenAI(api_key=openai_api_key)
14
+
15
+ top_cities = ["New York", "London", "Tokyo", "Paris", "Dubai", "Singapore", "Sydney", "Toronto", "Mumbai", "Berlin"]
16
+
17
+ def get_weather(city_name):
18
+ url = "http://api.openweathermap.org/data/2.5/weather"
19
+ params = {"q": city_name, "appid": weather_api_key, "units": "metric"}
20
+ response = requests.get(url, params=params)
21
+ data = response.json()
22
+ if response.status_code == 200:
23
+ return data["main"]["temp"], data["weather"][0]["description"], data["coord"]["lat"], data["coord"]["lon"]
24
+ return None, None, None, None
25
+
26
+ def get_air_quality(lat, lon):
27
+ url = "http://api.openweathermap.org/data/2.5/air_pollution"
28
+ params = {"lat": lat, "lon": lon, "appid": weather_api_key}
29
+ response = requests.get(url, params=params)
30
+ data = response.json()
31
+ if response.status_code == 200:
32
+ aqi = data["list"][0]["main"]["aqi"]
33
+ levels = {1: "Good 😊", 2: "Fair πŸ™‚", 3: "Moderate 😐", 4: "Poor 😷", 5: "Very Poor 😫"}
34
+ return f"Air Quality Index: {aqi} ({levels.get(aqi, 'Unknown')})"
35
+ return "❌ Could not retrieve air quality info."
36
+
37
+ def weather_chat(city, custom_city, user_query):
38
+ selected_city = custom_city if custom_city else city
39
+ temp, condition, lat, lon = get_weather(selected_city)
40
+ if temp is None:
41
+ return f"❌ Could not fetch weather for '{selected_city}'."
42
+ report = f"The current temperature in {selected_city} is {temp}Β°C with {condition}."
43
+ hour = datetime.now().hour
44
+ time_context = "morning" if hour < 12 else "afternoon" if hour < 17 else "evening"
45
+ alert = "⚠️ You may want to postpone any outdoor events." if "rain" in condition or "storm" in condition else ""
46
+ aqi_info = get_air_quality(lat, lon)
47
+ messages = [
48
+ {"role": "system", "content": "You are a helpful weather assistant. Give Celsius responses. Encourage user to be positive and appreciate the weather."},
49
+ {"role": "user", "content": f"{report}\nTime: {time_context}\n{aqi_info}\n{alert}\nUser asked: {user_query}"}
50
+ ]
51
+ try:
52
+ response = client.chat.completions.create(
53
+ model="gpt-3.5-turbo", messages=messages, temperature=0, max_tokens=350
54
+ )
55
+ return response.choices[0].message.content
56
+ except Exception as e:
57
+ return f"❌ OpenAI API Error: {e}"
58
+
59
+ def get_recommendation(city, custom_city):
60
+ selected_city = custom_city if custom_city else city
61
+ temp, condition, lat, lon = get_weather(selected_city)
62
+ if temp is None:
63
+ return f"❌ Could not fetch weather for '{selected_city}'."
64
+ aqi = get_air_quality(lat, lon)
65
+ hour = datetime.now().hour
66
+ time_context = "morning" if hour < 12 else "afternoon" if hour < 17 else "evening"
67
+ system_msg = "You are a weather lifestyle advisor. Based on temperature, weather, AQI, and time of day, suggest clothes, food, and activities."
68
+ user_msg = f"City: {selected_city}\nTemperature: {temp}Β°C\nCondition: {condition}\nTime: {time_context}\nAir Quality: {aqi}"
69
+ try:
70
+ response = client.chat.completions.create(
71
+ model="gpt-3.5-turbo",
72
+ messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": user_msg}],
73
+ temperature=0.3,
74
+ max_tokens=300
75
+ )
76
+ return f"{aqi}\n\n{response.choices[0].message.content}"
77
+ except Exception as e:
78
+ return f"❌ OpenAI API Error: {e}"
79
+
80
+ # Gradio Interface
81
+ with gr.Blocks(title="Weather Assistant Bot") as demo:
82
+ with gr.Tabs():
83
+ with gr.TabItem("🌦️ Weather Chat"):
84
+ gr.Markdown("### Ask about current weather and get advice")
85
+ city = gr.Dropdown(choices=top_cities, label="Select City")
86
+ custom_city = gr.Textbox(label="Or Enter Your Own City")
87
+ query = gr.Textbox(label="Enter Weather-related Question")
88
+ output = gr.Textbox(label="Response", lines=8)
89
+ btn = gr.Button("Get Weather Info")
90
+ btn.click(fn=weather_chat, inputs=[city, custom_city, query], outputs=output)
91
+
92
+ with gr.TabItem("🌫️ AQI & Lifestyle Tips"):
93
+ gr.Markdown("### Check Air Quality and Get Personalized Recommendations")
94
+ city2 = gr.Dropdown(choices=top_cities, label="Select City")
95
+ custom_city2 = gr.Textbox(label="Or Enter Your Own City")
96
+ aqi_output = gr.Textbox(label="AQI & Recommendation", lines=10)
97
+ aqi_btn = gr.Button("Check AQI & Get Tips")
98
+ aqi_btn.click(fn=get_recommendation, inputs=[city2, custom_city2], outputs=aqi_output)
99
+
100
+ demo.launch()