abuzarAli commited on
Commit
e4fce57
·
verified ·
1 Parent(s): aa3c089

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+ from groq import Groq
5
+
6
+ # --- API Clients ---
7
+
8
+ # 1. Setup Groq Client (AI)
9
+ # It will look for the key in the Environment Variables
10
+ api_key = os.environ.get("GROQ_API_KEY")
11
+
12
+ # Initialize client only if key exists to prevent immediate crash
13
+ client = Groq(api_key=api_key) if api_key else None
14
+
15
+ # --- Core Logic Functions ---
16
+
17
+ def get_coordinates(city_name):
18
+ """Fetch Lat/Lon for a city name."""
19
+ try:
20
+ url = f"https://geocoding-api.open-meteo.com/v1/search?name={city_name}&count=1&language=en&format=json"
21
+ response = requests.get(url)
22
+ data = response.json()
23
+ if "results" in data:
24
+ return data["results"][0]
25
+ return None
26
+ except:
27
+ return None
28
+
29
+ def get_weather_data(lat, lon):
30
+ """Fetch current weather data."""
31
+ try:
32
+ url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m&timezone=auto"
33
+ response = requests.get(url)
34
+ return response.json()
35
+ except:
36
+ return None
37
+
38
+ def generate_weather_report(city_name):
39
+ """
40
+ This is the main function called when the user clicks the button.
41
+ It combines Geocoding, Weather API, and Groq AI.
42
+ """
43
+ if not city_name:
44
+ return "Please enter a city name.", "", "", ""
45
+
46
+ # 1. Get Coordinates
47
+ location = get_coordinates(city_name)
48
+ if not location:
49
+ return f"Could not find city: {city_name}", "-", "-", "-"
50
+
51
+ # 2. Get Weather
52
+ weather = get_weather_data(location['latitude'], location['longitude'])
53
+ if not weather:
54
+ return "Error fetching weather data.", "-", "-", "-"
55
+
56
+ current = weather['current']
57
+ temp = f"{current['temperature_2m']} °C"
58
+ humidity = f"{current['relative_humidity_2m']} %"
59
+ wind = f"{current['wind_speed_10m']} km/h"
60
+
61
+ # 3. Get AI Summary using Groq
62
+ if not client:
63
+ ai_message = "⚠️ Groq API Key is missing. Please add it to Settings > Secrets."
64
+ else:
65
+ try:
66
+ prompt = f"""
67
+ The weather in {city_name} is:
68
+ Temperature: {temp}
69
+ Humidity: {humidity}
70
+ Wind Speed: {wind}
71
+
72
+ Provide a witty, helpful weather summary for a visitor. (Max 50 words).
73
+ """
74
+ completion = client.chat.completions.create(
75
+ messages=[{"role": "user", "content": prompt}],
76
+ model="mixtral-8x7b-32768",
77
+ )
78
+ ai_message = completion.choices[0].message.content
79
+ except Exception as e:
80
+ ai_message = f"AI Error: {str(e)}"
81
+
82
+ return ai_message, temp, humidity, wind
83
+
84
+ # --- UI Layout (Gradio Blocks) ---
85
+
86
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
87
+
88
+ # 1. Home / Header Section
89
+ gr.Markdown(
90
+ """
91
+ # ☁️ AI Weather Companion
92
+ Welcome! Enter a city below to get real-time weather stats and an AI-generated travel summary.
93
+ """
94
+ )
95
+
96
+ # 2. City Selection Section
97
+ with gr.Row():
98
+ city_input = gr.Textbox(
99
+ label="Enter City Name",
100
+ placeholder="e.g. Lahore, London, Tokyo",
101
+ scale=4
102
+ )
103
+ search_btn = gr.Button("Get Weather", variant="primary", scale=1)
104
+
105
+ # 3. Weather Info Section
106
+ gr.Markdown("### 📊 Current Conditions")
107
+
108
+ with gr.Row():
109
+ out_temp = gr.Label(label="Temperature")
110
+ out_humid = gr.Label(label="Humidity")
111
+ out_wind = gr.Label(label="Wind Speed")
112
+
113
+ # 4. AI Summary Output
114
+ gr.Markdown("### 🤖 AI Weatherman Says:")
115
+ out_summary = gr.Markdown("Waiting for input...")
116
+
117
+ # Connect the Button to the Function
118
+ search_btn.click(
119
+ fn=generate_weather_report,
120
+ inputs=city_input,
121
+ outputs=[out_summary, out_temp, out_humid, out_wind]
122
+ )
123
+
124
+ # Launch the app
125
+ if __name__ == "__main__":
126
+ demo.launch()