File size: 5,395 Bytes
2e8b17e |
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 135 136 |
import gradio as gr
import requests
import pandas as pd
from sklearn.linear_model import LogisticRegression
import os
# Use environment variables for API keys
API_KEY = os.environ.get("OPENWEATHER_API_KEY")
BASE_URL = 'https://api.openweathermap.org/data/2.5/'
def get_weather_data(location):
current_weather_url = f'{BASE_URL}weather?q={location}&appid={API_KEY}&units=metric'
current_response = requests.get(current_weather_url)
current_data = current_response.json()
current_weather = {
'temperature': current_data['main']['temp'],
'feels_like': current_data['main']['feels_like'],
'description': current_data['weather'][0]['description'],
'wind_speed': current_data['wind']['speed'],
'pressure': current_data['main']['pressure'],
'humidity': current_data['main']['humidity'],
'visibility': current_data['visibility'] / 1000,
'dew_point': current_data['main']['temp'] - ((100 - current_data['main']['humidity']) / 5.0)
}
return current_weather
def train_fog_model():
df = pd.read_csv('fog_weather_data.csv')
df = pd.get_dummies(df, columns=['Description'], drop_first=True)
X = df.drop('Fog', axis=1)
y = df['Fog']
model = LogisticRegression()
model.fit(X, y)
return model, X.columns
def predict_fog(model, feature_columns, weather_data):
new_data = pd.DataFrame({
'Temperature': [weather_data['temperature']],
'Feels like': [weather_data['feels_like']],
'Wind speed': [weather_data['wind_speed']],
'Pressure': [weather_data['pressure']],
'Humidity': [weather_data['humidity']],
'Dew point': [weather_data['dew_point']],
'Visibility': [weather_data['visibility']]
})
for col in feature_columns:
if col.startswith('Description_'):
new_data[col] = 0
description_column = f"Description_{weather_data['description'].replace(' ', '_')}"
if description_column in feature_columns:
new_data[description_column] = 1
prediction = model.predict(new_data)
return "Foggy weather" if prediction[0] == 1 else "Clear weather"
# Load the model once when the app starts
fog_model, feature_columns = train_fog_model()
def predict_current_weather(location):
try:
current_weather = get_weather_data(location)
fog_prediction = predict_fog(fog_model, feature_columns, current_weather)
result = f"Current weather in {location}:\n"
result += f"Temperature: {current_weather['temperature']}°C\n"
result += f"Feels like: {current_weather['feels_like']}°C\n"
result += f"Description: {current_weather['description']}\n"
result += f"Wind speed: {current_weather['wind_speed']} m/s\n"
result += f"Pressure: {current_weather['pressure']} hPa\n"
result += f"Humidity: {current_weather['humidity']}%\n"
result += f"Dew point: {current_weather['dew_point']}°C\n"
result += f"Visibility: {current_weather['visibility']} km\n"
result += f"\nFog Prediction: {fog_prediction}"
return result
except Exception as e:
return f"Error: {str(e)}"
def predict_custom_weather(temperature, feels_like, wind_speed, pressure, humidity, visibility, description):
try:
weather_data = {
'temperature': temperature,
'feels_like': feels_like,
'wind_speed': wind_speed,
'pressure': pressure,
'humidity': humidity,
'visibility': visibility,
'description': description,
'dew_point': temperature - ((100 - humidity) / 5.0)
}
fog_prediction = predict_fog(fog_model, feature_columns, weather_data)
result = "Custom weather prediction:\n"
result += f"Fog Prediction: {fog_prediction}"
return result
except Exception as e:
return f"Error: {str(e)}"
# Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Weather and Fog Prediction")
with gr.Tab("Current Weather Prediction"):
location_input = gr.Textbox(label="Enter Location")
predict_button = gr.Button("Predict Weather")
output = gr.Textbox(label="Prediction Result")
predict_button.click(predict_current_weather, inputs=location_input, outputs=output)
with gr.Tab("Custom Weather Prediction"):
with gr.Row():
temperature = gr.Number(label="Temperature (°C)")
feels_like = gr.Number(label="Feels Like (°C)")
wind_speed = gr.Number(label="Wind Speed (m/s)")
pressure = gr.Number(label="Pressure (hPa)")
with gr.Row():
humidity = gr.Number(label="Humidity (%)")
visibility = gr.Number(label="Visibility (km)")
description = gr.Dropdown(label="Weather Description", choices=["clear sky", "few clouds", "scattered clouds", "broken clouds", "shower rain", "rain", "thunderstorm", "snow", "mist"])
custom_predict_button = gr.Button("Predict Fog")
custom_output = gr.Textbox(label="Prediction Result")
custom_predict_button.click(
predict_custom_weather,
inputs=[temperature, feels_like, wind_speed, pressure, humidity, visibility, description],
outputs=custom_output
)
demo.launch() |