ECD / app.py
Nagaraj81's picture
Update app.py
760474d verified
# === EGYPT EARLY CHILDHOOD DEVELOPMENT AI DASHBOARD ===
# Complete Gradio App with Synthetic Data, AI/ML, and Visualizations
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
import folium
from folium.plugins import MarkerCluster
import gradio as gr
import io
from sklearn.ensemble import RandomForestClassifier, GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, mean_squared_error
# === STEP 1: Generate Synthetic Data ===
n = 5000
governorates = ["Cairo", "Giza", "Alexandria", "Aswan", "Luxor", "Asyut", "Minya", "Fayoum", "Qena", "Sohag", "Beheira", "Sharqia", "Dakahlia", "Gharbia"]
np.random.seed(42)
data = {
"Governorate": np.random.choice(governorates, size=n),
"Latitude": np.random.uniform(22.0, 31.5, size=n),
"Longitude": np.random.uniform(25.0, 35.0, size=n),
"Infrastructure_Score": np.random.randint(1, 6, size=n),
"Staff_Qualification": np.random.randint(1, 6, size=n),
"Governance_Score": np.random.randint(1, 6, size=n),
"Parent_Education_Level": np.random.randint(1, 6, size=n),
"Child_Protection_Score": np.random.randint(1, 6, size=n),
"Curriculum_Standard_Alignment_Score": np.random.uniform(0.4, 1.0, size=n),
"Capacity": np.random.randint(30, 150, size=n),
"Utilization_Rate": np.random.uniform(0.3, 1.0, size=n),
"Public_Perception_Score": np.random.uniform(1.0, 5.0, size=n),
"Staff_Training_Hours": np.random.randint(0, 80, size=n),
"Training_Need_Index": np.random.uniform(0.1, 1.0, size=n),
"Community_Awareness_Level": np.random.randint(1, 6, size=n),
"Interagency_Coordination_Score": np.random.uniform(0.0, 1.0, size=n),
"Policy_Implementation_Delay_Days": np.random.randint(0, 120, size=n),
"Startup_Cost_EGP": np.random.randint(100000, 600000, size=n),
"Monthly_Revenue_EGP": np.random.randint(10000, 60000, size=n),
"Monthly_Operating_Cost_EGP": np.random.randint(7000, 40000, size=n),
"Loan_Accessibility_Score": np.random.uniform(0.0, 1.0, size=n)
}
df = pd.DataFrame(data)
df["ROI_Estimate"] = (df["Monthly_Revenue_EGP"] - df["Monthly_Operating_Cost_EGP"]) * 12 / df["Startup_Cost_EGP"]
df["Curriculum_Compliance_Flag"] = (df["Curriculum_Standard_Alignment_Score"] > 0.75).astype(int)
df["Training_Required_Flag"] = (df["Training_Need_Index"] > 0.6).astype(int)
df["Quality_Index"] = df[["Infrastructure_Score", "Staff_Qualification", "Governance_Score", "Parent_Education_Level", "Child_Protection_Score"]].mean(axis=1)
df["Services_Development_Score"] = df[["Infrastructure_Score", "Governance_Score", "Parent_Education_Level", "Child_Protection_Score"]].mean(axis=1)
df["Expansion_Index"] = df["Utilization_Rate"] * df["Capacity"]
# === STEP 2: Train ML Models ===
clf_curriculum = RandomForestClassifier().fit(df[["Infrastructure_Score", "Staff_Qualification", "Governance_Score"]], df["Curriculum_Compliance_Flag"])
clf_training = RandomForestClassifier().fit(df[["Staff_Qualification", "Staff_Training_Hours", "Training_Need_Index"]], df["Training_Required_Flag"])
reg_perception = GradientBoostingRegressor().fit(df[["Quality_Index", "Community_Awareness_Level"]], df["Public_Perception_Score"])
reg_coordination = GradientBoostingRegressor().fit(df[["Interagency_Coordination_Score", "Governance_Score"]], df["Policy_Implementation_Delay_Days"])
reg_roi = GradientBoostingRegressor().fit(df[["Startup_Cost_EGP", "Monthly_Revenue_EGP", "Monthly_Operating_Cost_EGP", "Loan_Accessibility_Score"]], df["ROI_Estimate"])
# === STEP 3: Enhanced Gradio Dashboard Function ===
def dashboard(governorate):
subset = df[df["Governorate"] == governorate] if governorate else df
fig1 = px.histogram(subset, x="Public_Perception_Score", nbins=20, title="Objective 6: Public Perception (1–5 scale)", labels={"Public_Perception_Score": "Public Perception Score"})
fig2 = px.box(subset, y="Training_Need_Index", title="Objective 5: Staff Training Need (0 = Low, 1 = High)", labels={"Training_Need_Index": "Training Need Index"})
fig3 = px.scatter(subset, x="Interagency_Coordination_Score", y="Policy_Implementation_Delay_Days", title="Objective 7: Interagency Coordination vs Policy Delay", labels={"Interagency_Coordination_Score": "Coordination Score", "Policy_Implementation_Delay_Days": "Delay (Days)"})
fig4 = px.scatter(subset, x="Startup_Cost_EGP", y="ROI_Estimate", color="Loan_Accessibility_Score", title="Objective 8: ROI vs Startup Cost (color = Loan Access)", labels={"Startup_Cost_EGP": "Startup Cost (EGP)", "ROI_Estimate": "Estimated ROI"})
fig5 = px.box(subset, y="Services_Development_Score", title="Objective 3: Services Quality Score (1 = Poor, 5 = Excellent)", labels={"Services_Development_Score": "Services Development Score"})
fig6 = px.histogram(subset, x="Expansion_Index", nbins=30, title="Objective 4: Expansion Pressure (Utilization Γ— Capacity)", labels={"Expansion_Index": "Expansion Need Index"})
# Folium map
folium_map = folium.Map(location=[subset["Latitude"].mean(), subset["Longitude"].mean()], zoom_start=6)
marker_cluster = MarkerCluster().add_to(folium_map)
for _, row in subset.iterrows():
popup = f"""
<b>Gov:</b> {row['Governorate']}<br>
<b>Objective 1 - Quality Index:</b> {row['Quality_Index']:.2f}<br>
<b>Objective 2 - Curriculum:</b> {'βœ”' if row['Curriculum_Compliance_Flag'] else '❌'}<br>
<b>Objective 3 - Services Dev:</b> {row['Services_Development_Score']:.2f}<br>
<b>Objective 4 - Expansion Index:</b> {row['Expansion_Index']:.2f}<br>
<b>Objective 5 - Training Needed:</b> {'βœ”' if row['Training_Required_Flag'] else '❌'}<br>
<b>Objective 8 - ROI:</b> {row['ROI_Estimate']:.2f}<br>
"""
folium.Marker(
location=[row['Latitude'], row['Longitude']],
popup=popup,
icon=folium.Icon(color="blue")
).add_to(marker_cluster)
folium_html = folium_map._repr_html_()
return fig1, fig2, fig3, fig4, fig5, fig6, folium_html
# === STEP 4: Gradio Interface ===
iface = gr.Interface(
fn=dashboard,
inputs=gr.Dropdown(choices=[""] + sorted(df["Governorate"].unique()), label="Governorate"),
outputs=[
gr.Plot(label="Objective 6: Public Perception Distribution"),
gr.Plot(label="Objective 5: Training Need Index"),
gr.Plot(label="Objective 7: Coordination vs Policy Delay"),
gr.Plot(label="Objective 8: ROI vs Startup Cost"),
gr.Plot(label="Objective 3: Services Development Score"),
gr.Plot(label="Objective 4: Expansion Need Index"),
gr.HTML(label="Folium Map: Objectives Overview by Nursery")
],
title="πŸ‡ͺπŸ‡¬ AI Dashboard: Early Childhood Development in Egypt",
description="Visualizes all 8 strategic objectives using synthetic nursery data, AI/ML models, and interactive visualizations."
)
iface.launch()