# colab_style.py — le run d'essai des étiquettes de style (run-075), sur Google Colab, sans aucune clé.
# Refait le mélange de 7 sources étiquetées (prep_style.py) depuis les sources publiques, la validation habituelle
# (web, wiki, livres, sans étiquette, vérifiée par empreinte), puis entraîne le petit modèle (34 M) sur 600 M jetons.
import gzip, hashlib, json, os, subprocess, sys, time, urllib.request

SITE = "https://ia.vmailx.com/data/fr-mini"
RACINE = "/content/fr-mini"
PREP, RAW, DATA, RES = (f"{RACINE}/{d}" for d in ("prep", "raw", "data", "res"))
for d in (PREP, RAW, DATA, RES):
    os.makedirs(d, exist_ok=True)
EMPREINTES_VAL = {"web": "c2b7e3d73bf3c106", "wiki": "96f25d64b281217d", "livres": "d5c5dc22f03d78c7"}
# part des lectures par source : aucune source relue plus d'environ 4 fois
POIDS = {"web": 0.2025, "wiki": 0.2025, "livres": 0.2025, "litterature": 0.2025, "debats": 0.12, "vikidia": 0.04, "droit": 0.03}
RUN = {"nom": "S-style", "sources": list(POIDS), "poids": POIDS, "uniques": 600_000_000, "vus": 600_000_000,
       "compile": True, "budget_minutes": 690}
T0 = time.time()
def log(*a):
    print(f"[{(time.time() - T0) / 60:6.1f} min]", *a, flush=True)

subprocess.run([sys.executable, "-m", "pip", "install", "-q", "tokenizers", "pyarrow", "huggingface_hub", "hf_xet"], check=True)
for nom, dest in [("prep_style.py", f"{RACINE}/prep_style.py"), ("style_fr.py", f"{RACINE}/style_fr.py"), ("train.py", f"{RACINE}/train.py"),
                  ("tokenizer.json", f"{PREP}/tokenizer.json"), ("val_docs.json.gz", f"{RAW}/val_docs.json.gz")]:
    urllib.request.urlretrieve(f"{SITE}/{nom}", dest)
urllib.request.urlretrieve("https://www.lexique.org/databases/Lexique383/Lexique383.tsv", f"{RAW}/Lexique383.tsv")
with gzip.open(f"{RAW}/val_docs.json.gz") as g, open(f"{RAW}/val_docs.json", "wb") as f:
    f.write(g.read())
log("fichiers récupérés")

# 1. le mélange étiqueté
env = dict(os.environ, FR_OUT=PREP, FR_RAW=RAW, LEXIQUE=f"{RAW}/Lexique383.tsv", PAR_SOURCE="90000000",
           RAYON_NUM_THREADS=str(os.cpu_count() or 2))
subprocess.run([sys.executable, f"{RACINE}/prep_style.py"], env=env, check=True)

# 2. la validation habituelle, sans étiquette, identique aux autres runs
from tokenizers import Tokenizer
import numpy as np
tk = Tokenizer.from_file(f"{PREP}/tokenizer.json")
val = json.load(open(f"{RAW}/val_docs.json", encoding="utf-8"))
for s in ("web", "wiki", "livres"):
    chemin = f"{DATA}/v16384_{s}.val.bin"
    with open(chemin, "wb") as f:
        for i in range(0, len(val[s]), 256):
            for enc in tk.encode_batch(val[s][i:i + 256]):
                np.asarray(enc.ids + [0], dtype=np.uint16).tofile(f)
    h = hashlib.sha256(open(chemin, "rb").read()).hexdigest()[:16]
    assert h == EMPREINTES_VAL[s], f"validation {s} différente ({h})"
for s in POIDS:
    os.symlink(f"{PREP}/{s}.train.bin", f"{DATA}/{s}.train.bin")
os.symlink(f"{PREP}/tokenizer.json", f"{DATA}/tokenizer.json")
log("données prêtes", json.load(open(f"{PREP}/stats_style.json")))

# 3. l'entraînement
src = open(f"{RACINE}/train.py", encoding="utf-8").read().replace("__EXPERIENCES__", json.dumps([RUN], ensure_ascii=False))
open(f"{RACINE}/train_lance.py", "w", encoding="utf-8").write(src)
subprocess.run([sys.executable, f"{RACINE}/train_lance.py"], env=dict(os.environ, FR_MINI_DATA=DATA, FR_MINI_OUT=RES), check=True)
import shutil
shutil.copy(f"{PREP}/stats_style.json", f"{RES}/S-style/stats_style.json")
log("fini")
