File size: 8,515 Bytes
9924eab
 
 
 
58bcc88
9924eab
58bcc88
 
f70954b
9924eab
58bcc88
ccb7521
9924eab
ccb7521
76ec835
 
2950344
76ec835
 
ccb7521
 
 
 
9924eab
ccb7521
76ec835
 
2950344
ccb7521
 
9924eab
ccb7521
f70954b
 
9924eab
ccb7521
 
9924eab
ccb7521
f70954b
9924eab
f70954b
9924eab
 
 
 
ccb7521
9924eab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccb7521
2950344
 
 
ece65d7
c48a9dd
ece65d7
2950344
9924eab
 
 
 
ece65d7
 
 
 
 
2950344
c48a9dd
ece65d7
 
 
 
 
 
9924eab
ece65d7
 
 
 
 
 
 
 
 
9924eab
596d7d1
 
89a8b83
 
9924eab
 
 
 
89a8b83
 
 
596d7d1
 
89a8b83
 
 
 
 
 
9924eab
89a8b83
 
 
 
 
 
9924eab
 
 
f70954b
 
 
 
 
9924eab
f70954b
 
9924eab
f70954b
 
 
9924eab
f70954b
 
9924eab
f70954b
 
9924eab
 
 
 
f70954b
9924eab
 
 
 
 
2950344
 
9924eab
 
 
c48a9dd
9924eab
 
80ebef1
2950344
9924eab
2950344
9924eab
 
1dac411
9924eab
 
 
 
 
 
 
 
 
ece65d7
2950344
9924eab
 
1dac411
 
9924eab
 
 
 
ece65d7
 
2950344
9924eab
2950344
 
 
 
 
ccb7521
 
 
 
2950344
9924eab
58bcc88
9924eab
3a02f0d
8c765ff
 
 
b0894d3
8c765ff
 
 
 
b0894d3
8c765ff
3a02f0d
 
 
 
 
b0894d3
3a02f0d
 
 
 
b0894d3
3a02f0d
 
58bcc88
2950344
 
 
 
ccb7521
303d43b
d84a612
9924eab
2950344
ece65d7
ccb7521
596d7d1
 
 
9924eab
2950344
 
 
 
 
 
 
ccb7521
2950344
ece65d7
d84a612
9924eab
ccb7521
9924eab
ccb7521
9924eab
ccb7521
9924eab
ccb7521
9924eab
f70954b
9924eab
ccb7521
d84a612
9924eab
 
 
 
 
f70954b
ccb7521
9924eab
 
 
62f81ec
 
ccb7521
9924eab
ccb7521
2950344
ccb7521
d84a612
2950344
9924eab
 
 
ccb7521
76ec835
9924eab
 
 
58bcc88
 
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# ====================================================
# app.py β€” State School Fuzzy Matcher (Village Enabled)
# ====================================================

import os
import json
import pandas as pd
import gradio as gr
from functools import lru_cache
from huggingface_hub import hf_hub_download

# ----------------------------------------------------
# External search logic
# ----------------------------------------------------
from searchschool import (
    search_candidates,
    on_search_web,
)

# ----------------------------------------------------
# CONFIG
# ----------------------------------------------------
HF_SCHOOLS_DATASET = "Apf-AI4Good/Schools"
STATE_HIERARCHY_PARQUET = "state_district_block_villages.parquet"

ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", None)
if not ADMIN_PASSWORD:
    print("⚠ ADMIN_PASSWORD not set")

# ----------------------------------------------------
# Load hierarchy ONCE from Hugging Face (Parquet)
# ----------------------------------------------------
@lru_cache(maxsize=1)
def load_state_hierarchy():
    parquet_path = hf_hub_download(
        repo_id=HF_SCHOOLS_DATASET,
        repo_type="dataset",
        filename=STATE_HIERARCHY_PARQUET,
    )

    df = pd.read_parquet(parquet_path)

    required_cols = {"State", "District", "Block", "Village"}
    missing = required_cols - set(df.columns)
    if missing:
        raise ValueError(f"Missing columns in parquet: {missing}")

    hier = {}
    for _, r in df.iterrows():
        hier \
            .setdefault(r["State"], {}) \
            .setdefault(r["District"], {}) \
            .setdefault(r["Block"], set()) \
            .add(r["Village"])

    # Convert sets β†’ sorted lists
    for s in hier:
        for d in hier[s]:
            for b in hier[s][d]:
                hier[s][d][b] = sorted(hier[s][d][b])

    return hier


STATE_HIER = load_state_hierarchy()
STATE_CHOICES = sorted(STATE_HIER.keys())

# ----------------------------------------------------
# UI RENDER HELPERS
# ----------------------------------------------------
def render_results_md(df, show_score=True):
    if df is None or df.empty:
        return "❌ No results found."

    headers = [
        "School Name", "UDISE Code",
        "State", "District", "Block", "Village"
    ]
    if show_score:
        headers.append("Score")

    md = "| " + " | ".join(headers) + " |\n"
    md += "| " + " | ".join(["---"] * len(headers)) + " |\n"

    for _, r in df.iterrows():
        row = [
            str(r.get("School_Name", "")),
            str(r.get("UDISE_Code", "")),
            str(r.get("State", "")),
            str(r.get("District", "")),
            str(r.get("Block", "")),
            str(r.get("Village", "")),
        ]
        if show_score:
            score = r.get("Score", "")
            row.append("" if pd.isna(score) else f"{float(score):.2f}")

        md += "| " + " | ".join(row) + " |\n"

    return md


def render_best_md(df):
    if df is None or df.empty:
        return "❌ No confident best match found."

    headers = [
        "School Name", "UDISE Code",
        "State", "District", "Block", "Village", "Score"
    ]

    md = "| " + " | ".join(headers) + " |\n"
    md += "| " + " | ".join(["---"] * len(headers)) + " |\n"

    r = df.iloc[0]
    row = [
        str(r.get("School_Name", "")),
        str(r.get("UDISE_Code", "")),
        str(r.get("State", "")),
        str(r.get("District", "")),
        str(r.get("Block", "")),
        str(r.get("Village", "")),
        f"{float(r.get('Score', 0)):.2f}",
    ]

    md += "| " + " | ".join(row) + " |\n"
    return md

# ----------------------------------------------------
# Cascading dropdown handlers
# ----------------------------------------------------
def on_state_change(state):
    if not state:
        return (
            gr.update(choices=[], value=None),
            gr.update(choices=[], value=None),
            gr.update(choices=[], value=None),
        )

    districts = sorted(STATE_HIER[state].keys())
    return (
        gr.update(choices=districts, value=None),
        gr.update(choices=[], value=None),
        gr.update(choices=[], value=None),
    )


def on_district_change(state, district):
    if not state or not district:
        return (
            gr.update(choices=[], value=None),
            gr.update(choices=[], value=None),
        )

    blocks = sorted(STATE_HIER[state][district].keys())
    return (
        gr.update(choices=blocks, value=None),
        gr.update(choices=[], value=None),
    )


def on_block_change(state, district, block):
    if not state or not district or not block:
        return gr.update(choices=[], value=None)

    villages = STATE_HIER[state][district][block]
    return gr.update(choices=villages, value=None)

# ----------------------------------------------------
# Search wrappers
# ----------------------------------------------------
def rapid_search_and_render(name, state, district, block, village):
    candidates, best = search_candidates(
        query_name=name,
        state=state,
        district=district,
        block=block,
        village=village,
    )
    return (
        render_results_md(candidates, show_score=True),
        render_best_md(best),
    )


def web_search_and_render(name, state, district, block, village):
    results = on_search_web(
        school_name=name,
        state_name=state,
        district=district,
        block=block,
        village=village,
    )
    return render_results_md(results, show_score=False)

# ----------------------------------------------------
# Admin unlock
# ----------------------------------------------------
def unlock_web_search(pwd):
    if pwd == ADMIN_PASSWORD:
        return gr.update(interactive=True), "πŸ”“ Web search unlocked."
    return gr.update(interactive=False), "❌ Invalid password."

# ----------------------------------------------------
# Gradio App
# ----------------------------------------------------
with gr.Blocks(title="State School Fuzzy Matcher") as demo:
    gr.Markdown("# Find School UDISE Code")

    # ---------- Inputs ----------
    with gr.Row():
        state_dd = gr.Dropdown(
            label="State",
            choices=STATE_CHOICES,
            value=None
        )
        district_dd = gr.Dropdown(
            label="District",
            interactive=True,
            value=None
        )

    with gr.Row():
        block_dd = gr.Dropdown(
            label="Block",
            interactive=True,
            value=None
        )
        village_dd = gr.Dropdown(
            label="Village",
            interactive=True,
            value=None
        )


    school_input = gr.Textbox(
        label="School Name",
        placeholder="Enter school name from marksheet",
    )

    search_btn = gr.Button("πŸ” Find Schools")

    # ---------- Rapid Search ----------
    gr.Markdown("### πŸ”Ž Rapid Search Results")
    rapid_results_md = gr.Markdown()

    gr.Markdown("### ⭐ Best Rapid Match")
    best_result_md = gr.Markdown()

    # ---------- Web Search ----------
    gr.Markdown("### 🌐 Web Search (Locked)")
    unlock_pwd = gr.Textbox(
        label="Admin Password",
        type="password",
    )
    unlock_btn = gr.Button("Unlock Web Search")
    web_status = gr.Markdown("")

    search_web_btn = gr.Button("Search Web", interactive=False)
    web_results_md = gr.Markdown()

    # ---------- Wiring ----------
    state_dd.change(
        on_state_change,
        inputs=state_dd,
        outputs=[district_dd, block_dd, village_dd],
    )

    district_dd.change(
        on_district_change,
        inputs=[state_dd, district_dd],
        outputs=[block_dd, village_dd],
    )

    block_dd.change(
        on_block_change,
        inputs=[state_dd, district_dd, block_dd],
        outputs=village_dd,
    )

    search_btn.click(
        rapid_search_and_render,
        inputs=[school_input, state_dd, district_dd, block_dd, village_dd],
        outputs=[rapid_results_md, best_result_md],
    )

    unlock_btn.click(
        unlock_web_search,
        inputs=unlock_pwd,
        outputs=[search_web_btn, web_status],
    )

    search_web_btn.click(
        web_search_and_render,
        inputs=[school_input, state_dd, district_dd, block_dd, village_dd],
        outputs=web_results_md,
    )

# ----------------------------------------------------
# Entry point
# ----------------------------------------------------
if __name__ == "__main__":
    demo.launch()