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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from sklearn.linear_model import LogisticRegression
|
| 5 |
+
from fastai.vision.all import *
|
| 6 |
+
from fastai.vision.all import PILImage
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Load the trained model for image-based fog classification
|
| 10 |
+
learn = load_learner('afog_classifier.pkl')
|
| 11 |
+
labels = learn.dls.vocab
|
| 12 |
+
|
| 13 |
+
# Use environment variables for API keys
|
| 14 |
+
API_KEY = os.environ.get("OPENWEATHER_API_KEY")
|
| 15 |
+
BASE_URL = 'https://api.openweathermap.org/data/2.5/'
|
| 16 |
+
|
| 17 |
+
# Define the prediction function for image-based fog classification
|
| 18 |
+
def predict_image(img):
|
| 19 |
+
img = PILImage.create(img)
|
| 20 |
+
img = img.resize((512, 512))
|
| 21 |
+
pred, pred_idx, probs = learn.predict(img)
|
| 22 |
+
return {labels[i]: float(probs[i]) for i in range(len(labels))}
|
| 23 |
+
|
| 24 |
+
# Function to get weather data
|
| 25 |
+
def get_weather_data(location):
|
| 26 |
+
current_weather_url = f'{BASE_URL}weather?q={location}&appid={API_KEY}&units=metric'
|
| 27 |
+
current_response = requests.get(current_weather_url)
|
| 28 |
+
current_data = current_response.json()
|
| 29 |
+
|
| 30 |
+
current_weather = {
|
| 31 |
+
'temperature': current_data['main']['temp'],
|
| 32 |
+
'feels_like': current_data['main']['feels_like'],
|
| 33 |
+
'description': current_data['weather'][0]['description'],
|
| 34 |
+
'wind_speed': current_data['wind']['speed'],
|
| 35 |
+
'pressure': current_data['main']['pressure'],
|
| 36 |
+
'humidity': current_data['main']['humidity'],
|
| 37 |
+
'visibility': current_data['visibility'] / 1000,
|
| 38 |
+
'dew_point': current_data['main']['temp'] - ((100 - current_data['main']['humidity']) / 5.0)
|
| 39 |
+
}
|
| 40 |
+
return current_weather
|
| 41 |
+
|
| 42 |
+
# Function to train the fog prediction model
|
| 43 |
+
def train_fog_model():
|
| 44 |
+
df = pd.read_csv('fog_weather_data.csv')
|
| 45 |
+
df = pd.get_dummies(df, columns=['Description'], drop_first=True)
|
| 46 |
+
X = df.drop('Fog', axis=1)
|
| 47 |
+
y = df['Fog']
|
| 48 |
+
model = LogisticRegression()
|
| 49 |
+
model.fit(X, y)
|
| 50 |
+
return model, X.columns
|
| 51 |
+
|
| 52 |
+
# Function to predict fog based on weather data
|
| 53 |
+
def predict_fog(model, feature_columns, weather_data):
|
| 54 |
+
new_data = pd.DataFrame({
|
| 55 |
+
'Temperature': [weather_data['temperature']],
|
| 56 |
+
'Feels like': [weather_data['feels_like']],
|
| 57 |
+
'Wind speed': [weather_data['wind_speed']],
|
| 58 |
+
'Pressure': [weather_data['pressure']],
|
| 59 |
+
'Humidity': [weather_data['humidity']],
|
| 60 |
+
'Dew point': [weather_data['dew_point']],
|
| 61 |
+
'Visibility': [weather_data['visibility']]
|
| 62 |
+
})
|
| 63 |
+
|
| 64 |
+
for col in feature_columns:
|
| 65 |
+
if col.startswith('Description_'):
|
| 66 |
+
new_data[col] = 0
|
| 67 |
+
|
| 68 |
+
description_column = f"Description_{weather_data['description'].replace(' ', '_')}"
|
| 69 |
+
if description_column in feature_columns:
|
| 70 |
+
new_data[description_column] = 1
|
| 71 |
+
|
| 72 |
+
prediction = model.predict(new_data)
|
| 73 |
+
return "Foggy weather" if prediction[0] == 1 else "Clear weather"
|
| 74 |
+
|
| 75 |
+
# Function to get 5-day weather forecast
|
| 76 |
+
def get_5day_forecast(location):
|
| 77 |
+
forecast_url = f'{BASE_URL}forecast?q={location}&appid={API_KEY}&units=metric'
|
| 78 |
+
forecast_response = requests.get(forecast_url)
|
| 79 |
+
forecast_data = forecast_response.json()
|
| 80 |
+
|
| 81 |
+
forecast_list = []
|
| 82 |
+
for entry in forecast_data['list']:
|
| 83 |
+
forecast_list.append({
|
| 84 |
+
'date': entry['dt_txt'],
|
| 85 |
+
'temperature': entry['main']['temp'],
|
| 86 |
+
'humidity': entry['main']['humidity'],
|
| 87 |
+
'description': entry['weather'][0]['description']
|
| 88 |
+
})
|
| 89 |
+
return forecast_list
|
| 90 |
+
|
| 91 |
+
# Load the fog prediction model
|
| 92 |
+
fog_model, feature_columns = train_fog_model()
|
| 93 |
+
|
| 94 |
+
# Function to predict current weather and fog
|
| 95 |
+
def predict_current_weather(location):
|
| 96 |
+
try:
|
| 97 |
+
current_weather = get_weather_data(location)
|
| 98 |
+
fog_prediction = predict_fog(fog_model, feature_columns, current_weather)
|
| 99 |
+
|
| 100 |
+
result = f"Current weather in {location}:\n"
|
| 101 |
+
result += f"Temperature: {current_weather['temperature']}°C\n"
|
| 102 |
+
result += f"Feels like: {current_weather['feels_like']}°C\n"
|
| 103 |
+
result += f"Description: {current_weather['description']}\n"
|
| 104 |
+
result += f"Wind speed: {current_weather['wind_speed']} m/s\n"
|
| 105 |
+
result += f"Pressure: {current_weather['pressure']} hPa\n"
|
| 106 |
+
result += f"Humidity: {current_weather['humidity']}%\n"
|
| 107 |
+
result += f"Dew point: {current_weather['dew_point']}°C\n"
|
| 108 |
+
result += f"Visibility: {current_weather['visibility']} km\n"
|
| 109 |
+
result += f"\nFog Prediction: {fog_prediction}"
|
| 110 |
+
|
| 111 |
+
return result
|
| 112 |
+
except Exception as e:
|
| 113 |
+
return f"Error: {str(e)}"
|
| 114 |
+
|
| 115 |
+
# Function to determine transmission power based on combined results
|
| 116 |
+
def determine_transmission_power(image_prediction, weather_prediction, humidity):
|
| 117 |
+
image_class = max(image_prediction, key=image_prediction.get)
|
| 118 |
+
weather_class = "Foggy weather" if weather_prediction == "Foggy weather" else "Clear weather"
|
| 119 |
+
|
| 120 |
+
if humidity > 80: # High humidity increases the likelihood of fog
|
| 121 |
+
if image_class == "Dense_Fog" or weather_class == "Foggy weather":
|
| 122 |
+
return "High"
|
| 123 |
+
elif image_class == "Moderate_Fog":
|
| 124 |
+
return "Medium"
|
| 125 |
+
else:
|
| 126 |
+
return "Normal"
|
| 127 |
+
else:
|
| 128 |
+
if image_class == "Dense_Fog":
|
| 129 |
+
return "Medium"
|
| 130 |
+
elif image_class == "Moderate_Fog":
|
| 131 |
+
return "Normal"
|
| 132 |
+
else:
|
| 133 |
+
return "Normal"
|
| 134 |
+
|
| 135 |
+
# Main function to integrate all functionalities
|
| 136 |
+
def integrated_prediction(image, location):
|
| 137 |
+
# Predict fog from image
|
| 138 |
+
image_prediction = predict_image(image)
|
| 139 |
+
|
| 140 |
+
# Get current weather data and predict fog
|
| 141 |
+
current_weather = get_weather_data(location)
|
| 142 |
+
weather_prediction = predict_fog(fog_model, feature_columns, current_weather)
|
| 143 |
+
|
| 144 |
+
# Get 5-day weather forecast
|
| 145 |
+
forecast = get_5day_forecast(location)
|
| 146 |
+
|
| 147 |
+
# Determine transmission power
|
| 148 |
+
transmission_power = determine_transmission_power(image_prediction, weather_prediction, current_weather['humidity'])
|
| 149 |
+
|
| 150 |
+
# Prepare the result
|
| 151 |
+
result = f"Current Weather and Fog Prediction:\n{predict_current_weather(location)}\n\n"
|
| 152 |
+
result += f"5-Day Weather Forecast:\n{forecast}\n\n"
|
| 153 |
+
result += f"Transmission Power: {transmission_power}"
|
| 154 |
+
|
| 155 |
+
return result
|
| 156 |
+
|
| 157 |
+
# Gradio interface
|
| 158 |
+
with gr.Blocks() as demo:
|
| 159 |
+
gr.Markdown("# Integrated Fog Prediction and Transmission Power Decision")
|
| 160 |
+
|
| 161 |
+
with gr.Row():
|
| 162 |
+
image_input = gr.Image(label="Upload Image")
|
| 163 |
+
location_input = gr.Textbox(label="Enter Location")
|
| 164 |
+
|
| 165 |
+
predict_button = gr.Button("Predict and Determine Transmission Power")
|
| 166 |
+
output = gr.Textbox(label="Prediction and Transmission Power Result")
|
| 167 |
+
|
| 168 |
+
predict_button.click(integrated_prediction, inputs=[image_input, location_input], outputs=output)
|
| 169 |
+
|
| 170 |
+
demo.launch()
|