ArceusInception's picture
Update app.py
156235b verified
raw
history blame
2.47 kB
import gradio as gr
import requests
from huggingface_hub import InferenceClient
import os
def preprocess_city_name_and_generate_insight(city_name):
token = os.getenv("HF_TOKEN")
if not token:
return city_name, "Hugging Face token is not set in the environment variables."
try:
client = InferenceClient(model_id="gpt2", api_token=token)
# Construct the prompt for GPT-2
prompt = f"Generate a short, interesting fact about {city_name} in less than 10 words."
# Make the prediction request
result = client.predict(inputs=prompt)
# Process the result
insight = result[0]['generated_text'].strip() if result else "No insight generated."
except Exception as e:
print(f"Error generating insight: {str(e)}")
insight = "Could not generate insight due to an error."
return city_name, insight
def get_weather(city_name):
corrected_city_name, city_insight = preprocess_city_name_and_generate_insight(city_name)
API_Key = os.getenv("OPENWEATHER_API_KEY")
if not API_Key:
return "API Key is not set. Please set the OPENWEATHER_API_KEY environment variable."
url = f'https://api.openweathermap.org/data/2.5/weather?q={corrected_city_name}&appid={API_Key}&units=metric'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather = data['weather'][0]['description']
temp = data['main']['temp']
humidity = data['main']['humidity']
weather_emoji = "☀️" if "clear" in weather else "☁️" if "cloud" in weather else "🌧️" if "rain" in weather else "❄️" if "snow" in weather else "🌫️"
return (f"In {corrected_city_name}, the weather is currently {weather} {weather_emoji}. "
f"The temperature is a comfy {temp}°C 🌡️. "
f"And the humidity levels are at {humidity}% 💧. "
f"Did you know? {city_insight}")
else:
return "Failed to retrieve data. Please check the city name and try again."
# Defining Gradio interface
iface = gr.Interface(
fn=get_weather,
inputs=gr.Textbox(label="Enter City Name", placeholder="Type here..."),
outputs=gr.Textbox(label="Weather Update"),
title="WeatherAssistantApp",
description="Enter a city name to get a lively description of the current weather, temperature, and humidity."
)
# Launching the interface
iface.launch()