Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,76 @@
|
|
| 1 |
import json
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
|
|
|
|
|
|
|
|
|
|
| 4 |
with open("titles.json", "r", encoding="utf-8") as f:
|
| 5 |
-
|
| 6 |
|
| 7 |
-
def
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
title="Kent Index API",
|
| 15 |
-
description="
|
| 16 |
)
|
| 17 |
|
| 18 |
if __name__ == "__main__":
|
| 19 |
-
|
|
|
|
| 1 |
import json
|
| 2 |
+
import re
|
| 3 |
import gradio as gr
|
| 4 |
|
| 5 |
+
# ----------------------------
|
| 6 |
+
# Load Kent rubric titles
|
| 7 |
+
# ----------------------------
|
| 8 |
with open("titles.json", "r", encoding="utf-8") as f:
|
| 9 |
+
RAW_TITLES = json.load(f)
|
| 10 |
|
| 11 |
+
def normalize(text: str) -> str:
|
| 12 |
+
text = text.lower()
|
| 13 |
+
text = re.sub(r"[^a-z0-9\s]", " ", text)
|
| 14 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 15 |
+
return text
|
| 16 |
|
| 17 |
+
TITLES = [
|
| 18 |
+
{
|
| 19 |
+
"original": title,
|
| 20 |
+
"norm": normalize(title)
|
| 21 |
+
}
|
| 22 |
+
for title in RAW_TITLES
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
# ----------------------------
|
| 26 |
+
# Search function
|
| 27 |
+
# ----------------------------
|
| 28 |
+
def search(query, top_k=5):
|
| 29 |
+
q = normalize(query)
|
| 30 |
+
|
| 31 |
+
if not q:
|
| 32 |
+
return []
|
| 33 |
+
|
| 34 |
+
scored = []
|
| 35 |
+
for item in TITLES:
|
| 36 |
+
score = 0.0
|
| 37 |
+
|
| 38 |
+
# Strong signal: substring match
|
| 39 |
+
if q in item["norm"]:
|
| 40 |
+
score += 1.0
|
| 41 |
+
|
| 42 |
+
# Weaker signal: token overlap
|
| 43 |
+
q_tokens = set(q.split())
|
| 44 |
+
t_tokens = set(item["norm"].split())
|
| 45 |
+
overlap = len(q_tokens & t_tokens)
|
| 46 |
+
score += overlap * 0.1
|
| 47 |
+
|
| 48 |
+
if score > 0:
|
| 49 |
+
scored.append((score, item["original"]))
|
| 50 |
+
|
| 51 |
+
scored.sort(reverse=True)
|
| 52 |
+
|
| 53 |
+
return [
|
| 54 |
+
{
|
| 55 |
+
"rubric": title,
|
| 56 |
+
"score": round(score, 3)
|
| 57 |
+
}
|
| 58 |
+
for score, title in scored[:int(top_k)]
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
# ----------------------------
|
| 62 |
+
# Gradio interface (API host)
|
| 63 |
+
# ----------------------------
|
| 64 |
+
api = gr.Interface(
|
| 65 |
+
fn=search,
|
| 66 |
+
inputs=[
|
| 67 |
+
gr.Textbox(label="query"),
|
| 68 |
+
gr.Number(label="top_k", value=5)
|
| 69 |
+
],
|
| 70 |
+
outputs="json",
|
| 71 |
title="Kent Index API",
|
| 72 |
+
description="Kent rubric title search (API endpoint)"
|
| 73 |
)
|
| 74 |
|
| 75 |
if __name__ == "__main__":
|
| 76 |
+
api.launch()
|