Covid-Predict / app.py
Nadeem005's picture
Update app.py
a0558ce verified
Raw History Blame Contribute Delete
4.07 kB
# -*- coding: utf-8 -*-
"""app.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1t4OTspXEXeKN2nCtYeVFhc1fw6wHgzDi
"""
import gradio as gr
import pandas as pd
import numpy as np
import joblib
from datetime import datetime, timedelta
# --- 1. Load Pre-trained Objects ---
# Load the models, feature list, and country list saved from your notebook
model_cases = joblib.load('model_cases.joblib')
model_deaths = joblib.load('model_deaths.joblib')
features = joblib.load('features.joblib')
countries = joblib.load('countries.joblib')
# Load the original dataset to calculate features for new predictions
df = pd.read_csv('train.csv')
df['Date'] = pd.to_datetime(df['Date'])
df['Province/State'] = df['Province/State'].fillna('')
df = df.sort_values(by=['Country/Region', 'Province/State', 'Date'])
df['Country_Code'] = df['Country/Region'].astype('category').cat.codes
# --- 2. Prediction Function ---
# This function takes user input and returns predictions
def predict_covid_cases(country, date_str):
# Convert date string to datetime object
future_date = pd.to_datetime(date_str)
# Get the most recent data available for the selected country
country_data = df[df['Country/Region'] == country].iloc[-1]
# --- 3. Feature Engineering for the Future Date ---
# Create the feature vector for the prediction
feature_vector = {}
# days_since_first_case
first_case_date = df[df['Country/Region'] == country]['Date'].min()
feature_vector['days_since_first_case'] = (future_date - first_case_date).days
# Lag features (using the most recent available data)
feature_vector['ConfirmedCases_lag1'] = country_data['Fatalities'] # Corrected based on your notebook's logic
feature_vector['ConfirmedCases_lag7'] = country_data['Fatalities'] # Corrected based on your notebook's logic
feature_vector['Fatalities_lag1'] = country_data['Fatalities']
feature_vector['Fatalities_lag7'] = country_data['Fatalities']
# Growth rate (simplified for a single prediction point)
# A more complex implementation might forecast this too
recent_growth = (country_data['ConfirmedCases'] - df[(df['Country/Region'] == country)].iloc[-2]['ConfirmedCases']) / (country_data['ConfirmedCases'] + 1)
feature_vector['growth_rate'] = recent_growth if np.isfinite(recent_growth) else 0
# Country Code
feature_vector['Country_Code'] = country_data['Country_Code']
# Create a DataFrame from the feature vector
input_df = pd.DataFrame([feature_vector])
# Ensure columns are in the same order as during training
input_df = input_df[features]
# --- 4. Make Predictions ---
pred_cases = model_cases.predict(input_df)[0]
pred_deaths = model_deaths.predict(input_df)[0]
# Ensure predictions are non-negative integers
pred_cases = max(0, int(pred_cases))
pred_deaths = max(0, int(pred_deaths))
return f"Predicted Confirmed Cases: {pred_cases}", f"Predicted Fatalities: {pred_deaths}"
# --- 5. Create the Gradio Interface ---
with gr.Blocks(theme=gr.themes.Soft(), title="COVID-19 Forecaster") as demo:
gr.Markdown("# 🦠 COVID-19 Cases & Fatalities Forecaster")
gr.Markdown("Select a country and a future date to predict the cumulative number of confirmed cases and fatalities.")
with gr.Row():
country_input = gr.Dropdown(choices=countries, label="Country/Region", value="India")
date_input = gr.Textbox(label="Future Date (YYYY-MM-DD)", value=(datetime.now() + timedelta(days=7)).strftime('%Y-%m-%d'))
predict_btn = gr.Button("Predict")
with gr.Row():
cases_output = gr.Label(label="Cases Prediction")
deaths_output = gr.Label(label="Fatalities Prediction")
predict_btn.click(
fn=predict_covid_cases,
inputs=[country_input, date_input],
outputs=[cases_output, deaths_output]
)
gr.Markdown("---")
gr.Markdown("Project by: [Nadeem Ahmad]")
# --- 6. Launch the App ---
if __name__ == "__main__":
demo.launch()