from fastapi import FastAPI, Query, Body from fastapi.responses import HTMLResponse, JSONResponse import sqlite3, os, re, threading from pathlib import Path from huggingface_hub import hf_hub_download, HfApi app = FastAPI() REPO_ID = "iSoFe/ministry-db" DB_DIR = Path("/tmp/dbs") DB_DIR.mkdir(exist_ok=True) PROVINCES = [ {"key": "baghdad", "name": "بغداد", "file": "baghdad.sqlite"}, {"key": "nineveh", "name": "نينوى", "file": "nineveh.sqlite"}, {"key": "basra", "name": "البصرة", "file": "basra.sqlite"}, {"key": "dhiqar", "name": "ذي قار", "file": "dhiqar.sqlite"}, {"key": "babylon", "name": "بابل", "file": "babylon.sqlite"}, {"key": "sulaymaniyah", "name": "السليمانية", "file": "sulaymaniyah.sqlite"}, {"key": "erbil", "name": "أربيل", "file": "erbil.sqlite"}, {"key": "najaf", "name": "النجف", "file": "najaf.sqlite"}, {"key": "alanbar", "name": "الأنبار", "file": "al-anbar.sqlite"}, {"key": "diyala", "name": "ديالى", "file": "diyala.sqlite"}, {"key": "kirkuk", "name": "كركوك", "file": "kirkuk.sqlite"}, {"key": "salahaldeen", "name": "صلاح الدين", "file": "salah-aldeen.sqlite"}, {"key": "muthana", "name": "المثنى", "file": "muthana.sqlite"}, {"key": "mesan", "name": "ميسان", "file": "mesan.sqlite"}, {"key": "karbalaa", "name": "كربلاء", "file": "karbalaa.sqlite"}, {"key": "qadisiya", "name": "القادسية", "file": "qadisiya.sqlite"}, {"key": "duhok", "name": "دهوك", "file": "duhok.sqlite"}, {"key": "wasit", "name": "واسط", "file": "wasit.sqlite"}, {"key": "balad", "name": "بلد (يثرب)", "file": "balad.sqlite"}, ] PROVINCE_MAP = {p["key"]: p for p in PROVINCES} # ─── TEXT ───────────────────────────────────────────────────────────────────── DIACRITICS = re.compile(r'[\u064B-\u065F\u0610-\u061A\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]') ARABIC_ONLY = re.compile('[^\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF\s]') def clean(text) -> str: if not text: return "" return ARABIC_ONLY.sub('', str(text)).strip() def normalize(text) -> str: if not text: return "" t = clean(text) t = DIACRITICS.sub('', t) t = t.replace("أ","ا").replace("إ","ا").replace("آ","ا") t = t.replace("ة","ه").replace("ى","ي") return t.strip() def fmt_name(raw) -> str: if not raw: return "" raw = DIACRITICS.sub('', clean(str(raw))).strip() for p in ["عبد","ابو","أبو","زين","بدر","نور","سيف","عز","علاء","ضياء","بهاء","ذو"]: if raw.startswith(p) and len(raw) - len(p) > 2: return raw[:len(p)] + " " + raw[len(p):] return raw def fmt_birth(raw) -> str: if raw is None: return "" try: n = int(float(str(raw).split("+")[0].strip())) s = str(n) if len(s) == 6: y, m = s[:4], s[4:] return y if m == "00" else f"{y}/{m}" return s except: return str(raw) def row_to_dict(row) -> dict: f = fmt_name(row["p_first"]) fa = fmt_name(row["p_father"]) g = fmt_name(row["p_grand"]) return { "fam_no": str(row["fam_no"] or "").strip(), "p_first": f, "p_father": fa, "p_grand": g, "p_birth": fmt_birth(row["p_birth"]), "full_name": f"{f} {fa} {g}".strip(), } # ─── DB ─────────────────────────────────────────────────────────────────────── def download_db(filename): local = DB_DIR / filename if not local.exists(): hf_hub_download(repo_id=REPO_ID, filename=filename, repo_type="dataset", local_dir=str(DB_DIR), token=os.environ.get("HF_TOKEN")) return str(local) def get_db_path(key): prov = PROVINCE_MAP.get(key) return download_db(prov["file"]) if prov else None def open_db(path): conn = sqlite3.connect(path) conn.row_factory = sqlite3.Row conn.create_function("NORM", 1, normalize) return conn def get_table(conn): r = conn.execute("SELECT name FROM sqlite_master WHERE type='table' LIMIT 1").fetchone() return r[0] if r else None def name_combos(words): n = len(words) if n < 3 or n > 7: return [] seen = set() out = [] for i in range(1, n-1): for j in range(i+1, n): k = ("".join(words[:i]), "".join(words[i:j]), "".join(words[j:])) if k not in seen: seen.add(k) out.append(k) return out def fam_candidates(fam): s = {fam.strip()} try: n = int(fam.strip()) s.add(str(n)); s.add(f"{n:07d}") except: pass return s # ─── PRELOAD ────────────────────────────────────────────────────────────────── SMALL_FILES = ["balad","muthana","duhok","karbalaa","salahaldeen","mesan","qadisiya","wasit","kirkuk"] def preload(): for key in SMALL_FILES: try: prov = PROVINCE_MAP.get(key) if prov: local = DB_DIR / prov["file"] if not local.exists(): download_db(prov["file"]) except: pass @app.on_event("startup") async def startup(): threading.Thread(target=preload, daemon=True).start() # ─── API ────────────────────────────────────────────────────────────────────── @app.get("/api/search") def search(p: str = Query(...), name: str = Query(None), fam: str = Query(None)): try: db_path = get_db_path(p) if not db_path: return JSONResponse({"error": "محافظة غير موجودة"}, 404) conn = open_db(db_path) table = get_table(conn) if not table: return JSONResponse({"error": "قاعدة البيانات فارغة"}, 500) results, seen = [], set() fuzzy = False if fam: for c in fam_candidates(fam): for row in conn.execute(f"SELECT fam_no,p_first,p_father,p_grand,p_birth FROM [{table}] WHERE fam_no=? LIMIT 200", (c,)).fetchall(): d = row_to_dict(row) k = (d["fam_no"], d["p_first"], d["p_father"], d["p_grand"]) if k not in seen: seen.add(k); results.append(d) elif name: words = name.strip().split() if len(words) < 3: conn.close() return JSONResponse({"error": "يرجى إدخال الاسم الثلاثي كاملاً"}) norm_words = [normalize(w) for w in words] # ── Exact search first ── for first, father, grand in name_combos(norm_words): for row in conn.execute( f"SELECT fam_no,p_first,p_father,p_grand,p_birth FROM [{table}] WHERE NORM(p_first)=? AND NORM(p_father)=? AND NORM(p_grand)=? LIMIT 300", (first, father, grand)).fetchall(): d = row_to_dict(row) k = (d["fam_no"], d["p_first"], d["p_father"], d["p_grand"]) if k not in seen: seen.add(k); results.append(d) # ── Fuzzy fallback: search by first+father only ── if not results and len(norm_words) >= 2: fuzzy = True for i in range(1, len(norm_words)): first = "".join(norm_words[:i]) father = "".join(norm_words[i:]) for row in conn.execute( f"SELECT fam_no,p_first,p_father,p_grand,p_birth FROM [{table}] WHERE NORM(p_first)=? AND NORM(p_father)=? LIMIT 100", (first, father)).fetchall(): d = row_to_dict(row) k = (d["fam_no"], d["p_first"], d["p_father"], d["p_grand"]) if k not in seen: seen.add(k); results.append(d) conn.close() return JSONResponse({"results": results, "count": len(results), "mode": "fam" if fam else "name", "fuzzy": fuzzy}) except Exception as e: return JSONResponse({"error": str(e)}, 500) @app.get("/api/family") def family(p: str = Query(...), fam: str = Query(...)): try: db_path = get_db_path(p) if not db_path: return JSONResponse({"error": "محافظة غير موجودة"}, 404) conn = open_db(db_path) table = get_table(conn) members, seen = [], set() for c in fam_candidates(fam): for row in conn.execute(f"SELECT fam_no,p_first,p_father,p_grand,p_birth FROM [{table}] WHERE fam_no=? LIMIT 100", (c,)).fetchall(): d = row_to_dict(row) k = (d["p_first"], d["p_father"], d["p_grand"]) if k not in seen: seen.add(k); members.append(d) conn.close() return JSONResponse({"members": members, "count": len(members)}) except Exception as e: return JSONResponse({"error": str(e)}, 500) # ─── PAGES ──────────────────────────────────────────────────────────────────── INDEX_HTML = """ نظام البحث في السجلات
سجلات الوزارة
قواعد البيانات الإدارية

نظام البحث في السجلات

الوصول السريع إلى القيود المدنية والملفات الأسرية حسب الوحدة الإدارية

19 وحدة إدارية
متصل المزامنة السحابية
نشط حالة النظام الآمن
المحافظات والأقضية المتوفرة 19 وحدة إدارية
بغداد
نينوى
البصرة
ذي قار
بابل
السليمانية
أربيل
النجف
الأنبار
ديالى
كركوك
صلاح الدين
المثنى
ميسان
كربلاء
القادسية
دهوك
واسط
بلد (يثرب)
""" SEARCH_HTML = """ بحث — {prov_name}
الرئيسية {prov_name}

أدخل الاسم الثلاثي — الاسم واسم الأب واسم الجد

""" # ─── ADMIN API ──────────────────────────────────────────────────────────────── @app.post("/api/admin/add") def admin_add(data: dict = Body(...)): try: p = data.get("province") first = data.get("p_first","").strip() father = data.get("p_father","").strip() grand = data.get("p_grand","").strip() birth = data.get("p_birth","").strip() fam_no = data.get("fam_no","").strip() if not all([p, first, father, grand, fam_no]): return JSONResponse({"error": "جميع الحقول مطلوبة"}, 400) db_path = get_db_path(p) if not db_path: return JSONResponse({"error": "محافظة غير موجودة"}, 404) conn = sqlite3.connect(db_path) table = get_table(conn) # Convert birth to integer format YYYYMM birth_int = None if birth: birth_clean = birth.replace("/","").strip() if len(birth_clean) == 4: birth_int = int(birth_clean + "00") elif len(birth_clean) == 6: birth_int = int(birth_clean) conn.execute( f"INSERT INTO [{table}] (fam_no, p_first, p_father, p_grand, p_birth) VALUES (?,?,?,?,?)", (fam_no, first, father, grand, birth_int) ) conn.commit() conn.close() return JSONResponse({"ok": True}) except Exception as e: return JSONResponse({"error": str(e)}, 500) @app.post("/api/admin/edit") def admin_edit(data: dict = Body(...)): try: p = data.get("province") old_first = data.get("old_first","").strip() old_father = data.get("old_father","").strip() old_grand = data.get("old_grand","").strip() old_fam = data.get("old_fam","").strip() new_first = data.get("p_first","").strip() new_father = data.get("p_father","").strip() new_grand = data.get("p_grand","").strip() new_birth = data.get("p_birth","").strip() new_fam = data.get("fam_no","").strip() db_path = get_db_path(p) if not db_path: return JSONResponse({"error": "محافظة غير موجودة"}, 404) conn = sqlite3.connect(db_path) table = get_table(conn) birth_int = None if new_birth: b = new_birth.replace("/","").strip() if len(b) == 4: birth_int = int(b + "00") elif len(b) == 6: birth_int = int(b) conn.execute( f"UPDATE [{table}] SET p_first=?, p_father=?, p_grand=?, p_birth=?, fam_no=? " f"WHERE fam_no=? AND p_first=? AND p_father=? AND p_grand=?", (new_first, new_father, new_grand, birth_int, new_fam, old_fam, old_first, old_father, old_grand) ) conn.commit() conn.close() return JSONResponse({"ok": True}) except Exception as e: return JSONResponse({"error": str(e)}, 500) @app.post("/api/admin/delete-person") def admin_delete_person(data: dict = Body(...)): try: p = data.get("province") first = data.get("p_first","").strip() father = data.get("p_father","").strip() grand = data.get("p_grand","").strip() fam_no = data.get("fam_no","").strip() db_path = get_db_path(p) if not db_path: return JSONResponse({"error": "محافظة غير موجودة"}, 404) conn = sqlite3.connect(db_path) table = get_table(conn) conn.execute( f"DELETE FROM [{table}] WHERE fam_no=? AND p_first=? AND p_father=? AND p_grand=?", (fam_no, first, father, grand) ) conn.commit() conn.close() return JSONResponse({"ok": True}) except Exception as e: return JSONResponse({"error": str(e)}, 500) @app.post("/api/admin/delete-family") def admin_delete_family(data: dict = Body(...)): try: p = data.get("province") fam_no = data.get("fam_no","").strip() db_path = get_db_path(p) if not db_path: return JSONResponse({"error": "محافظة غير موجودة"}, 404) conn = sqlite3.connect(db_path) table = get_table(conn) candidates = {fam_no} try: n = int(fam_no) candidates.add(str(n)) candidates.add(f"{n:07d}") except: pass deleted = 0 for candidate in candidates: cur = conn.execute(f"DELETE FROM [{table}] WHERE fam_no=?", (candidate,)) deleted += cur.rowcount conn.commit() conn.close() return JSONResponse({"ok": True, "deleted": deleted}) except Exception as e: return JSONResponse({"error": str(e)}, 500) @app.post("/api/admin/save") def admin_save(data: dict = Body(...)): try: p = data.get("province") prov = PROVINCE_MAP.get(p) if not prov: return JSONResponse({"error": "محافظة غير موجودة"}, 404) db_path = get_db_path(p) token = os.environ.get("HF_TOKEN") if not token: return JSONResponse({"error": "HF_TOKEN غير موجود"}, 500) api = HfApi() api.upload_file( path_or_fileobj=db_path, path_in_repo=prov["file"], repo_id=REPO_ID, repo_type="dataset", token=token, ) return JSONResponse({"ok": True}) except Exception as e: return JSONResponse({"error": str(e)}, 500) # ─── ADMIN PAGE ─────────────────────────────────────────────────────────────── ADMIN_HTML = """ لوحة التحكم
البوابة العامة لوحة التحكم الإدارية

بيانات القيد الجديد

ابحث عن قيد لتعديله أو حذفه

ابحث عن قيد لتعديله أو حذفه

إدارة القيد العائلي بالكامل

أدخل رقم العائلة لعرض وحذف السجلات المرتبطة بها

""" @app.get("/", response_class=HTMLResponse) def index(): return HTMLResponse(INDEX_HTML) @app.get("/search", response_class=HTMLResponse) def search_page(p: str = Query(...)): prov = PROVINCE_MAP.get(p) if not prov: return HTMLResponse("

محافظة غير موجودة

", 404) return HTMLResponse(SEARCH_HTML.format(prov_name=prov["name"], prov_key=p)) @app.get("/admin", response_class=HTMLResponse) def admin_page(): return HTMLResponse(ADMIN_HTML)