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import os
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
import folium
|
| 7 |
+
import gradio as gr
|
| 8 |
+
from folium.plugins import MarkerCluster
|
| 9 |
+
|
| 10 |
+
def generate_nursery_data(num=5500):
|
| 11 |
+
np.random.seed(42)
|
| 12 |
+
governorates = ["Cairo", "Alexandria", "Giza", "Aswan", "Luxor", "Dakahlia", "Sharqia", "Qalyubia",
|
| 13 |
+
"Kafr El Sheikh", "Gharbia", "Menoufia", "Beheira", "Ismailia", "Suez", "Port Said", "Damietta",
|
| 14 |
+
"Fayoum", "Beni Suef", "Minya", "Assiut", "Sohag", "Qena", "Red Sea", "New Valley", "Matruh",
|
| 15 |
+
"North Sinai", "South Sinai"]
|
| 16 |
+
df = pd.DataFrame()
|
| 17 |
+
df["Governorate"] = np.random.choice(governorates, num)
|
| 18 |
+
df["Licensed"] = np.random.choice(["Licensed", "Unlicensed"], num, p=[0.62, 0.38])
|
| 19 |
+
df["Unlicensed_Status"] = np.where(df["Licensed"] == "Unlicensed",
|
| 20 |
+
np.random.choice(["No Application", "Licensing in Progress", "License Rejected"], num), "Not Applicable")
|
| 21 |
+
df["Rejection_Reason"] = np.where(df["Unlicensed_Status"] == "License Rejected",
|
| 22 |
+
np.random.choice(["Missing Documents", "Non-compliant Facility", "Safety Violations", "Staff Unqualified", "Others"], num), "Not Applicable")
|
| 23 |
+
df["Ownership"] = np.random.choice(["Rent", "Endowment", "Owned", "Usufruct", "Others"], num, p=[0.3,0.1,0.4,0.15,0.05])
|
| 24 |
+
df["Affiliation"] = np.random.choice(["Governmental", "Private", "CBO", "Individual"], num, p=[0.25,0.35,0.2,0.2])
|
| 25 |
+
df["Total_Classes"] = np.random.randint(1, 10, num)
|
| 26 |
+
df["Avg_Class_Area_sqm"] = np.random.normal(25, 5, num).round(1)
|
| 27 |
+
df["Avg_Children_Per_Class"] = np.random.randint(10, 35, num)
|
| 28 |
+
df["Avg_Occupancy_Rate"] = np.random.uniform(0.6, 1.0, num).round(2)
|
| 29 |
+
df["Total_Employees"] = np.random.randint(5, 25, num)
|
| 30 |
+
df["Edu_Staff_to_Children"] = np.random.uniform(0.05, 0.2, num).round(2)
|
| 31 |
+
df["Employee_Support_%"] = np.random.uniform(10, 30, num).round(1)
|
| 32 |
+
df["Employee_Edu_%"] = np.random.uniform(50, 80, num).round(1)
|
| 33 |
+
df["Employee_Admin_%"] = (100 - (df["Employee_Support_%"] + df["Employee_Edu_%"]).clip(upper=100)).round(1)
|
| 34 |
+
for col in ["Academic_Activities", "Languages", "Motor_Sensory", "Music_Theater", "Religious_Education", "Arts_Crafts", "Other_Activities"]:
|
| 35 |
+
df[col] = np.random.choice([True, False], num)
|
| 36 |
+
df["Meal_Subscription"] = np.random.choice(["Yes", "No"], num, p=[0.6, 0.4])
|
| 37 |
+
bins = ["0-50", "50-250", "250-500", "500-1000", "1000-2500", "2500+"]
|
| 38 |
+
df["Meal_Subscription_Value"] = np.where(df["Meal_Subscription"] == "Yes",
|
| 39 |
+
np.random.choice(bins, num, p=[0.05, 0.4, 0.3, 0.15, 0.08, 0.02]), "Not Applicable")
|
| 40 |
+
return df
|
| 41 |
+
|
| 42 |
+
# === Full Dashboard Launcher ===
|
| 43 |
+
def launch_dashboard():
|
| 44 |
+
df = generate_nursery_data()
|
| 45 |
+
|
| 46 |
+
gender_fig = px.pie(names=["Male", "Female"], values=[43, 57], title="Gender Distribution")
|
| 47 |
+
|
| 48 |
+
enrollment_fig = px.bar(
|
| 49 |
+
x=["Enrollment Rate", "Licensed %", "Unlicensed %"],
|
| 50 |
+
y=[10, (df['Licensed'] == 'Licensed').mean()*100, (df['Licensed'] == 'Unlicensed').mean()*100],
|
| 51 |
+
title="Enrollment & Licensing Overview",
|
| 52 |
+
labels={"x": "Metric", "y": "Percentage"},
|
| 53 |
+
text_auto=True
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
counts_fig = px.bar(
|
| 57 |
+
x=["Total Nurseries", "Children Enrolled"],
|
| 58 |
+
y=[5500, 55000],
|
| 59 |
+
title="Total Counts",
|
| 60 |
+
text_auto=True
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
ownership_fig = px.pie(df, names="Ownership", title="Ownership Distribution")
|
| 64 |
+
affiliation_fig = px.pie(df, names="Affiliation", title="Affiliation Distribution")
|
| 65 |
+
|
| 66 |
+
activity_cols = ["Academic_Activities", "Languages", "Motor_Sensory", "Music_Theater", "Religious_Education", "Arts_Crafts", "Other_Activities"]
|
| 67 |
+
activity_counts = df[activity_cols].apply(pd.Series.value_counts).T.rename(columns={True: "Offered", False: "Not Offered"})
|
| 68 |
+
activity_counts["Activity"] = activity_counts.index
|
| 69 |
+
activity_fig = px.bar(activity_counts, x="Activity", y="Offered", title="Activities Offered")
|
| 70 |
+
|
| 71 |
+
meal_fig = px.histogram(df[df["Meal_Subscription"] == "Yes"], x="Meal_Subscription_Value", title="Meal Subscription Value Distribution")
|
| 72 |
+
classroom_fig = px.histogram(df, x="Avg_Class_Area_sqm", nbins=30, title="Classroom Area Distribution")
|
| 73 |
+
|
| 74 |
+
emp_stack = go.Figure()
|
| 75 |
+
for role in ["Employee_Support_%", "Employee_Edu_%", "Employee_Admin_%"]:
|
| 76 |
+
emp_stack.add_trace(go.Box(y=df[role], name=role))
|
| 77 |
+
emp_stack.update_layout(title="Employee Role Distribution")
|
| 78 |
+
|
| 79 |
+
gov_summary = df.groupby("Governorate").agg(
|
| 80 |
+
Count=("Governorate", "count"),
|
| 81 |
+
Licensed_Rate=("Licensed", lambda x: (x=="Licensed").mean()*100),
|
| 82 |
+
Activity_Score=("Academic_Activities", lambda x: (x.sum() / len(x)) * 100),
|
| 83 |
+
Rejection_Score=("Rejection_Reason", lambda x: (x != 'Not Applicable').mean() * 100)
|
| 84 |
+
).reset_index()
|
| 85 |
+
|
| 86 |
+
gov_summary["Compliance_Tier"] = np.where(
|
| 87 |
+
gov_summary["Licensed_Rate"] < 50, "Low",
|
| 88 |
+
np.where(gov_summary["Licensed_Rate"] < 75, "Medium", "High")
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
gov_bar = px.bar(gov_summary, x="Governorate", y="Licensed_Rate", title="Licensing % by Governorate")
|
| 92 |
+
reject_fig = px.histogram(df[df['Rejection_Reason'] != 'Not Applicable'], x="Governorate", color="Rejection_Reason", title="Rejection Reasons by Governorate")
|
| 93 |
+
lang_fig = px.histogram(df[df['Languages']], x="Governorate", title="Language Activities Offered")
|
| 94 |
+
music_fig = px.histogram(df[df['Music_Theater']], x="Governorate", title="Music & Theater Offered")
|
| 95 |
+
tier_fig = px.bar(gov_summary, x="Governorate", y="Licensed_Rate", color="Compliance_Tier", title="Compliance Score by Governorate")
|
| 96 |
+
|
| 97 |
+
gov_coords = {g: [26.8 + np.random.rand()/2, 30.8 + np.random.rand()/2] for g in df["Governorate"].unique()}
|
| 98 |
+
maps = {}
|
| 99 |
+
for label, col, colors in [
|
| 100 |
+
("Licensing Coverage", "Licensed", {"Licensed": "green", "Unlicensed": "red"}),
|
| 101 |
+
("Ownership Type", "Ownership", {}),
|
| 102 |
+
("Affiliation Type", "Affiliation", {})
|
| 103 |
+
]:
|
| 104 |
+
fmap = folium.Map(location=[26.8, 30.8], zoom_start=6, control_scale=True, tiles='CartoDB positron')
|
| 105 |
+
mcluster = MarkerCluster().add_to(fmap)
|
| 106 |
+
for _, row in df.iterrows():
|
| 107 |
+
gov = row['Governorate']
|
| 108 |
+
coords = gov_coords.get(gov, [26.8, 30.8])
|
| 109 |
+
value = row[col]
|
| 110 |
+
color = colors.get(value, "blue")
|
| 111 |
+
popup = folium.Popup(f"<b>{gov}</b><br>{label}: {value}", max_width=300)
|
| 112 |
+
folium.Marker(location=coords, popup=popup, icon=folium.Icon(color=color)).add_to(mcluster)
|
| 113 |
+
file = f"map_{col}.html"
|
| 114 |
+
fmap.save(file)
|
| 115 |
+
maps[label] = file
|
| 116 |
+
|
| 117 |
+
insights = """
|
| 118 |
+
### Insights & Strategic Interventions
|
| 119 |
+
- **Licensing Focus**: Target Cairo, Giza, and Sharqia with <50% licensed nurseries
|
| 120 |
+
- **Facility Improvement**: Prioritize Governorates with smaller average classroom area (<22 sqm)
|
| 121 |
+
- **Rejection Reduction**: Most frequent reasons: 'Safety Violations' and 'Staff Unqualified'
|
| 122 |
+
- **Activity Gaps**: Arts, Music, and Sensory activities need boosting in rural areas
|
| 123 |
+
- **Staffing Ratios**: Recommend raising educational staff-to-child ratios above 0.12 minimum
|
| 124 |
+
|
| 125 |
+
### Priority Interventions by Tier:
|
| 126 |
+
- **Urgent** (Low Compliance): Cairo, Qalyubia — fast-track licensing, safety training
|
| 127 |
+
- **Strategic** (Medium Compliance): Beheira, Minya — curriculum and activity upgrade
|
| 128 |
+
- **Maintain** (High Compliance): Luxor, Red Sea — monitoring and recognition
|
| 129 |
+
|
| 130 |
+
### Expected Impact:
|
| 131 |
+
- Increase licensing compliance by 20% in 6 months
|
| 132 |
+
- Improve readiness of 1,500 nurseries via safety/teacher interventions
|
| 133 |
+
- Boost developmental outcomes by expanding educational offerings
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
with gr.Blocks() as demo:
|
| 137 |
+
gr.Markdown("# 🇪🇬 Egypt Nursery Dashboard – July 2025")
|
| 138 |
+
charts = [gender_fig, enrollment_fig, counts_fig, ownership_fig, affiliation_fig, activity_fig,
|
| 139 |
+
meal_fig, classroom_fig, emp_stack, gov_bar, reject_fig, lang_fig, music_fig, tier_fig]
|
| 140 |
+
titles = ["Gender Distribution", "Enrollment & Licensing Overview", "Total Counts", "Ownership", "Affiliation",
|
| 141 |
+
"Activities Offered", "Meal Pricing", "Classroom Area", "Employee Roles", "Licensing by Governorate",
|
| 142 |
+
"Rejection Reasons", "Language Activities", "Music & Theater", "Compliance Tier"]
|
| 143 |
+
for title, fig in zip(titles, charts):
|
| 144 |
+
gr.Markdown(f"## {title}")
|
| 145 |
+
gr.Plot(fig)
|
| 146 |
+
|
| 147 |
+
gr.Markdown("## Interactive Maps")
|
| 148 |
+
for label, file in maps.items():
|
| 149 |
+
gr.Markdown(f"### {label}")
|
| 150 |
+
with open(file, 'r', encoding='utf-8') as f:
|
| 151 |
+
html = f.read().replace("'", "'").replace("\n", " ")
|
| 152 |
+
gr.HTML(f"<iframe srcdoc='{html}' width='100%' height='500' style='border:none;'></iframe>")
|
| 153 |
+
|
| 154 |
+
gr.Markdown("## 🧠 Insights & Recommendations")
|
| 155 |
+
gr.Markdown(insights)
|
| 156 |
+
|
| 157 |
+
demo.launch()
|
| 158 |
+
|
| 159 |
+
launch_dashboard()be pasted here shortly...
|