bonosa
v 1.0
099c29b
import gradio as gr
import requests
import json
import os
def get_weather(city, state, country, units):
API_KEY = os.environ["OPENWEATHERMAP_API_KEY"]
# Combine the city, state, and country into a single string.
location = ",".join(filter(None, [city, state, country]))
response = requests.get(
"https://api.openweathermap.org/data/2.5/weather?q={}&appid={}&units={}".format(location, API_KEY, units)
)
if response.status_code != 200:
return None, None, None, None, "Unable to get weather data. Please check the location name and spelling."
weather_data = json.loads(response.content.decode("utf-8"))
weather_description = weather_data["weather"][0]["description"]
temperature = weather_data["main"]["temp"]
pressure = weather_data["main"]["pressure"]
humidity = weather_data["main"]["humidity"]
return weather_description, temperature, pressure, humidity, None
def app(city: str, state: str, country: str, units: str, show_pressure_humidity: bool):
weather_description, temperature, pressure, humidity, error = get_weather(city, state, country, units)
if error:
return error
temperature_units = "Kelvin"
if units == "metric":
temperature_units = "Celsius"
elif units == "Imperial":
temperature_units = "Fahrenheit"
weather_info = f"The weather in {city} is {weather_description} and the temperature is {temperature} {temperature_units}."
if show_pressure_humidity:
weather_info += f" The pressure is {pressure} hPa and the humidity is {humidity}%."
return weather_info
examples = [
["New York", "", "", "metric", False],
["San Francisco", "CA", "", "metric", False],
["Paris", "Ile-de-France", "France", "metric", True]
]
iface = gr.Interface(fn=app,
inputs=["text", "text", "text",
gr.inputs.Radio(["metric", "Imperial"], label="Temperature Units"),
gr.inputs.Checkbox(label="Show Pressure and Humidity")],
outputs="text",
title="Weather Forecast",
description="Enter a city (and optionally state/province and country) and get the current weather forecast.",
examples=examples)
iface.launch()