Adinarayana02's picture
Update app.py
1e3c146 verified
import os
import httpx
import streamlit as st
import urllib.parse
# Retrieve API keys from environment variables
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY", "default_openweather_api_key")
HF_TOKEN = os.getenv("HF_TOKEN", "default_hf_token")
# Initialize Hugging Face API endpoint
HF_MODEL_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
# Define a function to fetch the weather information
def fetch_weather() -> str:
"""Fetch the weather information for London."""
city = "London" # Hardcoded city name
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()
# Extract weather details
description = weather_data['weather'][0]['description']
temperature = weather_data['main']['temp']
humidity = weather_data['main']['humidity']
wind_speed = weather_data['wind']['speed']
# Format the weather information
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."
)
# Generate the review
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())
# Generate the review using the Hugging Face Inference API
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()
# Check if result is a list and handle accordingly
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}"
# Streamlit UI for fetching and displaying weather
st.title("Current Weather Information for London")
if st.button("Get Weather Information"):
with st.spinner("Processing..."):
try:
# Call the fetch_weather function
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}")