File size: 3,890 Bytes
a23359c e4075a6 5af3eab b8115d1 86f4fb8 edbaaa6 86f4fb8 f0adbf9 86f4fb8 6f3e63e 86f4fb8 573a8e6 b7f35c7 4bff71b a23359c b7f35c7 4bff71b a23359c 3252534 86f4fb8 a23359c 19980fe 5af3eab a23359c 3546322 5af3eab 3546322 19980fe 3546322 01c9c42 a23359c 3546322 5af3eab 3546322 5af3eab 0d7b6a9 19980fe 3546322 55ae2fa 3546322 55ae2fa 3546322 55ae2fa 19980fe 3546322 0d7b6a9 55ae2fa 5af3eab 3546322 5af3eab 3546322 5af3eab 3546322 5af3eab 3546322 5af3eab 3546322 5af3eab 3546322 6b8fcc8 55ae2fa 3546322 a23359c 55ae2fa 5af3eab 3546322 5af3eab 55ae2fa a23359c 86f4fb8 |
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 133 134 |
import requests
import gradio as gr
import pandas as pd
import os
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import numpy as np
from datetime import datetime, timedelta
# Load dataset
file_path = "indian_cities_weather_2015.csv"
df = pd.read_csv(file_path)
# Convert Date to Datetime
df['Date'] = pd.to_datetime(df['Date'])
# Encode country names as numbers
le = LabelEncoder()
df['City'] = le.fit_transform(df['City'])
# Extract useful features
df['Hour'] = df['Date'].dt.hour
df['Day'] = df['Date'].dt.day
df['Month'] = df['Date'].dt.month
# Features and Targets
X = df[['Hour', 'Day', 'Month', 'City']]
y = df[['Temperature', 'Humidity', 'Pressure', 'Rain', 'Cloud']]
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train Model
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
var1 = os.getenv("variable_1")
var2 = os.getenv("variable_2")
def get_weather(city):
result = f"{var1}q={city}&appid={var2}&units=metric"
response = requests.get(result).json()
if response.get("cod") != "200":
return "<span style='color:red; font-weight:bold;'>❌ Invalid city name! Please enter a correct city.</span>"
weather_info = {}
# Organizing data by date
for entry in response["list"]:
date = entry["dt_txt"].split(" ")[0] # Extract only the date
time = entry["dt_txt"].split(" ")[1] # Extract only the time
if date not in weather_info:
weather_info[date] = []
weather_info[date].append([
time,
f"{entry['main']['temp']}°C",
f"{entry['main']['humidity']}%",
f"{entry['main']['pressure']} hPa",
f"{entry['wind']['speed']} m/s",
f"{entry['rain']['3h']} mm" if "rain" in entry and "3h" in entry["rain"] else "0 mm",
f"{entry['clouds']['all']}%"
])
# Formatting output as tables inside boxes
markdown_output = "<h2>📅 5-Day Weather Forecast</h2>"
for date, details in weather_info.items():
df = pd.DataFrame(details, columns=["Time", "Temperature", "Humidity", "Pressure", "Wind Speed", "Rain", "Cloud Cover"])
table_html = df.to_html(index=False)
markdown_output += f"""
<div class='weather-box'>
<h3>📆 {date}</h3>
{table_html}
</div>
"""
return markdown_output
# **Adding Background Image and Box Styling**
custom_css = """
body {
background: url('https://images.unsplash.com/photo-1548337138-e87d889cc369?q=80&w=1796&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D.jpg') no-repeat center center fixed;
background-size: cover;
color: black;
}
.gradio-container {
background: rgba(255, 255, 255, 0.6);
padding: 20px;
border-radius: 10px;
}
h1 {
color: black;
text-align: center;
}
.weather-box {
background: rgba(255, 255, 255, 0.9);
border-radius: 10px;
padding: 15px;
margin-bottom: 10px;
box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);
}
table {
width: 100%;
border-collapse: collapse;
background: white;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
th {
background: #4CAF50;
color: white;
}
"""
# Gradio Interface
iface = gr.Interface(
fn=get_weather,
inputs=gr.Textbox(label="🌍 Enter City Name"),
outputs=gr.HTML(),
title="🌤️Climate change model to forecast future weather patterns",
description="Enter a city name to get **temperature, humidity, wind speed, and cloud cover** for the next **5 days** (grouped by date).",
theme="default",
css=custom_css
)
if __name__ == "__main__":
iface.launch()
|