|
import os |
|
import httpx |
|
import streamlit as st |
|
import urllib.parse |
|
|
|
|
|
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY", "default_openweather_api_key") |
|
HF_TOKEN = os.getenv("HF_TOKEN", "default_hf_token") |
|
|
|
|
|
HF_MODEL_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3" |
|
|
|
|
|
def fetch_weather() -> str: |
|
"""Fetch the weather information for London.""" |
|
city = "London" |
|
encoded_city = urllib.parse.quote(city) |
|
url = f"https://api.openweathermap.org/data/2.5/weather?q={encoded_city}&appid={OPENWEATHER_API_KEY}&units=metric" |
|
|
|
try: |
|
response = httpx.get(url) |
|
response.raise_for_status() |
|
weather_data = response.json() |
|
|
|
|
|
description = weather_data['weather'][0]['description'] |
|
temperature = weather_data['main']['temp'] |
|
humidity = weather_data['main']['humidity'] |
|
wind_speed = weather_data['wind']['speed'] |
|
|
|
|
|
weather_info = ( |
|
f"The current weather in London is {description} with a temperature of {temperature}°C. " |
|
f"The humidity is {humidity}% and the wind speed is {wind_speed} m/s." |
|
) |
|
|
|
|
|
input_text = f"{weather_info} As an expert in weather forecast analysis, please provide an appropriate weather review." |
|
input_text = ''.join(c for c in input_text if c.isprintable()) |
|
|
|
|
|
headers = {"Authorization": f"Bearer {HF_TOKEN}"} |
|
payload = {"inputs": input_text} |
|
response = httpx.post(HF_MODEL_URL, headers=headers, json=payload) |
|
response.raise_for_status() |
|
result = response.json() |
|
|
|
|
|
if isinstance(result, list): |
|
review = result[0].get("generated_text", "No review generated.") |
|
else: |
|
review = "Unexpected response format." |
|
|
|
return weather_info + "\n\n" + review |
|
|
|
except Exception as e: |
|
return f"Error: {e}" |
|
|
|
|
|
st.title("Current Weather Information for London") |
|
|
|
if st.button("Get Weather Information"): |
|
with st.spinner("Processing..."): |
|
try: |
|
|
|
weather_report = fetch_weather() |
|
st.subheader("Current Weather Report for London") |
|
st.write(weather_report) |
|
except Exception as e: |
|
st.error(f"Error fetching weather report: {e}") |
|
|