Live-Weather / main.py
Zoro-147's picture
Update main.py
30ce246 verified
raw
history blame
2.12 kB
import gradio as gr
import google.generativeai as genai
import requests
import os
import json
# Configure Gemini
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
model = genai.GenerativeModel('gemini-2.5-flash')
def get_current_weather(location: str) -> str:
"""Get current weather using weatherapi.com"""
api_key = os.getenv("WEATHER_API_KEY")
if not api_key:
return "Weather API key not set"
try:
response = requests.get(
"http://api.weatherapi.com/v1/current.json",
params={"key": api_key, "q": location, "aqi": "no"},
timeout=10
)
response.raise_for_status()
data = response.json()
current = data["current"]
return (
f"Weather in {data['location']['name']}:\n"
f"• Temperature: {current['temp_c']}°C\n"
f"• Condition: {current['condition']['text']}\n"
f"• Humidity: {current['humidity']}%\n"
f"• Wind: {current['wind_kph']} km/h"
)
except Exception as e:
return f"Error fetching weather: {str(e)}"
def process_message(message):
"""Process user message with Gemini"""
# First check if it's a weather request
if "weather" in message.lower():
# Simple extraction - get the last word as location
location = message.split()[-1] if len(message.split()) > 1 else "London"
return get_current_weather(location)
# Otherwise use Gemini
try:
response = model.generate_content(message)
return response.text
except Exception as e:
return f"Gemini error: {str(e)}"
# Gradio Interface
def chat_interface(message, history):
"""Gradio chat function"""
bot_message = process_message(message)
return bot_message
demo = gr.ChatInterface(
fn=chat_interface,
title="MCP Server",
description="Ask about anything or request weather updates",
examples=["What's the weather in Paris?", "Explain quantum computing"]
)
# For Hugging Face Spaces
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)