File size: 2,330 Bytes
3115702
 
 
cea0cbb
3115702
099c29b
3115702
099c29b
 
 
3115702
 
099c29b
3115702
 
 
099c29b
3115702
 
 
 
 
 
 
 
df2d243
3115702
099c29b
 
df2d243
 
 
3115702
858423e
3115702
 
29c4f54
3115702
 
 
 
 
 
 
 
 
099c29b
 
 
 
 
 
3115702
099c29b
29c4f54
099c29b
3115702
 
099c29b
 
3115702
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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()