Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,142 +1,368 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
-
|
| 4 |
import gradio as gr
|
| 5 |
-
from transformers import pipeline
|
| 6 |
import joblib
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
:root {{ --brand-primary:{BRAND_PRIMARY}; --brand-accent:{BRAND_ACCENT}; --brand-text:{BRAND_TEXT}; --brand-bg:{BRAND_BG}; --hilite-bg:{HILITE_BG}; }}
|
| 14 |
-
.gradio-container {{ font-family: ui-sans-serif, system-ui, Segoe UI, Roboto, Helvetica, Arial; color:var(--brand-text); background:var(--brand-bg); }}
|
| 15 |
-
#hero {{ background: linear-gradient(120deg, #93c5fd 0%, #60a5fa 55%, #3b82f6 100%); color:#fff; border-radius:14px; padding:22px; margin-bottom:12px; display:flex; align-items:center; gap:16px; }}
|
| 16 |
-
#hero .title {{ color:#fff; font-weight:800; font-size:1.55rem; line-height:1.15; text-shadow:0 1px 2px rgba(0,0,0,.2); }}
|
| 17 |
-
#hero .subtitle {{ color:#eef5ff; font-size:.98rem; text-shadow:0 1px 2px rgba(0,0,0,.25); }}
|
| 18 |
-
#hero .pill {{ color:#eaf2ff; background:rgba(255,255,255,.14); border:1px solid rgba(255,255,255,.25); padding:4px 10px; border-radius:999px; font-size:.80rem; }}
|
| 19 |
-
button, .gr-button {{ border-radius:12px !important; font-weight:700 !important; border:0 !important; background:var(--brand-accent) !important; color:#fff !important; }}
|
| 20 |
-
button:hover, .gr-button:hover {{ filter:brightness(1.06); }}
|
| 21 |
-
textarea, input, .gr-textbox, .gr-box {{ border-radius:12px !important; }}
|
| 22 |
-
.markdown-body mark, mark {{ background:var(--hilite-bg); padding:0 .15em; border-radius:.2em; }}
|
| 23 |
-
.card {{ background:#fff; border:1px solid #e5e7eb; border-radius:12px; padding:14px; }}
|
| 24 |
-
.footer-note {{ color:#6b7280; font-size:.85rem; }}
|
| 25 |
-
"""
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
|
|
|
|
|
|
|
|
|
|
| 38 |
APOS = {"’": "'", "‘": "'", "“": '"', "”": '"'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def norm(s: str) -> str:
|
| 40 |
-
|
|
|
|
| 41 |
for k,v in APOS.items(): s = s.replace(k,v)
|
| 42 |
return re.sub(r"\s+", " ", s).strip()
|
| 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 |
else:
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
-
mx = max(o["score"] for o in outs)
|
| 81 |
-
exps = [math.exp(o["score"] - mx) for o in outs]; den = sum(exps) or 1.0
|
| 82 |
-
tops = "\n".join([f"- {o['answer']} (confidence={(exps[i]/den):.1%})" for i,o in enumerate(outs)])
|
| 83 |
-
return ans, highlighted, tops
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
if not cands:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
md_lines.append(f"- {i} (sim={s:.3f}) {snippet}…")
|
| 97 |
-
md = "\n".join(md_lines)
|
| 98 |
-
return ans, hl, tops, md
|
| 99 |
-
|
| 100 |
-
with gr.Blocks(title="Salatus QA — Question-Only (RAG)", css=CSS, theme=gr.themes.Soft(primary_hue="slate", secondary_hue="amber")) as demo:
|
| 101 |
-
with gr.Row():
|
| 102 |
-
gr.HTML("""
|
| 103 |
<div id="hero">
|
| 104 |
-
<div style="font-size:1.
|
| 105 |
<div>
|
| 106 |
-
<
|
| 107 |
-
<
|
|
|
|
|
|
|
|
|
|
| 108 |
</div>
|
| 109 |
-
<div style="margin-left:auto"><span class="pill">RAG Demo</span></div>
|
| 110 |
</div>
|
| 111 |
-
"""
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
with gr.
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
with gr.
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
demo.queue().launch()
|
|
|
|
| 1 |
+
# app.py — Salatus QA (Question-Only RAG, bilingual, bright theme)
|
| 2 |
+
import math, re, json, os
|
| 3 |
from pathlib import Path
|
| 4 |
+
|
| 5 |
import gradio as gr
|
|
|
|
| 6 |
import joblib
|
| 7 |
+
import numpy as np
|
| 8 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 9 |
+
from sklearn.pipeline import make_pipeline
|
| 10 |
+
from sklearn.preprocessing import Normalizer
|
| 11 |
+
from transformers import pipeline
|
| 12 |
|
| 13 |
+
# =========================
|
| 14 |
+
# CONFIG
|
| 15 |
+
# =========================
|
| 16 |
+
# Change this to your model repo if needed (Hugging Face Hub id)
|
| 17 |
+
HF_MODEL = os.getenv("MODEL_REPO", "ChogwuCY/salatus-qa-xlmrb-base")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# Colors (bright header + amber button)
|
| 20 |
+
CSS = """
|
| 21 |
+
:root {
|
| 22 |
+
--brand-primary: #1e3a8a; /* blue-800 */
|
| 23 |
+
--brand-secondary: #0ea5e9;/* sky-500 */
|
| 24 |
+
--brand-accent: #f59e0b; /* amber-500 */
|
| 25 |
+
--brand-bg: #f8fafc; /* slate-50 */
|
| 26 |
+
}
|
| 27 |
|
| 28 |
+
.gradio-container {
|
| 29 |
+
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
|
| 30 |
+
background: var(--brand-bg);
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
#hero {
|
| 34 |
+
background: linear-gradient(100deg, var(--brand-primary), #2563eb 50%, var(--brand-secondary));
|
| 35 |
+
color: #fff;
|
| 36 |
+
border-radius: 16px;
|
| 37 |
+
padding: 18px 20px;
|
| 38 |
+
display: flex;
|
| 39 |
+
align-items: center;
|
| 40 |
+
gap: 14px;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
#hero h1 { margin: 0; font-size: 1.45rem; font-weight: 800; letter-spacing: .2px; }
|
| 44 |
+
#hero p { margin: 2px 0 0; opacity: .95; }
|
| 45 |
+
|
| 46 |
+
.gr-button, button {
|
| 47 |
+
background: var(--brand-accent) !important;
|
| 48 |
+
color: #111 !important;
|
| 49 |
+
font-weight: 800 !important;
|
| 50 |
+
border-radius: 12px !important;
|
| 51 |
+
border: 0 !important;
|
| 52 |
+
}
|
| 53 |
+
.gr-button:hover { filter: brightness(1.05); }
|
| 54 |
+
|
| 55 |
+
.markdown-body mark, mark {
|
| 56 |
+
background: #fff59d;
|
| 57 |
+
padding: 0 .18em;
|
| 58 |
+
border-radius: .2em;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
.card {
|
| 62 |
+
background: #fff;
|
| 63 |
+
border: 1px solid #e5e7eb;
|
| 64 |
+
border-radius: 12px;
|
| 65 |
+
padding: 12px;
|
| 66 |
+
}
|
| 67 |
|
| 68 |
+
textarea, input, .gr-textbox, .gr-box { border-radius: 12px !important; }
|
| 69 |
+
"""
|
| 70 |
|
| 71 |
+
# =========================
|
| 72 |
+
# Utilities: normalisation / cleaning
|
| 73 |
+
# =========================
|
| 74 |
APOS = {"’": "'", "‘": "'", "“": '"', "”": '"'}
|
| 75 |
+
LEAD_STOP = {"maka","oleh","akan","yang","dan","bahawa","adapun","pun","di","ke","dari"}
|
| 76 |
+
TAIL_STOP = {"itu","pun","lah","kah"}
|
| 77 |
+
NAME_PAT = re.compile(
|
| 78 |
+
r"(Raja|Sultan|Tun|Tuan|Puteri|Megat|Hang|Wan)\s+[A-ZĀ-ÿ][^\s,.;]{1,}(?:\s+[A-ZĀ-ÿ][^\s,.;]{1,}){0,3}"
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
def norm(s: str) -> str:
|
| 82 |
+
if not s: return ""
|
| 83 |
+
s = s.replace("\u200b","").replace("\u200c","")
|
| 84 |
for k,v in APOS.items(): s = s.replace(k,v)
|
| 85 |
return re.sub(r"\s+", " ", s).strip()
|
| 86 |
|
| 87 |
+
def clean_edges(text: str) -> str:
|
| 88 |
+
t = text.strip(" .,:;—-")
|
| 89 |
+
toks = t.split()
|
| 90 |
+
while toks and toks[0].lower() in LEAD_STOP: toks = toks[1:]
|
| 91 |
+
while toks and toks[-1].lower() in TAIL_STOP: toks = toks[:-1]
|
| 92 |
+
return " ".join(toks)
|
| 93 |
+
|
| 94 |
+
def answer_sentence(context: str, name: str) -> str:
|
| 95 |
+
# Try to surface a natural clause mentioning name + dikahwinkan
|
| 96 |
+
m = re.search(rf"([^.]{re.escape(name)}[^.]*dikahwinkan[^.]\.)", context, flags=re.I)
|
| 97 |
+
if m:
|
| 98 |
+
s = re.sub(r"\b(Maka|oleh|akan)\b\s*", "", m.group(1), flags=re.I).strip()
|
| 99 |
+
return s
|
| 100 |
+
m2 = re.search(r"dikahwinkan dengan ([^.]*?)\.", context, flags=re.I)
|
| 101 |
+
if m2:
|
| 102 |
+
return f"{name} dikahwinkan dengan {m2.group(1)}."
|
| 103 |
+
return name
|
| 104 |
+
|
| 105 |
+
# =========================
|
| 106 |
+
# Retriever: load (or build from sources) at startup
|
| 107 |
+
# =========================
|
| 108 |
+
RDIR = Path("retriever")
|
| 109 |
+
RDIR.mkdir(exist_ok=True)
|
| 110 |
+
PIPE_PATH = RDIR / "tfidf_pipe.joblib"
|
| 111 |
+
CTX_PATH = RDIR / "contexts.json"
|
| 112 |
+
|
| 113 |
+
def load_or_build_retriever():
|
| 114 |
+
if PIPE_PATH.exists() and CTX_PATH.exists():
|
| 115 |
+
pipe = joblib.load(PIPE_PATH)
|
| 116 |
+
contexts = json.loads(CTX_PATH.read_text(encoding="utf-8"))
|
| 117 |
+
X = pipe.transform(contexts)
|
| 118 |
+
return pipe, contexts, X
|
| 119 |
+
|
| 120 |
+
# Try building from files shipped in repo root
|
| 121 |
+
candidates = [Path("contexts.json"), Path("contexts.jsonl"),
|
| 122 |
+
Path("salatus_qa.json"), Path("salatus_qa.jsonl")]
|
| 123 |
+
seen, contexts = set(), []
|
| 124 |
+
for p in candidates:
|
| 125 |
+
if not p.exists(): continue
|
| 126 |
+
if p.suffix.lower() == ".jsonl":
|
| 127 |
+
with p.open("r", encoding="utf-8") as f:
|
| 128 |
+
for line in f:
|
| 129 |
+
if not line.strip(): continue
|
| 130 |
+
obj = json.loads(line)
|
| 131 |
+
c = norm(obj.get("context",""))
|
| 132 |
+
if len(c) >= 40 and c not in seen:
|
| 133 |
+
seen.add(c); contexts.append(c)
|
| 134 |
+
else:
|
| 135 |
+
data = json.loads(p.read_text(encoding="utf-8"))
|
| 136 |
+
if isinstance(data, list):
|
| 137 |
+
# list of objects with context or list of strings
|
| 138 |
+
for ex in data:
|
| 139 |
+
c = norm(ex["context"] if isinstance(ex, dict) else str(ex))
|
| 140 |
+
if len(c) >= 40 and c not in seen:
|
| 141 |
+
seen.add(c); contexts.append(c)
|
| 142 |
+
if contexts: break
|
| 143 |
+
|
| 144 |
+
if not contexts:
|
| 145 |
+
# tiny fallback (so app still runs)
|
| 146 |
+
contexts = [
|
| 147 |
+
"Maka oleh Raja Aktabu'l-Ard akan Raja Suran dikahwinkan dengan anaknya Tuan Puteri Mahtabu'l-Bahri itu.",
|
| 148 |
+
"Hatta Sultan Alau'd-Din ... pihak Sultan Alau'd-Din, Bendahara yang memerintahkan."
|
| 149 |
+
]
|
| 150 |
+
|
| 151 |
+
vec = TfidfVectorizer(analyzer="word", ngram_range=(1,2), min_df=1)
|
| 152 |
+
pipe = make_pipeline(vec, Normalizer(copy=False))
|
| 153 |
+
X = pipe.fit_transform(contexts)
|
| 154 |
+
# Save for next boot
|
| 155 |
+
joblib.dump(pipe, PIPE_PATH)
|
| 156 |
+
CTX_PATH.write_text(json.dumps(contexts, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 157 |
+
return pipe, contexts, X
|
| 158 |
+
|
| 159 |
+
PIPE, CONTEXTS, X = load_or_build_retriever()
|
| 160 |
+
|
| 161 |
+
def retrieve(query: str, top_k: int = 5, threshold: float = 0.12):
|
| 162 |
+
qv = PIPE.transform([norm(query)])
|
| 163 |
+
sims = (X @ qv.T).toarray().ravel()
|
| 164 |
+
idx = np.argsort(-sims)[:max(1, int(top_k))]
|
| 165 |
+
out = [(int(i), float(sims[i]), CONTEXTS[int(i)]) for i in idx if sims[i] >= threshold]
|
| 166 |
+
return out
|
| 167 |
|
| 168 |
+
# =========================
|
| 169 |
+
# QA pipeline
|
| 170 |
+
# =========================
|
| 171 |
+
qa = pipeline("question-answering", model=HF_MODEL, tokenizer=HF_MODEL)
|
| 172 |
+
|
| 173 |
+
def answer_with_cleaning(q: str, contexts, max_len: int):
|
| 174 |
+
"""
|
| 175 |
+
Run QA on each candidate context; pick the highest-score span.
|
| 176 |
+
Return (short_answer, sentence_answer, highlighted_context, top_candidates_md, retrieved_md)
|
| 177 |
+
"""
|
| 178 |
+
if not contexts:
|
| 179 |
+
return "—", "", "", "—", "—"
|
| 180 |
+
|
| 181 |
+
best = None
|
| 182 |
+
cands_md_lines = []
|
| 183 |
+
for (i, sim, ctx) in contexts:
|
| 184 |
+
outs = qa({"question": q, "context": ctx}, top_k=3, max_answer_len=int(max_len), truncation=True)
|
| 185 |
+
if isinstance(outs, dict): outs = [outs]
|
| 186 |
+
|
| 187 |
+
# top span for this context
|
| 188 |
+
b = max(outs, key=lambda x: x["score"])
|
| 189 |
+
# accumulate candidate spans (softmax for display)
|
| 190 |
+
mx = max(o["score"] for o in outs)
|
| 191 |
+
exps = [math.exp(o["score"] - mx) for o in outs]; den = sum(exps) or 1.0
|
| 192 |
+
for j, o in enumerate(outs[:3]):
|
| 193 |
+
conf = exps[j] / den
|
| 194 |
+
cands_md_lines.append(f"- {o['answer']} (confidence={conf:.1%})")
|
| 195 |
+
|
| 196 |
+
# keep global best
|
| 197 |
+
if (best is None) or (b["score"] > best["score"]):
|
| 198 |
+
best = {"span": b, "ctx": ctx, "idx": i, "sim": sim}
|
| 199 |
+
|
| 200 |
+
raw = best["span"]["answer"]
|
| 201 |
+
s, e = best["span"].get("start", -1), best["span"].get("end", -1)
|
| 202 |
+
|
| 203 |
+
short = clean_edges(raw)
|
| 204 |
+
# prefer titled name near the span
|
| 205 |
+
if isinstance(s, int) and isinstance(e, int) and 0 <= s < e <= len(best["ctx"]):
|
| 206 |
+
window = best["ctx"][max(0, s-30):min(len(best["ctx"]), e+40)]
|
| 207 |
+
m = NAME_PAT.search(window)
|
| 208 |
+
if m: short = m.group(0).strip()
|
| 209 |
+
|
| 210 |
+
# natural sentence (optional)
|
| 211 |
+
sent = answer_sentence(best["ctx"], short) if short else ""
|
| 212 |
+
|
| 213 |
+
# highlight (avoid backslash in f-string expression)
|
| 214 |
+
ctx = best["ctx"]
|
| 215 |
+
pos = ctx.find(short) if short else -1
|
| 216 |
+
if pos != -1:
|
| 217 |
+
highlighted = ctx[:pos] + "<mark>" + short + "</mark>" + ctx[pos+len(short):]
|
| 218 |
else:
|
| 219 |
+
# fallback to the raw span
|
| 220 |
+
raw_span = raw
|
| 221 |
+
highlighted = ctx.replace(raw_span, f"<mark>{raw_span}</mark>", 1) if raw_span else ctx
|
| 222 |
+
|
| 223 |
+
# retrieved list (first 3)
|
| 224 |
+
ret_lines = []
|
| 225 |
+
for (i, sim, _c) in contexts[:3]:
|
| 226 |
+
snip = _c[:120].replace("\n", " ")
|
| 227 |
+
ret_lines.append(f"{i} (sim={sim:.3f}) {snip}…")
|
| 228 |
+
retrieved_md = "\n".join(ret_lines)
|
| 229 |
+
cands_md = "\n".join(cands_md_lines)
|
| 230 |
|
| 231 |
+
return short, sent, highlighted, cands_md, retrieved_md
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
+
# =========================
|
| 234 |
+
# UI text (Malay / English)
|
| 235 |
+
# =========================
|
| 236 |
+
TXT = {
|
| 237 |
+
"ms": {
|
| 238 |
+
"title": "Salatus QA — Question-Only",
|
| 239 |
+
"subtitle": "Masukkan soalan sahaja. Aplikasi memilih konteks terbaik, kemudian mengekstrak jawapan.",
|
| 240 |
+
"tab_demo": "Demo",
|
| 241 |
+
"q": "Soalan / Question",
|
| 242 |
+
"topk": "Bilangan konteks dicadang (top_k)",
|
| 243 |
+
"maxlen": "Maks panjang jawapan (token)",
|
| 244 |
+
"thresh": "Ambang persamaan (retrieval)",
|
| 245 |
+
"ask": "Tanya",
|
| 246 |
+
"best": "Jawapan terbaik",
|
| 247 |
+
"sent": "Jawapan (ayat)",
|
| 248 |
+
"cands": "Calon jawapan (Top-3)",
|
| 249 |
+
"retr": "Konteks terpilih",
|
| 250 |
+
"placeholder_q": "Tulis soalan…",
|
| 251 |
+
"examples": "Contoh pantas",
|
| 252 |
+
"no_ctx": "Maaf, konteks tidak mencukupi. Cuba soalan lain atau turunkan ambang."
|
| 253 |
+
},
|
| 254 |
+
"en": {
|
| 255 |
+
"title": "Salatus QA — Question-Only",
|
| 256 |
+
"subtitle": "Ask a question only. The app retrieves the best passage and extracts the answer.",
|
| 257 |
+
"tab_demo": "Demo",
|
| 258 |
+
"q": "Question",
|
| 259 |
+
"topk": "Number of candidate passages (top_k)",
|
| 260 |
+
"maxlen": "Max answer length (tokens)",
|
| 261 |
+
"thresh": "Similarity threshold (retrieval)",
|
| 262 |
+
"ask": "Ask",
|
| 263 |
+
"best": "Best answer",
|
| 264 |
+
"sent": "Answer (sentence)",
|
| 265 |
+
"cands": "Top-3 candidates",
|
| 266 |
+
"retr": "Selected passages",
|
| 267 |
+
"placeholder_q": "Type your question…",
|
| 268 |
+
"examples": "Quick examples",
|
| 269 |
+
"no_ctx": "No confident passage found. Try another question or lower the threshold."
|
| 270 |
+
}
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
# =========================
|
| 274 |
+
# Gradio App
|
| 275 |
+
# =========================
|
| 276 |
+
def run(q, top_k, max_len, thresh, lang):
|
| 277 |
+
if not q:
|
| 278 |
+
return "—", "", "", "—", "—"
|
| 279 |
+
cands = retrieve(q, int(top_k), float(thresh))
|
| 280 |
if not cands:
|
| 281 |
+
msg = TXT[lang]["no_ctx"]
|
| 282 |
+
return msg, "", "", "—", "—"
|
| 283 |
+
return answer_with_cleaning(q, cands, int(max_len))
|
| 284 |
+
|
| 285 |
+
with gr.Blocks(title="Salatus QA — Question-Only", css=CSS, theme=gr.themes.Soft()) as demo:
|
| 286 |
+
# Header
|
| 287 |
+
gr.HTML(
|
| 288 |
+
f"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
<div id="hero">
|
| 290 |
+
<div style="font-size:1.8rem">🏰</div>
|
| 291 |
<div>
|
| 292 |
+
<h1>{TXT['ms']['title']}</h1>
|
| 293 |
+
<p>{TXT['ms']['subtitle']}</p>
|
| 294 |
+
</div>
|
| 295 |
+
<div style="margin-left:auto; background: rgba(255,255,255,.15); border: 1px solid rgba(255,255,255,.25); padding: 4px 10px; border-radius: 999px;">
|
| 296 |
+
RAG Demo
|
| 297 |
</div>
|
|
|
|
| 298 |
</div>
|
| 299 |
+
"""
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
with gr.Tabs():
|
| 303 |
+
with gr.Tab(TXT["ms"]["tab_demo"]):
|
| 304 |
+
with gr.Row():
|
| 305 |
+
lang = gr.Radio(choices=[("Bahasa Melayu","ms"), ("English","en")],
|
| 306 |
+
value=("Bahasa Melayu","ms"),
|
| 307 |
+
label="Bahasa / Language", interactive=True)
|
| 308 |
+
|
| 309 |
+
with gr.Row():
|
| 310 |
+
q = gr.Textbox(label=TXT["ms"]["q"], lines=2, placeholder=TXT["ms"]["placeholder_q"])
|
| 311 |
+
|
| 312 |
+
with gr.Row():
|
| 313 |
+
top_k = gr.Slider(1, 10, value=5, step=1, label=TXT["ms"]["topk"])
|
| 314 |
+
max_len = gr.Slider(6, 24, value=12, step=1, label=TXT["ms"]["maxlen"])
|
| 315 |
+
thresh = gr.Slider(0.0, 0.4, value=0.12, step=0.01, label=TXT["ms"]["thresh"])
|
| 316 |
+
|
| 317 |
+
ask = gr.Button(TXT["ms"]["ask"], size="lg")
|
| 318 |
+
|
| 319 |
+
with gr.Row():
|
| 320 |
+
ans = gr.Textbox(label=TXT["ms"]["best"], interactive=False)
|
| 321 |
+
with gr.Row():
|
| 322 |
+
sent = gr.Textbox(label=TXT["ms"]["sent"], interactive=False)
|
| 323 |
+
|
| 324 |
+
html = gr.HTML(label="Sorotan / Highlight", elem_classes=["card"])
|
| 325 |
+
tops = gr.Textbox(label=TXT["ms"]["cands"], interactive=False)
|
| 326 |
+
rets = gr.Textbox(label=TXT["ms"]["retr"], interactive=False)
|
| 327 |
+
|
| 328 |
+
# Quick examples (click to auto-fill then click Ask)
|
| 329 |
+
examples = [
|
| 330 |
+
["Siapakah yang dikahwinkan dengan Tuan Puteri Mahtabu’l-Bahri?", 5, 12, 0.12],
|
| 331 |
+
["Siapakah yang memerintahkan pihak Sultan Alau'd-Din?", 5, 12, 0.12],
|
| 332 |
+
]
|
| 333 |
+
eg = gr.Examples(
|
| 334 |
+
examples=[[e[0], e[1], e[2], e[3]] for e in examples],
|
| 335 |
+
inputs=[q, top_k, max_len, thresh],
|
| 336 |
+
label=TXT["ms"]["examples"],
|
| 337 |
+
cache_examples=False
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
def ask(q, top_k_, max_len_, thresh_, lang_tuple):
|
| 341 |
+
# lang comes in as (label,value)
|
| 342 |
+
lang_code = lang_tuple[1] if isinstance(lang_tuple, (tuple, list)) else lang_tuple
|
| 343 |
+
return run(q_, top_k_, max_len_, thresh_, lang_code)
|
| 344 |
+
|
| 345 |
+
ask.click(_ask, inputs=[q, top_k, max_len, thresh, lang], outputs=[ans, sent, html, tops, rets])
|
| 346 |
+
|
| 347 |
+
# Live update labels when language toggles
|
| 348 |
+
def switch_labels(lang_tuple):
|
| 349 |
+
code = lang_tuple[1] if isinstance(lang_tuple, (tuple, list)) else lang_tuple
|
| 350 |
+
T = TXT[code]
|
| 351 |
+
return (
|
| 352 |
+
gr.update(label=T["q"], placeholder=T["placeholder_q"]),
|
| 353 |
+
gr.update(label=T["topk"]),
|
| 354 |
+
gr.update(label=T["maxlen"]),
|
| 355 |
+
gr.update(label=T["thresh"]),
|
| 356 |
+
gr.update(value=T["ask"]),
|
| 357 |
+
gr.update(label=T["best"]),
|
| 358 |
+
gr.update(label=T["sent"]),
|
| 359 |
+
gr.update(label=T["cands"]),
|
| 360 |
+
gr.update(label=T["retr"]),
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
lang.change(
|
| 364 |
+
switch_labels, inputs=[lang],
|
| 365 |
+
outputs=[q, top_k, max_len, thresh, ask, ans, sent, tops, rets]
|
| 366 |
+
)
|
| 367 |
|
| 368 |
demo.queue().launch()
|