File size: 3,926 Bytes
40cd83f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import gradio as gr
import requests

# ==============================
# πŸ”‘ API KEY (ADD YOUR KEY HERE)
# ==============================
API_KEY = "b58b4fa298fca72bc2438258de81bb6a"


# ==============================
# 🌀 GET CURRENT WEATHER
# ==============================
def get_current_weather(city, unit):
    try:
        units = "metric" if unit == "Celsius" else "imperial"

        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units={units}"
        response = requests.get(url, timeout=10)
        data = response.json()

        # ❌ Error Handling
        if data.get("cod") != 200:
            return f"❌ Error: {data.get('message')}"

        # βœ… Extract Data
        name = data["name"]
        country = data["sys"]["country"]
        temp = data["main"]["temp"]
        feels_like = data["main"]["feels_like"]
        humidity = data["main"]["humidity"]
        weather = data["weather"][0]["description"]
        wind = data["wind"]["speed"]
        icon = data["weather"][0]["icon"]

        icon_url = f"http://openweathermap.org/img/wn/{icon}@2x.png"

        unit_symbol = "Β°C" if unit == "Celsius" else "Β°F"

        # 🎨 UI Output
        result = f"""
### 🌍 {name}, {country}

![icon]({icon_url})

🌑 **Temperature:** {temp}{unit_symbol}  
πŸ€” **Feels Like:** {feels_like}{unit_symbol}  
πŸ’§ **Humidity:** {humidity}%  
🌬 **Wind Speed:** {wind} m/s  
☁ **Condition:** {weather}
"""
        return result

    except requests.exceptions.Timeout:
        return "❌ Request timed out. Try again."
    except requests.exceptions.ConnectionError:
        return "❌ Network error. Check your internet."
    except Exception as e:
        return f"❌ Unexpected error: {str(e)}"


# ==============================
# πŸ“… 5-DAY FORECAST
# ==============================
def get_forecast(city, unit):
    try:
        units = "metric" if unit == "Celsius" else "imperial"

        url = f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={API_KEY}&units={units}"
        response = requests.get(url, timeout=10)
        data = response.json()

        if data.get("cod") != "200":
            return f"❌ Error: {data.get('message')}"

        forecast_text = "### πŸ“… 5-Day Forecast\n\n"
        unit_symbol = "Β°C" if unit == "Celsius" else "Β°F"

        # Show every 8th entry (~24 hours)
        for i in range(0, len(data["list"]), 8):
            item = data["list"][i]
            date = item["dt_txt"]
            temp = item["main"]["temp"]
            desc = item["weather"][0]["description"]

            forecast_text += f"πŸ“† **{date}**\n🌑 {temp}{unit_symbol} | ☁ {desc}\n\n"

        return forecast_text

    except Exception as e:
        return f"❌ Forecast error: {str(e)}"


# ==============================
# πŸ”„ MAIN FUNCTION
# ==============================
def weather_app(city, unit):
    if not city.strip():
        return "❌ Please enter a city name.", ""

    current = get_current_weather(city, unit)
    forecast = get_forecast(city, unit)

    return current, forecast


# ==============================
# 🎨 GRADIO UI
# ==============================
with gr.Blocks(theme=gr.themes.Soft()) as demo:

    gr.Markdown("# 🌀 Weather App")
    gr.Markdown("Enter a city name to get real-time weather and forecast")

    with gr.Row():
        city_input = gr.Textbox(label="πŸ™ City Name", placeholder="e.g. Karachi")
        unit_input = gr.Radio(["Celsius", "Fahrenheit"], value="Celsius", label="🌑 Unit")

    submit_btn = gr.Button("πŸ” Get Weather")

    with gr.Row():
        current_output = gr.Markdown()
        forecast_output = gr.Markdown()

    # Loading feedback
    submit_btn.click(
        fn=weather_app,
        inputs=[city_input, unit_input],
        outputs=[current_output, forecast_output]
    )

# πŸš€ Launch (Colab Compatible)
demo.launch(share=True)