import requests import openai import gradio as gr import re import os OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") OPENWEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY") def get_weather(city): url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_API_KEY}&units=metric" response = requests.get(url).json() if response["cod"] == 200: temp = response["main"]["temp"] condition = response["weather"][0]["description"] return f"The temperature in {city} is {temp}°C with {condition}." else: return "City not found." def ask_ai_about_weather(city): weather_info = get_weather(city) response = openai.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a weather assistant, answer using the provided content below from openweather"}, {"role": "user", "content": f"What is the weather in {city}?"}, {"role": "assistant", "content": weather_info} ] ) return response.choices[0].message.content def extract_city_from_query(query): # Pattern to match "weather in CITY" or just "CITY" patterns = [ r"(?:weather in|weather for|weather at|weather of|what is the weather in|how is the weather in)\s+([a-zA-Z\s]+)(?:\?)?", r"^([a-zA-Z\s]+)$" # Just the city name ] for pattern in patterns: match = re.search(pattern, query.lower().strip()) if match: return match.group(1).strip() return None # Wrapper function for Gradio def process_query(query): city = extract_city_from_query(query) if city: try: return ask_ai_about_weather(city) except Exception as e: return f"An error occurred: {str(e)}" else: return "I couldn't determine which city you're asking about. Please provide a city name or ask about the weather in a specific location." # Create Gradio Interface with gr.Blocks(title="Weather Assistant") as demo: gr.Markdown("# Weather Information Center") gr.Markdown("Ask about the weather in any city around the world.") with gr.Row(): with gr.Column(): query_input = gr.Textbox(label="Your Question", placeholder="What is the weather in London?", lines=2) submit_btn = gr.Button("Get Weather") output = gr.Textbox(label="Weather Information", lines=10) submit_btn.click(fn=process_query, inputs=query_input, outputs=output) gr.Examples( examples=[ ["What is the weather in London?"], ["Weather in Tokyo"], ["New York"], ["How is the weather in Lagos?"] ], inputs=query_input ) # Launch the app with public sharing enabled if __name__ == "__main__": demo.launch(share=True) # share=True creates a public URL