Memoona648 commited on
Commit
4a43ed5
·
verified ·
1 Parent(s): f5deb0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -40
app.py CHANGED
@@ -3,9 +3,10 @@ from huggingface_hub import InferenceClient
3
  import plotly.express as px
4
  from datetime import datetime
5
  import os
 
6
 
7
  # ------------------- CONFIG -------------------
8
- API_KEY = os.environ["HF_API_KEY"] # Hugging Face secret
9
  MODEL_ID = "duongtruongbinh/smolagents-weather-agent"
10
 
11
  client = InferenceClient(API_KEY)
@@ -13,6 +14,7 @@ client = InferenceClient(API_KEY)
13
  # ------------------- STREAMLIT PAGE -------------------
14
  st.set_page_config(page_title="Weather Forecast App", page_icon="⛅", layout="wide")
15
 
 
16
  mode = st.sidebar.radio("Choose Theme", ["Light", "Dark"])
17
  if mode == "Dark":
18
  st.markdown('<style>body {background-color: #0e1117; color: white;}</style>', unsafe_allow_html=True)
@@ -23,42 +25,51 @@ st.markdown("Enter a city name to get current weather and a 5-day forecast")
23
  city = st.text_input("🌍 Enter city name", "London")
24
 
25
  if city:
26
- try:
27
- response = client(MODEL_ID, {"location": city}) # Correct API call
28
- except Exception as e:
29
- st.error(f"API Error: {e}")
30
- else:
31
- if "error" in response:
32
- st.error("City not found or API issue. Try again!")
33
- else:
34
- # Current weather metrics
35
- st.subheader(f"Current Weather in {city.title()}")
36
- col1, col2, col3, col4 = st.columns(4)
37
- with col1:
38
- st.metric("🌡 Temperature", f"{response['temperature']} °C")
39
- with col2:
40
- st.metric("💧 Humidity", f"{response['humidity']} %")
41
- with col3:
42
- st.metric("🌬 Wind Speed", f"{response['wind_speed']} m/s")
43
- with col4:
44
- st.image(response['icon_url'])
45
-
46
- st.write(f"**Condition:** {response['condition']}")
47
-
48
- # 5-day forecast chart
49
- forecast = response['forecast']
50
- dates = [datetime.fromisoformat(f['datetime']).strftime("%d %b") for f in forecast]
51
- temps = [f['temp'] for f in forecast]
52
-
53
- fig = px.line(
54
- x=dates,
55
- y=temps,
56
- labels={"x": "Date", "y": "Temperature (°C)"},
57
- title=f"5-Day Temperature Forecast for {city.title()}"
58
- )
59
- fig.update_layout(
60
- plot_bgcolor='rgba(0,0,0,0)',
61
- paper_bgcolor='rgba(0,0,0,0)' if mode=='Dark' else 'white',
62
- font_color='white' if mode=='Dark' else 'black'
63
- )
64
- st.plotly_chart(fig, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
3
  import plotly.express as px
4
  from datetime import datetime
5
  import os
6
+ import json
7
 
8
  # ------------------- CONFIG -------------------
9
+ API_KEY = os.environ["HF_API_KEY"] # Hugging Face secret from Spaces
10
  MODEL_ID = "duongtruongbinh/smolagents-weather-agent"
11
 
12
  client = InferenceClient(API_KEY)
 
14
  # ------------------- STREAMLIT PAGE -------------------
15
  st.set_page_config(page_title="Weather Forecast App", page_icon="⛅", layout="wide")
16
 
17
+ # Dark/Light mode
18
  mode = st.sidebar.radio("Choose Theme", ["Light", "Dark"])
19
  if mode == "Dark":
20
  st.markdown('<style>body {background-color: #0e1117; color: white;}</style>', unsafe_allow_html=True)
 
25
  city = st.text_input("🌍 Enter city name", "London")
26
 
27
  if city:
28
+ with st.spinner("Fetching weather data..."):
29
+ try:
30
+ # Call Hugging Face text2text API
31
+ response_text = client.text2text(MODEL_ID, inputs=f"Weather in {city}")["generated_text"]
32
+
33
+ # Attempt to parse JSON from model output
34
+ try:
35
+ response = json.loads(response_text)
36
+ except:
37
+ st.error("Unable to parse weather data. Model output may not be JSON.")
38
+ st.write("Raw output:", response_text)
39
+ response = None
40
+
41
+ if response:
42
+ # Current weather metrics
43
+ st.subheader(f"Current Weather in {city.title()}")
44
+ col1, col2, col3, col4 = st.columns(4)
45
+ with col1:
46
+ st.metric("🌡 Temperature", f"{response['temperature']} °C")
47
+ with col2:
48
+ st.metric("💧 Humidity", f"{response['humidity']} %")
49
+ with col3:
50
+ st.metric("🌬 Wind Speed", f"{response['wind_speed']} m/s")
51
+ with col4:
52
+ st.image(response['icon_url'])
53
+
54
+ st.write(f"**Condition:** {response['condition']}")
55
+
56
+ # 5-day forecast chart
57
+ forecast = response['forecast']
58
+ dates = [datetime.fromisoformat(f['datetime']).strftime("%d %b") for f in forecast]
59
+ temps = [f['temp'] for f in forecast]
60
+
61
+ fig = px.line(
62
+ x=dates,
63
+ y=temps,
64
+ labels={"x": "Date", "y": "Temperature (°C)"},
65
+ title=f"5-Day Temperature Forecast for {city.title()}"
66
+ )
67
+ fig.update_layout(
68
+ plot_bgcolor='rgba(0,0,0,0)',
69
+ paper_bgcolor='rgba(0,0,0,0)' if mode=='Dark' else 'white',
70
+ font_color='white' if mode=='Dark' else 'black'
71
+ )
72
+ st.plotly_chart(fig, use_container_width=True)
73
+
74
+ except Exception as e:
75
+ st.error(f"API Error: {e}")