Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +13 -119
- requirements.txt +0 -1
app.py
CHANGED
|
@@ -1,23 +1,23 @@
|
|
| 1 |
"""
|
| 2 |
Bassma v2 inference endpoint — FastAPI on HuggingFace Spaces.
|
| 3 |
|
|
|
|
|
|
|
|
|
|
| 4 |
Endpoints:
|
| 5 |
-
GET /
|
| 6 |
-
POST /verify
|
| 7 |
-
POST /telegram — Telegram webhook for the bot
|
| 8 |
|
| 9 |
Env (set as Space Secrets in the HF UI):
|
| 10 |
-
HF_TOKEN
|
| 11 |
-
BASSMA_API_KEY
|
| 12 |
-
|
| 13 |
"""
|
| 14 |
|
| 15 |
import os
|
| 16 |
-
import time
|
| 17 |
|
| 18 |
import numpy as np
|
| 19 |
-
import
|
| 20 |
-
from fastapi import FastAPI, Header, HTTPException, Request
|
| 21 |
from pydantic import BaseModel
|
| 22 |
from sentence_transformers import SentenceTransformer
|
| 23 |
|
|
@@ -25,7 +25,6 @@ MODEL_ID = "ziadabdullah/bassma-v1"
|
|
| 25 |
|
| 26 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 27 |
API_KEY = os.environ.get("BASSMA_API_KEY")
|
| 28 |
-
TG_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
|
| 29 |
|
| 30 |
print("Loading model...", flush=True)
|
| 31 |
model = SentenceTransformer(MODEL_ID, token=HF_TOKEN)
|
|
@@ -39,14 +38,6 @@ def normalize(text: str) -> str:
|
|
| 39 |
)
|
| 40 |
|
| 41 |
|
| 42 |
-
def cosine(a: str, b: str) -> float:
|
| 43 |
-
embs = model.encode(
|
| 44 |
-
[normalize(a), normalize(b)],
|
| 45 |
-
normalize_embeddings=True, convert_to_numpy=True,
|
| 46 |
-
)
|
| 47 |
-
return float(np.dot(embs[0], embs[1]))
|
| 48 |
-
|
| 49 |
-
|
| 50 |
class VerifyRequest(BaseModel):
|
| 51 |
text_a: str
|
| 52 |
text_b: str
|
|
@@ -70,105 +61,8 @@ def verify(req: VerifyRequest, x_api_key: str = Header(default="")):
|
|
| 70 |
raise HTTPException(status_code=401, detail="invalid api key")
|
| 71 |
if len(req.text_a.strip()) < 50 or len(req.text_b.strip()) < 50:
|
| 72 |
raise HTTPException(status_code=400, detail="texts too short")
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# ------------------------------------------------------------------
|
| 77 |
-
# Telegram bot — two-message flow
|
| 78 |
-
# ------------------------------------------------------------------
|
| 79 |
-
# Per-chat state lives in process memory. When the Space restarts the
|
| 80 |
-
# state is lost; users just resend their first text. Good enough for a
|
| 81 |
-
# stateless free-tier Space.
|
| 82 |
-
|
| 83 |
-
TG_STATE: dict[int, dict] = {}
|
| 84 |
-
TG_MIN_CHARS = 280
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
def tg_send(chat_id: int, text: str) -> None:
|
| 88 |
-
"""Reply via Telegram bot API with retry on transient SSL/network errors."""
|
| 89 |
-
if not TG_TOKEN:
|
| 90 |
-
return
|
| 91 |
-
url = f"https://api.telegram.org/bot{TG_TOKEN}/sendMessage"
|
| 92 |
-
data = {"chat_id": chat_id, "text": text, "parse_mode": "HTML"}
|
| 93 |
-
for attempt in range(3):
|
| 94 |
-
try:
|
| 95 |
-
r = requests.post(url, data=data, timeout=30)
|
| 96 |
-
if r.status_code == 200:
|
| 97 |
-
return
|
| 98 |
-
print(f"[tg] sendMessage HTTP {r.status_code}: {r.text[:200]}", flush=True)
|
| 99 |
-
except Exception as e:
|
| 100 |
-
print(f"[tg] sendMessage attempt {attempt+1} failed: {e}", flush=True)
|
| 101 |
-
time.sleep(1.5)
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
HELP_AR = (
|
| 105 |
-
"أهلاً 👋 أنا <b>بصمة</b> — أكشف ما إذا كان نصّان عربيّان كتبهما "
|
| 106 |
-
"نفس الشخص.\n\n"
|
| 107 |
-
"أرسل النصّ الأول الآن (٢٨٠ حرفاً على الأقل).\n"
|
| 108 |
-
"ثم سأطلب منك النصّ الثاني، وسأعطيك نسبة التطابق.\n\n"
|
| 109 |
-
"/reset — لمسح ما أرسلته والبدء من جديد"
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def verdict_ar(sim: float) -> str:
|
| 114 |
-
if sim > 0.85:
|
| 115 |
-
return "✅ <b>مؤشّر قوي على نفس الكاتب</b>"
|
| 116 |
-
if sim > 0.70:
|
| 117 |
-
return "🟡 تقارب أسلوبي ملحوظ — الأدلّة غير حاسمة"
|
| 118 |
-
if sim > 0.50:
|
| 119 |
-
return "🟠 تباين أسلوبي مع نقاط تشابه"
|
| 120 |
-
return "❌ <b>أسلوبان مختلفان — مؤشّر قوي على اختلاف الكاتب</b>"
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
@app.post("/telegram")
|
| 124 |
-
async def telegram_webhook(req: Request):
|
| 125 |
-
update = await req.json()
|
| 126 |
-
msg = update.get("message") or update.get("edited_message")
|
| 127 |
-
if not msg:
|
| 128 |
-
return {"ok": True}
|
| 129 |
-
|
| 130 |
-
chat_id = msg["chat"]["id"]
|
| 131 |
-
text = (msg.get("text") or "").strip()
|
| 132 |
-
|
| 133 |
-
if text in ("/start", "/help"):
|
| 134 |
-
TG_STATE.pop(chat_id, None)
|
| 135 |
-
tg_send(chat_id, HELP_AR)
|
| 136 |
-
return {"ok": True}
|
| 137 |
-
|
| 138 |
-
if text == "/reset":
|
| 139 |
-
TG_STATE.pop(chat_id, None)
|
| 140 |
-
tg_send(chat_id, "تم المسح. أرسل النصّ الأول.")
|
| 141 |
-
return {"ok": True}
|
| 142 |
-
|
| 143 |
-
if len(text) < TG_MIN_CHARS:
|
| 144 |
-
tg_send(
|
| 145 |
-
chat_id,
|
| 146 |
-
f"النصّ قصير ({len(text)} حرف). أحتاج {TG_MIN_CHARS} حرفاً على الأقل.",
|
| 147 |
-
)
|
| 148 |
-
return {"ok": True}
|
| 149 |
-
|
| 150 |
-
state = TG_STATE.get(chat_id)
|
| 151 |
-
if not state or not state.get("first"):
|
| 152 |
-
TG_STATE[chat_id] = {"first": text}
|
| 153 |
-
tg_send(chat_id, f"حفظت النصّ الأول ({len(text)} حرف). أرسل النصّ الثاني.")
|
| 154 |
-
return {"ok": True}
|
| 155 |
-
|
| 156 |
-
first = state["first"]
|
| 157 |
-
TG_STATE.pop(chat_id, None)
|
| 158 |
-
|
| 159 |
-
tg_send(chat_id, "جارٍ التحليل…")
|
| 160 |
-
try:
|
| 161 |
-
sim = cosine(first, text)
|
| 162 |
-
except Exception as e:
|
| 163 |
-
print(f"[tg] verify error: {e}", flush=True)
|
| 164 |
-
tg_send(chat_id, "تعذّر التحليل. حاول مجدّداً.")
|
| 165 |
-
return {"ok": True}
|
| 166 |
-
|
| 167 |
-
pct = max(0.0, min(1.0, sim)) * 100
|
| 168 |
-
reply = (
|
| 169 |
-
f"<b>نسبة التطابق:</b> {pct:.1f}%\n"
|
| 170 |
-
f"{verdict_ar(sim)}\n\n"
|
| 171 |
-
"<i>أداة مساعدة وليست دليلاً قانونياً.</i>"
|
| 172 |
)
|
| 173 |
-
|
| 174 |
-
return {"ok": True}
|
|
|
|
| 1 |
"""
|
| 2 |
Bassma v2 inference endpoint — FastAPI on HuggingFace Spaces.
|
| 3 |
|
| 4 |
+
Pure model server. The Telegram bot lives on Vercel; that side calls
|
| 5 |
+
this /verify endpoint with a shared API key.
|
| 6 |
+
|
| 7 |
Endpoints:
|
| 8 |
+
GET / — health check (also used by keep-alive cron)
|
| 9 |
+
POST /verify — JSON API for the Next.js frontend AND Vercel bot route
|
|
|
|
| 10 |
|
| 11 |
Env (set as Space Secrets in the HF UI):
|
| 12 |
+
HF_TOKEN — read token to pull the private model at startup
|
| 13 |
+
BASSMA_API_KEY — shared secret with anything that calls /verify
|
| 14 |
+
(frontend, Vercel /api/telegram, etc.)
|
| 15 |
"""
|
| 16 |
|
| 17 |
import os
|
|
|
|
| 18 |
|
| 19 |
import numpy as np
|
| 20 |
+
from fastapi import FastAPI, Header, HTTPException
|
|
|
|
| 21 |
from pydantic import BaseModel
|
| 22 |
from sentence_transformers import SentenceTransformer
|
| 23 |
|
|
|
|
| 25 |
|
| 26 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 27 |
API_KEY = os.environ.get("BASSMA_API_KEY")
|
|
|
|
| 28 |
|
| 29 |
print("Loading model...", flush=True)
|
| 30 |
model = SentenceTransformer(MODEL_ID, token=HF_TOKEN)
|
|
|
|
| 38 |
)
|
| 39 |
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
class VerifyRequest(BaseModel):
|
| 42 |
text_a: str
|
| 43 |
text_b: str
|
|
|
|
| 61 |
raise HTTPException(status_code=401, detail="invalid api key")
|
| 62 |
if len(req.text_a.strip()) < 50 or len(req.text_b.strip()) < 50:
|
| 63 |
raise HTTPException(status_code=400, detail="texts too short")
|
| 64 |
+
embs = model.encode(
|
| 65 |
+
[normalize(req.text_a), normalize(req.text_b)],
|
| 66 |
+
normalize_embeddings=True, convert_to_numpy=True,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
)
|
| 68 |
+
return VerifyResponse(similarity=float(np.dot(embs[0], embs[1])))
|
|
|
requirements.txt
CHANGED
|
@@ -2,4 +2,3 @@ fastapi==0.115.0
|
|
| 2 |
uvicorn[standard]==0.30.6
|
| 3 |
sentence-transformers==3.4.1
|
| 4 |
numpy<2.0
|
| 5 |
-
requests==2.32.3
|
|
|
|
| 2 |
uvicorn[standard]==0.30.6
|
| 3 |
sentence-transformers==3.4.1
|
| 4 |
numpy<2.0
|
|
|