KAPtechies's picture
Update app.py
6f3e63e verified
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()