|
|
import gradio as gr |
|
|
import requests |
|
|
from datetime import datetime, timedelta |
|
|
|
|
|
API_KEY = "91b23cab82ee530b2052c8757e343b0d" |
|
|
|
|
|
def kelvin_to_celsius(temp_kelvin): |
|
|
return int(temp_kelvin - 273.15) |
|
|
|
|
|
def get_weather(city_name): |
|
|
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)).strftime('%H:%M') |
|
|
return temperature, weather_description, local_time |
|
|
else: |
|
|
return None |
|
|
|
|
|
def summarize_weather(first_city, second_city): |
|
|
first_city = ' '.join(word.capitalize() for word in first_city.split()) |
|
|
second_city = ' '.join(word.capitalize() for word in second_city.split()) |
|
|
|
|
|
weather1 = get_weather(first_city) |
|
|
weather2 = get_weather(second_city) |
|
|
|
|
|
if weather1 and weather2: |
|
|
summary = (f"In {first_city} it's {weather1[2]} and {weather1[1]} with {weather1[0]}°C, " |
|
|
f"while in {second_city} it's {weather2[2]} and {weather2[1]} with {weather2[0]}°C.") |
|
|
return summary |
|
|
else: |
|
|
return "Error fetching weather data for one or both cities." |
|
|
|
|
|
|
|
|
theme = gr.Theme.from_hub("gradio/Monochrome") |
|
|
|
|
|
interface = gr.Interface( |
|
|
fn=summarize_weather, |
|
|
inputs=[ |
|
|
gr.Textbox(placeholder="Enter First City", label="First City"), |
|
|
gr.Textbox(placeholder="Enter Second City", label="Second City") |
|
|
], |
|
|
outputs="text", |
|
|
theme=theme, |
|
|
title="Weather Comparison", |
|
|
description="Compare local time and temperature in Celsius between two cities." |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
interface.launch() |