decodingdatascience commited on
Commit
459dd14
·
verified ·
1 Parent(s): f939e80

Create app.py

Browse files

updating my weather app on hugging space

Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import gradio as gr
4
+
5
+ # ----------------------------------------
6
+ # 1) Read API key from Hugging Face secret
7
+ # (set OPENWEATHER_API_KEY in Space settings)
8
+ # ----------------------------------------
9
+ API_KEY = os.getenv("OPENWEATHER_API_KEY")
10
+
11
+ def get_weather(city: str) -> str:
12
+ """Fetch weather for a given city using OpenWeatherMap API."""
13
+ if not city:
14
+ return "Please enter a city name."
15
+
16
+ if not API_KEY:
17
+ return "API key is not configured. Please contact the app owner."
18
+
19
+ url = (
20
+ "https://api.openweathermap.org/data/2.5/weather"
21
+ f"?q={city}&appid={API_KEY}&units=metric"
22
+ )
23
+
24
+ try:
25
+ response = requests.get(url, timeout=10)
26
+ data = response.json()
27
+
28
+ # Handle API error (e.g., city not found)
29
+ if data.get("cod") != 200:
30
+ message = data.get("message", "Unable to fetch weather data.")
31
+ return f"Error: {message.capitalize()}"
32
+
33
+ temp = data["main"]["temp"]
34
+ description = data["weather"][0]["description"]
35
+
36
+ return f"The current temperature in {city.title()} is {temp}°C with {description}."
37
+
38
+ except requests.exceptions.RequestException as e:
39
+ return f"Network error: {e}"
40
+
41
+ # ----------------------------------------
42
+ # 2) Gradio interface
43
+ # ----------------------------------------
44
+ iface = gr.Interface(
45
+ fn=get_weather,
46
+ inputs=gr.Textbox(label="City", placeholder="e.g., Abu Dhabi"),
47
+ outputs=gr.Textbox(label="Weather Info"),
48
+ title="Arshad Weather App",
49
+ description="Enter a city name to get current weather using OpenWeatherMap.",
50
+ )
51
+
52
+ # Hugging Face Spaces will run this
53
+ if __name__ == "__main__":
54
+ iface.launch()