mbalvi commited on
Commit
4736d13
·
verified ·
1 Parent(s): 91db7d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -38
app.py CHANGED
@@ -1,63 +1,80 @@
1
  """
2
- app.py - Simple Weather Forecast App for Pakistan Cities
3
- ---------------------------------------------------------
4
- Beginner-friendly Gradio web app to simulate weather forecasts
5
- for Pakistani cities.
6
 
7
- ⚠️ NOTE: This app does NOT use real-time weather APIs
8
- (no API key needed). It randomly generates forecasts
9
- for demonstration on Hugging Face Spaces.
10
 
11
  How to run on Hugging Face Spaces:
12
- 1. Create a new Space with "Gradio" SDK
13
- 2. Upload app.py and requirements.txt
14
- 3. Commit Your app will run!
 
15
  """
16
 
17
  import gradio as gr
18
- import random
19
- from datetime import datetime, timedelta
20
 
21
- # --- List of Pakistani cities ---
22
- pak_cities = [
 
 
 
 
23
  "Karachi", "Lahore", "Islamabad", "Rawalpindi", "Faisalabad",
24
- "Multan", "Peshawar", "Quetta", "Hyderabad", "Sialkot", "Bahawalpur"
25
  ]
26
 
27
- # --- Simple mock forecast generator ---
28
- def get_mock_forecast(city, days):
29
- if not city or days <= 0:
30
- return "❌ Please select a city and valid number of days."
 
 
 
 
 
 
 
 
 
31
 
32
- forecasts = []
33
- conditions = ["Sunny", "🌤️ Partly Cloudy", "🌧️ Rainy", "🌩️ Thunderstorm", "❄️ Cold & Dry"]
34
 
35
- today = datetime.now()
36
- for i in range(days):
37
- date = (today + timedelta(days=i)).strftime("%A, %d %b %Y")
38
-
39
- # Random but reasonable temperatures for Pakistan
40
- temp_min = random.randint(10, 25)
41
- temp_max = temp_min + random.randint(5, 15)
42
-
43
- condition = random.choice(conditions)
44
- forecasts.append(f"{date} {condition}, {temp_min}°C to {temp_max}°C")
 
 
45
 
46
- return "\n".join(forecasts)
 
 
47
 
48
  # --- Gradio UI ---
49
  with gr.Blocks() as demo:
50
- gr.Markdown("## 🌦️ Weather Forecast App for Pakistan (Demo)")
51
 
52
  with gr.Row():
53
- city = gr.Dropdown(pak_cities, label="Select City", value="Karachi")
54
- days = gr.Slider(1, 7, value=3, step=1, label="Forecast Days")
55
 
56
- forecast_btn = gr.Button("Get Forecast")
57
  output = gr.Textbox(label="Forecast", lines=8)
58
 
59
- forecast_btn.click(get_mock_forecast, inputs=[city, days], outputs=output)
60
 
61
- # Launch app
62
  if __name__ == "__main__":
63
  demo.launch()
 
1
  """
2
+ app.py - Real Weather Forecast App for Pakistan Cities
3
+ -------------------------------------------------------
4
+ This Gradio app fetches live weather forecasts using OpenWeatherMap API.
 
5
 
6
+ 🔑 REQUIREMENT: You need a free API key from https://openweathermap.org/api
7
+ - Sign up, get the key, and paste it below where it says YOUR_API_KEY_HERE.
8
+ - Free tier allows 60 calls/minute (sufficient for testing).
9
 
10
  How to run on Hugging Face Spaces:
11
+ 1. Add 'gradio' and 'requests' in requirements.txt
12
+ 2. Paste your API key in the variable API_KEY below
13
+ 3. Upload app.py + requirements.txt to your Space
14
+ 4. Run it — you’ll get real-time forecasts for Pakistan cities.
15
  """
16
 
17
  import gradio as gr
18
+ import requests
19
+ from datetime import datetime
20
 
21
+ # --- Put your free OpenWeatherMap API key here ---
22
+ API_KEY = "YOUR_API_KEY_HERE" # 🔑 Replace with your real key
23
+ BASE_URL = "https://api.openweathermap.org/data/2.5/forecast"
24
+
25
+ # --- Supported Pakistan Cities ---
26
+ PAKISTAN_CITIES = [
27
  "Karachi", "Lahore", "Islamabad", "Rawalpindi", "Faisalabad",
28
+ "Multan", "Peshawar", "Quetta", "Hyderabad", "Sialkot"
29
  ]
30
 
31
+ def get_weather(city, days):
32
+ if not API_KEY or API_KEY == "YOUR_API_KEY_HERE":
33
+ return "❌ Please add your OpenWeatherMap API key in the code."
34
+
35
+ params = {
36
+ "q": f"{city},PK", # city + country code
37
+ "appid": API_KEY,
38
+ "units": "metric" # Celsius
39
+ }
40
+
41
+ try:
42
+ response = requests.get(BASE_URL, params=params)
43
+ data = response.json()
44
 
45
+ if data.get("cod") != "200":
46
+ return f"Error: {data.get('message', 'Could not fetch weather')}"
47
 
48
+ forecasts = []
49
+ count = 0
50
+ for entry in data["list"]:
51
+ dt_txt = entry["dt_txt"]
52
+ date = datetime.strptime(dt_txt, "%Y-%m-%d %H:%M:%S")
53
+ if date.hour == 12: # pick daily forecast around noon
54
+ temp = entry["main"]["temp"]
55
+ desc = entry["weather"][0]["description"].title()
56
+ forecasts.append(f"{date.strftime('%A, %d %b %Y')} — {desc}, {temp}°C")
57
+ count += 1
58
+ if count >= days:
59
+ break
60
 
61
+ return "\n".join(forecasts) if forecasts else "No forecast available."
62
+ except Exception as e:
63
+ return f"❌ Error: {str(e)}"
64
 
65
  # --- Gradio UI ---
66
  with gr.Blocks() as demo:
67
+ gr.Markdown("## 🌦️ Pakistan Weather Forecast App (Live API)")
68
 
69
  with gr.Row():
70
+ city = gr.Dropdown(PAKISTAN_CITIES, label="Select City")
71
+ days = gr.Slider(1, 5, value=3, step=1, label="Days (1–5)")
72
 
73
+ btn = gr.Button("Get Forecast")
74
  output = gr.Textbox(label="Forecast", lines=8)
75
 
76
+ btn.click(get_weather, inputs=[city, days], outputs=output)
77
 
78
+ # --- Run app ---
79
  if __name__ == "__main__":
80
  demo.launch()