update code/robust_clean.py (post-review release)
Browse files- code/robust_clean.py +75 -0
code/robust_clean.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""robust_clean.py — المتانة بعشر بذور على ALL-نظيف (Tanzil-نظيف + Bible-نظيف فقط؛
|
| 4 |
+
TED مستثناة لأن النظيف منها 154 عنصرًا فقط — تُذكر كقيد)."""
|
| 5 |
+
import sys, re, random, json
|
| 6 |
+
sys.path.insert(0,"/home/user/lhc/code"); sys.path.insert(0,"/home/user/lhc/recon")
|
| 7 |
+
import numpy as np
|
| 8 |
+
from phase_w1_data import download_corpus
|
| 9 |
+
from phase_c_encoder import TrainableEncoder
|
| 10 |
+
from phase_p2_slot import hashed_features_slot
|
| 11 |
+
from lhc_core import LHC0
|
| 12 |
+
|
| 13 |
+
DD="/home/user/lhc/data/opus"
|
| 14 |
+
HELDOUT=[("Tanzil","https://object.pouta.csc.fi/OPUS-Tanzil/v1/moses/ar-en.txt.zip",20000),
|
| 15 |
+
("Bible","https://object.pouta.csc.fi/OPUS-bible-uedin/v1/moses/ar-en.txt.zip",20000)]
|
| 16 |
+
_AR_LETTER=re.compile(r"[\u0621-\u064A]")
|
| 17 |
+
_HARAKAT=["\u064E","\u064F","\u0650","\u0652","\u0651","\u064B","\u064C","\u064D"]
|
| 18 |
+
_DIGIT_MAP=str.maketrans("0123456789","\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669")
|
| 19 |
+
def distort_kind(t,nrs,kind):
|
| 20 |
+
if kind=="tashkeel":
|
| 21 |
+
out=[]
|
| 22 |
+
for ch in t:
|
| 23 |
+
out.append(ch)
|
| 24 |
+
if _AR_LETTER.match(ch) and nrs.rand()<0.28: out.append(_HARAKAT[int(nrs.randint(len(_HARAKAT)))])
|
| 25 |
+
return "".join(out)
|
| 26 |
+
if kind=="ortho":
|
| 27 |
+
for a,b in (("\u0623","\u0627"),("\u0625","\u0627"),("\u0622","\u0627"),("\u0671","\u0627"),("\u0629","\u0647"),("\u0649","\u064A")): t=t.replace(a,b)
|
| 28 |
+
return t.translate(_DIGIT_MAP)
|
| 29 |
+
if kind=="tatweel":
|
| 30 |
+
ws=t.split(" ")
|
| 31 |
+
for i in range(len(ws)):
|
| 32 |
+
w=ws[i]
|
| 33 |
+
if len(w)>3 and nrs.rand()<0.25:
|
| 34 |
+
j=int(nrs.randint(1,len(w)-2)); ws[i]=w[:j]+"\u0640"+w[j:]
|
| 35 |
+
return " ".join(ws)
|
| 36 |
+
if kind=="combined": return distort_kind(distort_kind(t,nrs,"tashkeel"),nrs,"ortho")
|
| 37 |
+
return t
|
| 38 |
+
|
| 39 |
+
M=json.load(open("/home/user/lhc/results/masks_v2.json"))
|
| 40 |
+
pool=[]
|
| 41 |
+
for name,url,lim in HELDOUT:
|
| 42 |
+
ps=download_corpus(name,url,lim,DD)
|
| 43 |
+
mask=set(M["masks_strong"][name])
|
| 44 |
+
pool += [p for i,p in enumerate(ps) if i not in mask]
|
| 45 |
+
print(f"ALL-نظيف (Tanzil+Bible): {len(pool):,} عنصرًا")
|
| 46 |
+
|
| 47 |
+
def acc(enc,queries,targets):
|
| 48 |
+
lhc=LHC0(kb=[{"prompt":t,"response":str(i),"domain":"x"} for i,t in enumerate(targets)],encoder=enc)
|
| 49 |
+
ok=0
|
| 50 |
+
for i,q in enumerate(queries):
|
| 51 |
+
e,_,_=lhc.memory.read(q); ok+=int(e["prompt"]==targets[i])
|
| 52 |
+
return ok/max(1,len(queries))
|
| 53 |
+
|
| 54 |
+
encs={}
|
| 55 |
+
for tag,wp in [("W4","weights/phase_w1_W.npz"),("W4.1","weights/phase_w1_W_robust.npz")]:
|
| 56 |
+
z=np.load(wp); encs[tag]=TrainableEncoder(F=int(z["F"]),d=int(z["d"]),tau=float(z["tau"]),W=z["W"],features_fn=hashed_features_slot)
|
| 57 |
+
|
| 58 |
+
rng=random.Random(41); samp=rng.sample(pool,300)
|
| 59 |
+
ar=[p["ar"] for p in samp]; en=[p["en"] for p in samp]
|
| 60 |
+
out={"pool":"ALL-clean (Tanzil+Bible clean)","n_pool":len(pool),"n_sample":300,"sample_seed":41,"seeds":list(range(10)),
|
| 61 |
+
"note":"TED مستثناة (النظيف 154 عنصرًا) — قيد معلن"}
|
| 62 |
+
for kind in ("clean","tashkeel","ortho","tatweel","combined"):
|
| 63 |
+
for tag in ("W4","W4.1"):
|
| 64 |
+
a1s,a2s=[],[]
|
| 65 |
+
for cs in range(10):
|
| 66 |
+
if kind=="clean": ar_d=ar
|
| 67 |
+
else:
|
| 68 |
+
nrs=np.random.RandomState(cs); ar_d=[distort_kind(a,nrs,kind) for a in ar]
|
| 69 |
+
a1s.append(acc(encs[tag],ar_d,en)); a2s.append(acc(encs[tag],en,ar_d))
|
| 70 |
+
if kind=="clean": break
|
| 71 |
+
m1,s1=float(np.mean(a1s)),float(np.std(a1s)); m2,s2=float(np.mean(a2s)),float(np.std(a2s))
|
| 72 |
+
out[f"{kind}|{tag}"]={"mean_ar_en":round(m1,4),"std_ar_en":round(s1,4),"mean_en_ar":round(m2,4),"std_en_ar":round(s2,4)}
|
| 73 |
+
print(f"[{kind:9s} {tag:4s}] {m1:.3f}±{s1:.3f} / {m2:.3f}±{s2:.3f}", flush=True)
|
| 74 |
+
json.dump(out, open("/home/user/lhc/results/robust_clean.json","w"), ensure_ascii=False, indent=1)
|
| 75 |
+
print("SAVED results/robust_clean.json")
|