oddadmix commited on
Commit
532cbb3
·
verified ·
1 Parent(s): b48e580

Redesign: interactive Docker/FastAPI demo on the routing-head model

Browse files

Editable category rows, live routing as you type, SVG connectors weighted by
probability, six Arabic presets. Serves Nawah-Router-v2 (0.9199, single pass)
instead of pairwise v1 (0.8421, n passes).

Files changed (8) hide show
  1. Dockerfile +9 -0
  2. README.md +16 -15
  3. app.py +53 -138
  4. requirements.txt +0 -3
  5. routing_model.py +85 -0
  6. static/app.js +153 -0
  7. static/index.html +72 -0
  8. static/style.css +83 -0
Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+ ENV PYTHONUNBUFFERED=1 HF_HOME=/tmp/hf TRANSFORMERS_VERBOSITY=error OMP_NUM_THREADS=4
3
+ WORKDIR /app
4
+ RUN pip install --no-cache-dir \
5
+ torch --index-url https://download.pytorch.org/whl/cpu \
6
+ && pip install --no-cache-dir "transformers>=5.15,<6" fastapi "uvicorn[standard]" huggingface_hub
7
+ COPY . /app
8
+ EXPOSE 7860
9
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -3,29 +3,30 @@ title: Nawah Router
3
  emoji: 🧭
4
  colorFrom: green
5
  colorTo: blue
6
- sdk: gradio
7
- sdk_version: 6.26.0
8
- python_version: '3.12'
9
- app_file: app.py
10
  pinned: false
11
  short_description: توجيه عربي صفري — نص + أي فئات تكتبها → الفئة المناسبة
12
  ---
13
 
14
  # Nawah-Router — Arabic zero-shot prompt routing
15
 
16
- Write a text and **any set of categories in plain Arabic**; the model picks one. Categories are
17
- free text supplied at runtime — the model has no fixed taxonomy. Arabic counterpart to
18
- [LFM2.5-Encoder-350M-Prompt-Router](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350-Prompt-Router).
 
 
19
 
20
  | eval set | accuracy | random |
21
  |---|---:|---:|
22
- | unseen category sets | **0.8421** | 0.2525 |
23
- | unseen domains | 0.5813 | 0.2524 |
24
- | deliberately adjacent categories | 0.8096 | 0.2628 |
 
 
 
25
 
26
- Model: [`oddadmix/Nawah-Router-v1`](https://huggingface.co/oddadmix/Nawah-Router-v1) — 51.8M
27
- parameters. Each (text, category) pair is scored independently and the scores are normalised
28
- across the categories you give, so *n* categories means *n* forward passes. Runs on `cpu-basic`.
29
 
30
- `MODEL_HF_TOKEN` is required while the model repo is private (`HF_TOKEN` is reserved by Spaces
31
- and never reaches the container).
 
3
  emoji: 🧭
4
  colorFrom: green
5
  colorTo: blue
6
+ sdk: docker
7
+ app_port: 7860
 
 
8
  pinned: false
9
  short_description: توجيه عربي صفري — نص + أي فئات تكتبها → الفئة المناسبة
10
  ---
11
 
12
  # Nawah-Router — Arabic zero-shot prompt routing
13
 
14
+ Write a text and **any categories in plain Arabic**; the model scores all of them in a single
15
+ forward pass. Categories are free text typed at runtime — the model has no fixed taxonomy.
16
+ Arabic counterpart to [LFM2.5-Encoder-350M-Prompt-Router](https://huggingface.co/LiquidAI/LFM2.5-Encoder-350-Prompt-Router).
17
+
18
+ Edit any category inline, add or remove lanes, and the routing updates as you type.
19
 
20
  | eval set | accuracy | random |
21
  |---|---:|---:|
22
+ | unseen category sets | **0.9199** | 0.2525 |
23
+ | unseen domains | 0.6665 | 0.2524 |
24
+ | deliberately adjacent categories | 0.9149 | 0.2628 |
25
+
26
+ Model: [`oddadmix/Nawah-Router-v2`](https://huggingface.co/oddadmix/Nawah-Router-v2) — 52M
27
+ parameters, CPU-only, one forward pass regardless of how many categories you give it.
28
 
29
+ Confidence is not calibrated: clear cases saturate near 100%. Use the ranking, not the number.
 
 
30
 
31
+ `MODEL_HF_TOKEN` is required while the model repo is private (`HF_TOKEN` is reserved by Spaces and
32
+ never reaches the container).
app.py CHANGED
@@ -1,150 +1,65 @@
1
  """
2
- Nawah-Router demo — Arabic zero-shot prompt routing.
3
 
4
- Layout follows the LFM2.5 prompt-routing demo: prompt on one side, the model in the middle,
5
- categories fanned out on the other, connectors weighted by probability.
6
-
7
- The model scores each (text, category) pair independently and the scores are normalised across
8
- the categories you supply. Categories are free text typed at runtime — nothing about them is
9
- baked into the model.
10
  """
11
- import html
12
  import os
13
  import time
14
 
15
- import gradio as gr
16
  import torch
17
- from transformers import AutoModelForSequenceClassification, AutoTokenizer
 
 
 
 
 
 
18
 
19
- MODEL_ID = os.environ.get("MODEL_ID", "oddadmix/Nawah-Router-v1")
20
  HF_TOKEN = os.environ.get("MODEL_HF_TOKEN") or os.environ.get("HF_TOKEN")
21
- MAX_LENGTH = 160
22
-
23
- print(f"[*] loading {MODEL_ID}")
24
- tok = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
25
- if tok.pad_token_id is None:
26
- tok.pad_token = tok.eos_token
27
- model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID, token=HF_TOKEN).eval()
28
- print(f"[+] {model.num_parameters():,} params")
29
-
30
- CSS = """
31
- .flow{display:grid;grid-template-columns:1fr auto 1.35fr;gap:18px;align-items:center;
32
- font-family:system-ui,-apple-system,'Segoe UI',sans-serif}
33
- .node{background:var(--nd);border:1px solid var(--br);border-radius:10px;padding:14px 16px}
34
- .node .lbl{font-size:10.5px;letter-spacing:.13em;text-transform:uppercase;color:var(--mu);
35
- margin-bottom:7px}
36
- .ptext{direction:rtl;text-align:right;font-size:14.5px;line-height:1.85;color:var(--ink);
37
- max-height:190px;overflow:auto}
38
- .mid{display:flex;flex-direction:column;align-items:center;gap:8px;min-width:120px}
39
- .orb{width:52px;height:52px;border-radius:50%;background:radial-gradient(circle at 35% 30%,
40
- var(--ac),transparent 70%);border:1.5px solid var(--ac);display:grid;place-items:center;
41
- font-size:21px}
42
- .mname{font-size:12.5px;font-weight:600;color:var(--ink)}
43
- .msize{font-size:11px;color:var(--mu)}
44
- .rows{display:flex;flex-direction:column;gap:7px}
45
- .row{position:relative;border:1px solid var(--br);border-radius:8px;padding:9px 12px;
46
- background:var(--nd);overflow:hidden}
47
- .row.top{border-color:var(--ac);box-shadow:0 0 0 1px var(--ac)}
48
- .fill{position:absolute;inset:0 auto 0 0;background:var(--acs);z-index:0}
49
- .row.top .fill{background:var(--act)}
50
- .rc{position:relative;z-index:1;display:flex;align-items:center;gap:10px}
51
- .rname{flex:1;direction:rtl;text-align:right;font-size:13.5px;color:var(--ink);
52
- unicode-bidi:isolate}
53
- .rpct{font-variant-numeric:tabular-nums;font-size:12.5px;font-weight:700;color:var(--mu);
54
- min-width:48px;text-align:right}
55
- .row.top .rpct{color:var(--ac)}
56
- .stats{margin-top:12px;font-size:11.5px;color:var(--mu);display:flex;gap:16px;
57
- font-variant-numeric:tabular-nums}
58
- :root{--nd:#fff;--br:#e3e6e4;--ink:#16201c;--mu:#6b7570;--ac:#1f7a5a;--acs:#eaf4f0;--act:#d6ece2}
59
- @media (prefers-color-scheme:dark){:root{--nd:#171d1a;--br:#2b3531;--ink:#e8eeea;--mu:#93a09a;
60
- --ac:#4fbf95;--acs:#16251f;--act:#1b3a2e}}
61
- """
62
 
63
 
64
- def render(prompt, results, ms, ntok):
65
- if not results:
66
- return "<div class='stats'>اكتب نصًا وفئة واحدة على الأقل.</div>"
67
- top = max(range(len(results)), key=lambda i: results[i][1])
68
- rows = "".join(
69
- f"<div class='row {'top' if i==top else ''}'>"
70
- f"<div class='fill' style='width:{p*100:.1f}%'></div>"
71
- f"<div class='rc'><span class='rname'>{html.escape(c)}</span>"
72
- f"<span class='rpct'>{p*100:.1f}%</span></div></div>"
73
- for i, (c, p) in enumerate(results))
74
- return f"""<style>{CSS}</style>
75
- <div class='flow'>
76
- <div class='node'><div class='lbl'>Prompt · النص</div>
77
- <div class='ptext'>{html.escape(prompt)[:900] or '—'}</div></div>
78
- <div class='mid'><div class='orb'>🧭</div>
79
- <div class='mname'>Nawah-Router</div><div class='msize'>52M · CPU</div></div>
80
- <div class='node'><div class='lbl'>Categories · الفئات</div>
81
- <div class='rows'>{rows}</div>
82
- <div class='stats'><span>{ms} ms</span><span>{ntok} tokens</span>
83
- <span>{len(results)} categories</span></div></div>
84
- </div>"""
85
-
86
-
87
- @torch.no_grad()
88
- def route(prompt, cats_raw):
89
- prompt = (prompt or "").strip()
90
- cats = [c.strip() for c in (cats_raw or "").split("\n") if c.strip()]
91
- if not prompt or not cats:
92
- return render(prompt, [], 0, 0)
93
  t0 = time.perf_counter()
94
- texts = [f"النص: {prompt}\nالفئة: {c}" for c in cats]
95
- enc = tok(texts, return_tensors="pt", padding=True, truncation=True,
96
- max_length=MAX_LENGTH, add_special_tokens=False)
97
- scores = model(**enc).logits.softmax(-1)[:, 1]
98
- probs = (scores / scores.sum()).tolist() if float(scores.sum()) > 0 \
99
- else [1 / len(cats)] * len(cats)
100
- ms = round((time.perf_counter() - t0) * 1000)
101
- return render(prompt, list(zip(cats, probs)), ms, int(enc["input_ids"].numel()))
102
-
103
-
104
- EXAMPLES = [
105
- ["الطلب تأخر أكثر من ساعة عن الموعد والسائق ما رد على الاتصال، وأبغى حل سريع.",
106
- "استفسار عن حالة التوصيل\nشكوى تأخير وتعويض\nمشكلة في الدفع\nتعديل محتويات الطلب"],
107
- ["حاولت أسجل دخول على المنصة وطلع لي خطأ في كلمة المرور رغم إني متأكد منها.",
108
- "مشكلة تقنية في الدخول\nاستفسار عن المناهج والامتحانات\nاستفسار مالي عن الاشتراك"],
109
- ["ممكن تكتب لي قصة قصيرة عن ولد لقي مفتاح قديم في حديقة جده؟",
110
- "برمجة\nكتابة إبداعية\nمعلومات عامة\nترجمة"],
111
- ["ودي أعرف كم باقي في رصيدي وهل الباقة تجدد تلقائي ولا لازم أجددها بنفسي.",
112
- "الرصيد والباقات\nمشاكل الشبكة والتغطية\nتغيير الجهاز أو الشريحة\nأخرى / لا ينطبق"],
113
- ["البيت فيه تسريب مياه تحت الحوض في المطبخ من يومين والأرضية بدأت تتأثر.",
114
- "سباكة وتسريبات\nكهرباء وإنارة\nتكييف وتبريد\nنجارة وأثاث"],
115
- ]
116
-
117
- with gr.Blocks(title="Nawah-Router", theme=gr.themes.Soft()) as demo:
118
- gr.HTML("""<div style="text-align:center">
119
- <h1>🧭 Nawah-Router</h1>
120
- <p>توجيه عربي صفري: اكتب نصًا وأي فئات تريدها، والنموذج يختار الفئة المناسبة.<br>
121
- Arabic zero-shot routing — write a text and <b>any categories you like</b>; the model picks one.</p>
122
- <p><i>الفئات ليست ثابتة في النموذج، اكتب ما تشاء وجرّب. / Categories are free text, defined at runtime.</i></p>
123
- </div>""")
124
- with gr.Row():
125
- with gr.Column(scale=3):
126
- prompt = gr.Textbox(label="النص / Prompt", rtl=True, lines=5,
127
- placeholder="اكتب رسالة أو طلبًا…")
128
- with gr.Column(scale=2):
129
- cats = gr.Textbox(label="الفئات — فئة في كل سطر / Categories — one per line",
130
- rtl=True, lines=5,
131
- placeholder="فئة أولى\nفئة ثانية\nفئة ثالثة")
132
- with gr.Row():
133
- go = gr.Button("🧭 وجّه / Route", variant="primary")
134
- clear = gr.Button("مسح / Clear")
135
- out = gr.HTML()
136
- gr.Examples(examples=EXAMPLES, inputs=[prompt, cats], label="أمثلة / Examples")
137
- gr.Markdown("""### ⚠️ الحدود / Limitations
138
- **0.842** على مجموعات فئات جديدة لم يرها النموذج، مقابل **0.581** على مجالات جديدة كليًا
139
- (baseline عشوائي ≈ 0.25). أي: يعمّم جيدًا على فئات جديدة داخل مجالات مألوفة، وأضعف في مجال
140
- لم يتدرب عليه إطلاقًا.
141
-
142
- **0.842** on unseen category sets vs **0.581** on entirely unseen domains (random ≈ 0.25).
143
- It generalises well to new categories inside familiar verticals, less so to a vertical it never
144
- saw. Trained on Arabic 1–3 line messages; long documents are untested.""")
145
- go.click(route, [prompt, cats], out)
146
- prompt.submit(route, [prompt, cats], out)
147
- clear.click(lambda: ("", "", ""), outputs=[prompt, cats, out])
148
-
149
- if __name__ == "__main__":
150
- demo.queue().launch()
 
1
  """
2
+ Nawah-Router — FastAPI backend for the interactive routing demo.
3
 
4
+ One endpoint. The model scores every supplied category in a single forward pass, so the frontend
5
+ can re-route on each keystroke without a per-category cost.
 
 
 
 
6
  """
 
7
  import os
8
  import time
9
 
 
10
  import torch
11
+ from fastapi import FastAPI
12
+ from fastapi.responses import FileResponse, JSONResponse
13
+ from fastapi.staticfiles import StaticFiles
14
+ from pydantic import BaseModel
15
+ from transformers import AutoTokenizer
16
+
17
+ from routing_model import MAX_ROUTES, RouterModel, build_text, route
18
 
19
+ MODEL_ID = os.environ.get("MODEL_ID", "oddadmix/Nawah-Router-v2")
20
  HF_TOKEN = os.environ.get("MODEL_HF_TOKEN") or os.environ.get("HF_TOKEN")
21
+
22
+ print(f"[*] loading {MODEL_ID}", flush=True)
23
+ TOK = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
24
+ MODEL = RouterModel.from_pretrained(MODEL_ID, token=HF_TOKEN)
25
+ torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", 4)))
26
+ print(f"[+] ready — {sum(p.numel() for p in MODEL.parameters())/1e6:.2f}M params", flush=True)
27
+
28
+ app = FastAPI()
29
+
30
+
31
+ class RouteReq(BaseModel):
32
+ text: str = ""
33
+ cats: list[str] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
 
36
+ @app.get("/")
37
+ def index():
38
+ return FileResponse("static/index.html")
39
+
40
+
41
+ @app.get("/api/ready")
42
+ def ready():
43
+ return {"ready": True, "model": MODEL_ID,
44
+ "params": sum(p.numel() for p in MODEL.parameters()), "max_routes": MAX_ROUTES}
45
+
46
+
47
+ @app.post("/api/route")
48
+ def api_route(req: RouteReq):
49
+ cats = [c.strip() for c in req.cats if c and c.strip()][:MAX_ROUTES]
50
+ text = (req.text or "").strip()
51
+ if not text or not cats:
52
+ return JSONResponse({"results": [], "ms": 0, "tokens": 0})
 
 
 
 
 
 
 
 
 
 
 
 
53
  t0 = time.perf_counter()
54
+ res = route(MODEL, TOK, text, cats)
55
+ full, _ = build_text(text, cats)
56
+ ntok = len(TOK.encode(full, add_special_tokens=False))
57
+ order = {r["route"]: r["score"] for r in res}
58
+ return JSONResponse({
59
+ # returned in the caller's order so the UI does not reshuffle rows under the cursor
60
+ "results": [{"route": c, "score": order.get(c, 0.0)} for c in cats],
61
+ "top": max(range(len(cats)), key=lambda i: order.get(cats[i], 0.0)),
62
+ "ms": round((time.perf_counter() - t0) * 1000), "tokens": ntok})
63
+
64
+
65
+ app.mount("/static", StaticFiles(directory="static"), name="static")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,3 +0,0 @@
1
- torch
2
- transformers>=5.15,<6
3
- gradio
 
 
 
 
routing_model.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference for Nawah-Router-v2 — an Arabic zero-shot router with a routing head.
3
+
4
+ The text and every category share one sequence. Each category's character span is mapped to token
5
+ indices through the tokenizer's offset mapping and mean-pooled into its own vector; a shared
6
+ scorer turns each into one logit, and the softmax runs over the categories actually supplied.
7
+ Because the scorer is shared across positions it reads category *content*, not slot index — which
8
+ is what makes the label set free text chosen at inference.
9
+
10
+ Layout is text-first, categories-second on purpose. The backbone is causal, so this ordering is
11
+ what lets every category token attend to the whole text; reversed, the categories would be
12
+ encoded blind to it.
13
+ """
14
+ import torch
15
+ import torch.nn as nn
16
+ from transformers import AutoModel, AutoTokenizer
17
+
18
+ MAX_ROUTES = 9
19
+ MAX_LENGTH = 320
20
+
21
+
22
+ class RouterModel(nn.Module):
23
+ def __init__(self, base_model):
24
+ super().__init__()
25
+ self.backbone = AutoModel.from_pretrained(base_model, dtype=torch.float32)
26
+ h = self.backbone.config.hidden_size
27
+ self.score = nn.Sequential(nn.Linear(h, h), nn.GELU(), nn.Linear(h, 1))
28
+ self.config = self.backbone.config
29
+
30
+ def forward(self, input_ids, attention_mask, cat_pool, n_routes):
31
+ hs = self.backbone(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
32
+ logits = self.score(torch.bmm(cat_pool.to(hs.dtype), hs)).squeeze(-1)
33
+ ar = torch.arange(logits.size(1), device=logits.device)[None, :]
34
+ return logits.masked_fill(ar >= n_routes[:, None], torch.finfo(logits.dtype).min)
35
+
36
+ @classmethod
37
+ def from_pretrained(cls, path, token=None):
38
+ import os
39
+ from huggingface_hub import hf_hub_download
40
+ m = cls(path)
41
+ w = (os.path.join(path, "router_model.pt") if os.path.isdir(path)
42
+ else hf_hub_download(path, "router_model.pt", token=token))
43
+ m.load_state_dict(torch.load(w, map_location="cpu", weights_only=True))
44
+ return m.eval()
45
+
46
+
47
+ def build_text(text, routes):
48
+ head = f"النص:\n{text}\n\nالفئات:\n"
49
+ s, spans = head, []
50
+ for c in routes:
51
+ s += "- "
52
+ spans.append((len(s), len(s) + len(c)))
53
+ s += c + "\n"
54
+ return s, spans
55
+
56
+
57
+ @torch.no_grad()
58
+ def route(model, tok, text, routes):
59
+ """-> [{'route': str, 'score': float}] sorted high to low."""
60
+ routes = [r for r in routes if r and r.strip()][:MAX_ROUTES]
61
+ if not text.strip() or not routes:
62
+ return []
63
+ full, spans = build_text(text, routes)
64
+ enc = tok(full, return_offsets_mapping=True, add_special_tokens=False,
65
+ truncation=True, max_length=MAX_LENGTH)
66
+ ids, offs = enc["input_ids"], enc["offset_mapping"]
67
+ pool = torch.zeros(1, MAX_ROUTES, len(ids))
68
+ for ci, (s, e) in enumerate(spans):
69
+ idx = [t for t, (a, b) in enumerate(offs) if a < e and b > s and a != b]
70
+ if idx:
71
+ pool[0, ci, idx] = 1.0 / len(idx)
72
+ logits = model(torch.tensor([ids]), torch.ones(1, len(ids), dtype=torch.long),
73
+ pool, torch.tensor([len(routes)]))
74
+ probs = logits.softmax(-1)[0][: len(routes)].tolist()
75
+ out = [{"route": r, "score": p} for r, p in zip(routes, probs)]
76
+ return sorted(out, key=lambda x: -x["score"])
77
+
78
+
79
+ if __name__ == "__main__":
80
+ M = "oddadmix/Nawah-Router-v2"
81
+ tok = AutoTokenizer.from_pretrained(M)
82
+ model = RouterModel.from_pretrained(M)
83
+ for r in route(model, tok, "الطلب تأخر ساعة والسائق ما رد على الاتصال",
84
+ ["استفسار عن التوصيل", "شكوى تأخير", "مشكلة في الدفع"]):
85
+ print(f"{r['score']:.3f} {r['route']}")
static/app.js ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Nawah-Router demo — editable categories, live routing, connectors weighted by probability. */
2
+ const $ = id => document.getElementById(id);
3
+
4
+ const PRESETS = [
5
+ { name: "توجيه مساعد ذكي",
6
+ text: "عندي كود بايثون بيطلع خطأ عند قراءة ملف CSV كبير، ممكن تشوف السبب وتظبطه؟",
7
+ cats: ["مهمة برمجية بسيطة", "مهمة برمجية معقدة", "ترجمة", "كتابة إبداعية",
8
+ "بحث عن معلومة مباشرة", "محادثة عابرة"] },
9
+ { name: "فرز خدمة العملاء",
10
+ text: "الطلب تأخر ساعة ونصف عن الموعد والسائق ما رد على الاتصال، وأبغى تعويض عن التأخير.",
11
+ cats: ["شكوى غاضبة تحتاج تصعيدًا فوريًا", "استفسار عادي غير مستعجل",
12
+ "طلب استرجاع مبلغ", "رسالة شكر وثناء", "رسالة مزعجة إعلانية"] },
13
+ { name: "تصنيف المحتوى",
14
+ text: "بعد شهرين من الاستخدام اليومي، جودة الصوت ممتازة لكن البطارية لا تدوم أكثر من خمس ساعات.",
15
+ cats: ["مراجعة منتج", "خبر اقتصادي", "إعلان تجاري", "مقال رأي", "محتوى تقني متقدم"] },
16
+ { name: "تعقيد الطلب",
17
+ text: "أحتاج خطة كاملة لترحيل قاعدة بيانات من MySQL إلى PostgreSQL مع الحفاظ على البيانات وبدون توقف الخدمة.",
18
+ cats: ["طلب بسيط ومباشر", "يحتاج خطوتين أو ثلاثًا", "طلب معقّد متعدد الخطوات",
19
+ "يحتاج نموذجًا أكبر"] },
20
+ { name: "أي أداة نستدعي",
21
+ text: "كم صار سعر صرف الدولار مقابل الجنيه اليوم؟",
22
+ cats: ["بحث في الويب", "حاسبة", "تقويم ومواعيد", "قاعدة بيانات", "لا يحتاج أداة"] },
23
+ { name: "دعم فني",
24
+ text: "ما أقدر أسجل دخول للحساب، يطلع لي أن كلمة المرور غلط مع إني متأكد منها.",
25
+ cats: ["مشكلة في الدخول إلى الحساب", "استفسار عن الفاتورة", "طلب ميزة جديدة",
26
+ "بلاغ عطل حرج يوقف الخدمة", "أخرى / لا ينطبق"] },
27
+ ];
28
+
29
+ let rows = []; // [{el, input, fill, pct}]
30
+ let timer = null, seq = 0;
31
+
32
+ function cats() {
33
+ return rows.map(r => r.input.value.trim());
34
+ }
35
+
36
+ function addRow(value = "", focus = false) {
37
+ const el = document.createElement("div");
38
+ el.className = "row";
39
+ el.innerHTML = `<div class="fill" style="width:0%"></div>
40
+ <input type="text" value="" placeholder="اسم الفئة…">
41
+ <span class="pct">—</span>
42
+ <button class="del" type="button" title="حذف">×</button>`;
43
+ const input = el.querySelector("input");
44
+ input.value = value;
45
+ input.addEventListener("input", schedule);
46
+ el.querySelector(".del").addEventListener("click", () => {
47
+ rows = rows.filter(r => r.el !== el);
48
+ el.remove(); drawWires(); schedule();
49
+ });
50
+ $("rows").appendChild(el);
51
+ rows.push({ el, input, fill: el.querySelector(".fill"), pct: el.querySelector(".pct") });
52
+ if (focus) input.focus();
53
+ drawWires();
54
+ }
55
+
56
+ function setPreset(p, btn) {
57
+ document.querySelectorAll(".preset").forEach(b => b.classList.remove("on"));
58
+ if (btn) btn.classList.add("on");
59
+ $("text").value = p.text;
60
+ $("rows").innerHTML = ""; rows = [];
61
+ p.cats.forEach(c => addRow(c));
62
+ updateCount(); schedule(0);
63
+ }
64
+
65
+ /* Connectors: prompt -> model -> each category, thickness and opacity carrying the score.
66
+ Redrawn on resize and whenever rows change, since row heights move. */
67
+ function drawWires(scores) {
68
+ const svg = $("wires"), stage = svg.parentElement;
69
+ if (window.innerWidth <= 900) { svg.innerHTML = ""; return; }
70
+ const S = stage.getBoundingClientRect();
71
+ const P = $("promptcard").getBoundingClientRect();
72
+ const N = $("node").getBoundingClientRect();
73
+ const rtl = getComputedStyle(document.body).direction === "rtl";
74
+ // in RTL the prompt sits on the right, so wires run right-to-left
75
+ const px = (rtl ? P.left : P.right) - S.left, py = P.top + P.height / 2 - S.top;
76
+ const nIn = (rtl ? N.right : N.left) - S.left, nOut = (rtl ? N.left : N.right) - S.left;
77
+ const ny = N.top + N.height / 2 - S.top;
78
+ let d = `<path d="M ${px} ${py} C ${(px + nIn) / 2} ${py}, ${(px + nIn) / 2} ${ny}, ${nIn} ${ny}"
79
+ fill="none" stroke="var(--acc-line)" stroke-width="2" opacity=".7"/>`;
80
+ rows.forEach((r, i) => {
81
+ const R = r.el.getBoundingClientRect();
82
+ const cx = (rtl ? R.right : R.left) - S.left, cy = R.top + R.height / 2 - S.top;
83
+ const s = scores ? scores[i] : null;
84
+ const w = s == null ? 1.2 : 1 + s * 4.5;
85
+ const o = s == null ? .3 : .18 + s * .72;
86
+ d += `<path d="M ${nOut} ${ny} C ${(nOut + cx) / 2} ${ny}, ${(nOut + cx) / 2} ${cy}, ${cx} ${cy}"
87
+ fill="none" stroke="var(--acc-line)" stroke-width="${w.toFixed(2)}"
88
+ opacity="${o.toFixed(2)}" stroke-linecap="round"/>`;
89
+ });
90
+ svg.setAttribute("viewBox", `0 0 ${S.width} ${S.height}`);
91
+ svg.innerHTML = d;
92
+ }
93
+
94
+ function updateCount() { $("charcount").textContent = $("text").value.length; }
95
+
96
+ function schedule(delay = 260) {
97
+ updateCount();
98
+ clearTimeout(timer);
99
+ timer = setTimeout(run, delay);
100
+ }
101
+
102
+ async function run() {
103
+ const text = $("text").value.trim(), cs = cats().filter(Boolean);
104
+ if (!text || !cs.length) {
105
+ rows.forEach(r => { r.fill.style.width = "0%"; r.pct.textContent = "—";
106
+ r.el.classList.remove("top"); });
107
+ $("stats").textContent = ""; drawWires(); return;
108
+ }
109
+ const my = ++seq;
110
+ $("orb").classList.add("busy");
111
+ try {
112
+ const res = await fetch("/api/route", {
113
+ method: "POST", headers: { "Content-Type": "application/json" },
114
+ body: JSON.stringify({ text, cats: cats() })
115
+ });
116
+ const data = await res.json();
117
+ if (my !== seq) return; // a newer keystroke already superseded this
118
+ const byName = new Map(data.results.map(r => [r.route, r.score]));
119
+ const scores = rows.map(r => byName.get(r.input.value.trim()) ?? 0);
120
+ const top = scores.indexOf(Math.max(...scores));
121
+ rows.forEach((r, i) => {
122
+ const s = scores[i];
123
+ r.fill.style.width = (s * 100).toFixed(1) + "%";
124
+ r.pct.textContent = (s * 100).toFixed(1) + "%";
125
+ r.el.classList.toggle("top", i === top && s > 0);
126
+ });
127
+ $("stats").textContent = `${data.ms} ms · ${data.tokens} توكن · ${cs.length} فئة`;
128
+ drawWires(scores);
129
+ } catch (e) {
130
+ $("stats").textContent = "تعذّر الاتصال";
131
+ } finally {
132
+ if (my === seq) $("orb").classList.remove("busy");
133
+ }
134
+ }
135
+
136
+ $("text").addEventListener("input", () => schedule());
137
+ $("add").addEventListener("click", () => { addRow("", true); schedule(); });
138
+ window.addEventListener("resize", () => drawWires());
139
+
140
+ PRESETS.forEach((p, i) => {
141
+ const b = document.createElement("button");
142
+ b.className = "preset"; b.type = "button"; b.textContent = p.name;
143
+ b.addEventListener("click", () => setPreset(p, b));
144
+ $("presets").appendChild(b);
145
+ if (i === 0) setTimeout(() => setPreset(p, b), 0);
146
+ });
147
+
148
+ fetch("/api/ready").then(r => r.json()).then(d => {
149
+ $("dot").classList.add("on");
150
+ $("modelname").textContent = d.model.split("/").pop();
151
+ $("modelsize").textContent = (d.params / 1e6).toFixed(1) + "M";
152
+ $("nodemeta").textContent = `CPU · مسار واحد · حتى ${d.max_routes} فئات`;
153
+ }).catch(() => { $("modelname").textContent = "غير متصل"; });
static/index.html ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="ar" dir="rtl">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>Nawah-Router — توجيه عربي صفري</title>
6
+ <meta name="viewport" content="width=device-width,initial-scale=1">
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap">
10
+ <link rel="stylesheet" href="/static/style.css">
11
+ </head>
12
+ <body>
13
+ <div class="wrap">
14
+
15
+ <header>
16
+ <div class="brand">
17
+ <span class="logo">🧭</span>
18
+ <div>
19
+ <h1>Nawah&#8209;Router</h1>
20
+ <p class="sub">توجيه عربي صفري — اكتب نصًا وأي فئات تريدها، والنموذج يوزّعها في مسار واحد.</p>
21
+ </div>
22
+ </div>
23
+ <div class="modelchip" id="modelchip">
24
+ <span class="dot" id="dot"></span>
25
+ <span id="modelname">…</span>
26
+ <span class="mono" id="modelsize"></span>
27
+ </div>
28
+ </header>
29
+
30
+ <section class="presets" id="presets"></section>
31
+
32
+ <main class="stage">
33
+ <svg class="wires" id="wires" aria-hidden="true"></svg>
34
+
35
+ <article class="card prompt" id="promptcard">
36
+ <label for="text">النص</label>
37
+ <textarea id="text" rows="9" placeholder="اكتب رسالة أو طلبًا هنا…"></textarea>
38
+ <div class="hint mono"><span id="charcount">0</span> حرف</div>
39
+ </article>
40
+
41
+ <article class="node" id="node">
42
+ <span class="node-lbl">النموذج</span>
43
+ <div class="orb" id="orb"><span></span></div>
44
+ <div class="node-name">Nawah-Router</div>
45
+ <div class="node-meta mono" id="nodemeta">CPU · مسار واحد</div>
46
+ </article>
47
+
48
+ <article class="card cats" id="catcard">
49
+ <div class="cats-head">
50
+ <label>الفئات</label>
51
+ <div class="stats mono" id="stats"></div>
52
+ </div>
53
+ <div id="rows"></div>
54
+ <button class="add" id="add" type="button">+ أضف فئة</button>
55
+ </article>
56
+ </main>
57
+
58
+ <footer>
59
+ <p>
60
+ الفئات ليست ثابتة في النموذج — اكتب أي فئة تريدها وسيوزّع النص عليها فورًا.
61
+ الدقة <strong>0.92</strong> على مجموعات فئات جديدة، و<strong>0.67</strong> على مجالات لم يرها
62
+ النموذج إطلاقًا (التخمين العشوائي ≈ 0.25). الثقة غير مُعايَرة: اعتمد على الترتيب لا على النسبة.
63
+ </p>
64
+ <p class="mono links">
65
+ <a href="https://huggingface.co/oddadmix/Nawah-Router-v2" target="_blank" rel="noopener">النموذج</a> ·
66
+ <a href="https://huggingface.co/datasets/oddadmix/arabic-prompt-routing" target="_blank" rel="noopener">البيانات</a>
67
+ </p>
68
+ </footer>
69
+ </div>
70
+ <script src="/static/app.js"></script>
71
+ </body>
72
+ </html>
static/style.css ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root{
2
+ --bg:#f6f7f9; --card:#fff; --rule:#e4e7ec; --ink:#141a20; --dim:#6b7684;
3
+ --acc:#1f7a5a; --acc-soft:#e8f3ee; --acc-line:#8fd0b8;
4
+ --warm:#b4762a; --shadow:0 1px 2px rgba(20,26,32,.04),0 12px 32px -20px rgba(20,26,32,.35);
5
+ }
6
+ @media (prefers-color-scheme:dark){
7
+ :root{--bg:#0d1114; --card:#151b20; --rule:#242c33; --ink:#e6ecf1; --dim:#8b98a5;
8
+ --acc:#4fbf95; --acc-soft:#14261f; --acc-line:#2f6f59;
9
+ --shadow:0 1px 2px rgba(0,0,0,.4),0 12px 32px -20px rgba(0,0,0,.8);}
10
+ }
11
+ *{box-sizing:border-box}
12
+ body{margin:0;background:var(--bg);color:var(--ink);
13
+ font-family:"IBM Plex Sans Arabic",system-ui,sans-serif;font-size:15px;line-height:1.7}
14
+ .mono{font-family:"IBM Plex Mono",ui-monospace,monospace;font-variant-numeric:tabular-nums}
15
+ .wrap{max-width:1180px;margin:0 auto;padding:26px 20px 60px;display:flex;flex-direction:column;gap:20px}
16
+
17
+ header{display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap}
18
+ .brand{display:flex;gap:13px;align-items:center}
19
+ .logo{font-size:31px;line-height:1}
20
+ h1{margin:0;font-size:25px;font-weight:700;letter-spacing:-.02em}
21
+ .sub{margin:2px 0 0;color:var(--dim);font-size:13.5px;max-width:62ch}
22
+ .modelchip{display:flex;align-items:center;gap:9px;background:var(--card);border:1px solid var(--rule);
23
+ border-radius:99px;padding:7px 15px;font-size:13px;box-shadow:var(--shadow)}
24
+ .dot{width:8px;height:8px;border-radius:50%;background:var(--warm);flex:none}
25
+ .dot.on{background:var(--acc);box-shadow:0 0 0 4px var(--acc-soft)}
26
+ .modelchip .mono{color:var(--dim);font-size:12px}
27
+
28
+ .presets{display:flex;gap:8px;flex-wrap:wrap}
29
+ .preset{background:var(--card);border:1px solid var(--rule);border-radius:99px;padding:6px 14px;
30
+ font-size:13px;cursor:pointer;color:var(--ink);font-family:inherit;transition:.15s}
31
+ .preset:hover{border-color:var(--acc);color:var(--acc)}
32
+ .preset.on{background:var(--acc);border-color:var(--acc);color:#fff}
33
+ .preset:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
34
+
35
+ .stage{position:relative;display:grid;grid-template-columns:1fr 168px 1.25fr;gap:20px;align-items:start}
36
+ @media (max-width:900px){.stage{grid-template-columns:1fr}.wires{display:none}}
37
+ .wires{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:0}
38
+ .card,.node{position:relative;z-index:1;background:var(--card);border:1px solid var(--rule);
39
+ border-radius:14px;box-shadow:var(--shadow)}
40
+ .card{padding:16px 18px}
41
+ label{font-size:11px;font-weight:600;letter-spacing:.1em;color:var(--dim);text-transform:uppercase}
42
+ textarea{width:100%;margin-top:9px;border:1px solid var(--rule);border-radius:9px;background:transparent;
43
+ color:var(--ink);padding:12px;font-family:inherit;font-size:15px;line-height:1.9;resize:vertical}
44
+ textarea:focus{outline:none;border-color:var(--acc);box-shadow:0 0 0 3px var(--acc-soft)}
45
+ .hint{margin-top:7px;color:var(--dim);font-size:11.5px}
46
+
47
+ .node{padding:18px 12px;display:flex;flex-direction:column;align-items:center;gap:7px;
48
+ align-self:center;text-align:center}
49
+ .node-lbl{font-size:10px;letter-spacing:.12em;color:var(--dim);text-transform:uppercase}
50
+ .orb{width:58px;height:58px;border-radius:50%;border:1.5px solid var(--acc);display:grid;place-items:center;
51
+ background:radial-gradient(circle at 34% 30%,var(--acc-soft),transparent 72%)}
52
+ .orb span{width:13px;height:13px;border-radius:50%;background:var(--acc);opacity:.85}
53
+ .orb.busy span{animation:pulse .7s ease-in-out infinite}
54
+ @keyframes pulse{0%,100%{transform:scale(1);opacity:.85}50%{transform:scale(1.75);opacity:.35}}
55
+ .node-name{font-weight:600;font-size:14px}
56
+ .node-meta{font-size:11px;color:var(--dim)}
57
+
58
+ .cats-head{display:flex;justify-content:space-between;align-items:baseline;gap:12px;margin-bottom:11px}
59
+ .stats{font-size:11.5px;color:var(--dim)}
60
+ .row{position:relative;display:flex;align-items:center;gap:9px;border:1px solid var(--rule);
61
+ border-radius:9px;margin-bottom:7px;overflow:hidden;background:var(--card);transition:border-color .18s}
62
+ .row .fill{position:absolute;inset:0 auto 0 0;background:var(--acc-soft);z-index:0;
63
+ transition:width .4s cubic-bezier(.22,1,.36,1)}
64
+ .row.top{border-color:var(--acc)}
65
+ .row input{position:relative;z-index:1;flex:1;min-width:0;border:0;background:transparent;color:var(--ink);
66
+ font-family:inherit;font-size:14px;padding:11px 13px}
67
+ .row input:focus{outline:none}
68
+ .pct{position:relative;z-index:1;font-family:"IBM Plex Mono",monospace;font-size:12.5px;font-weight:500;
69
+ color:var(--dim);min-width:52px;text-align:left;padding-left:4px}
70
+ .row.top .pct{color:var(--acc);font-weight:600}
71
+ .del{position:relative;z-index:1;border:0;background:transparent;color:var(--dim);cursor:pointer;
72
+ font-size:17px;line-height:1;padding:0 12px 2px}
73
+ .del:hover{color:#c0392b}
74
+ .add{margin-top:4px;width:100%;border:1px dashed var(--rule);background:transparent;color:var(--dim);
75
+ border-radius:9px;padding:9px;cursor:pointer;font-family:inherit;font-size:13px;transition:.15s}
76
+ .add:hover{border-color:var(--acc);color:var(--acc)}
77
+
78
+ footer{border-top:1px solid var(--rule);padding-top:16px;color:var(--dim);font-size:12.5px}
79
+ footer p{margin:0 0 6px;max-width:88ch}
80
+ footer strong{color:var(--ink)}
81
+ .links a{color:var(--acc);text-decoration:none}
82
+ .links a:hover{text-decoration:underline}
83
+ @media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}