| import gradio as gr |
| import requests |
| from datetime import datetime, timedelta |
|
|
| |
| API_KEY = '91b23cab82ee530b2052c8757e343b0d' |
| OPENAI_API_KEY = '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' |
|
|
| def kelvin_to_celsius(temp_kelvin): |
| return temp_kelvin - 273.15 |
|
|
| def get_weather(city_name, api_key): |
| base_url = "http://api.openweathermap.org/data/2.5/weather?" |
| complete_url = base_url + "q=" + city_name + "&appid=" + api_key |
| response = requests.get(complete_url) |
| data = response.json() |
| |
| if data.get("cod") == 200: |
| main_data = data.get("main", {}) |
| weather_data = data.get("weather", [{}])[0] |
| temperature = kelvin_to_celsius(main_data.get("temp", 0)) |
| weather_description = weather_data.get("description", "N/A") |
| timezone = data.get("timezone", 0) |
| |
| |
| local_time = datetime.utcnow() + timedelta(seconds=timezone) |
| formatted_time = local_time.strftime('%H:%M:%S') |
| |
| return temperature, weather_description, formatted_time |
| else: |
| return None |
|
|
| def openai_create(prompt): |
| openai_url = "https://api.openai.com/v1/engines/text-davinci-003/completions" |
| headers = { |
| "Authorization": f"Bearer {OPENAI_API_KEY}", |
| "Content-Type": "application/json" |
| } |
| data = { |
| "prompt": prompt, |
| "temperature": 0.7, |
| "max_tokens": 256, |
| "top_p": 1, |
| "frequency_penalty": 0, |
| "presence_penalty": 0.6, |
| "stop": ["\n"] |
| } |
| response = requests.post(openai_url, headers=headers, json=data) |
| response_data = response.json() |
| summary = response_data['choices'][0]['text'].strip() |
| return summary |
|
|
| def summarize_weather(city1, city2): |
| weather1 = get_weather(city1, API_KEY) |
| weather2 = get_weather(city2, API_KEY) |
| |
| if weather1 and weather2: |
| comparison = f""" |
| Can you provide a concise summary for the following weather information? |
| In {city1}, the current weather is {weather1[1]} with a temperature of {weather1[0]:.2f}°C. The local time is {weather1[2]}. |
| Meanwhile, in {city2}, it's {weather2[1]} and the temperature is {weather2[0]:.2f}°C. The local time there is {weather2[2]}. |
| """ |
| summary = openai_create(comparison) |
| return summary |
| else: |
| return "Error fetching weather data for one or both cities." |
|
|
| |
| interface = gr.Interface( |
| fn=summarize_weather, |
| inputs=[ |
| gr.Textbox(placeholder="Enter City 1 (e.g., New York)"), |
| gr.Textbox(placeholder="Enter City 2 (e.g., Los Angeles)") |
| ], |
| outputs="text" |
| ) |
|
|
| interface.launch() |