| |
| |
| |
| |
| |
| |
| import json, sys, time, urllib.request |
|
|
| KEY = open("./deepseek_api_key.txt").read().strip() |
| BASE = "https://api.deepseek.com/v1" |
| OUT = "./p1_textes.jsonl" |
|
|
|
|
| def api(payload, timeout=900): |
| rq = urllib.request.Request(BASE + "/chat/completions", data=json.dumps(payload).encode(), |
| headers={"Content-Type": "application/json", |
| "Authorization": "Bearer " + KEY}) |
| return json.loads(urllib.request.urlopen(rq, timeout=timeout).read()) |
|
|
|
|
| def prompts(): |
| P = [] |
| phys_en = ["the mechanism of quark confinement", "asymptotic freedom and the running coupling", |
| "the Wilson loop area law", "instantons and the theta vacuum", |
| "the Higgs mechanism in the Standard Model", "lattice regularization of gauge theories"] |
| phys_fr = ["le mécanisme du confinement des quarks", "la liberté asymptotique", |
| "la loi d'aire de la boucle de Wilson", "les instantons et le vide theta", |
| "le mécanisme de Higgs", "la régularisation sur réseau des théories de jauge"] |
| for i, t in enumerate(phys_en): |
| P.append(("physique", "en", f"Explain {t} in about 400 words, plain prose.")) |
| for i, t in enumerate(phys_fr): |
| P.append(("physique", "fr", f"Explique {t} en environ 400 mots, prose simple.")) |
| code_en = ["a function that inverts a dictionary with duplicate values", |
| "a class implementing a fixed-size LRU cache", |
| "a generator that yields primes below n", |
| "a function that merges overlapping intervals", |
| "a decorator that retries a function 3 times", |
| "a parser for simple arithmetic expressions"] |
| code_fr = ["une fonction qui transpose une matrice creuse représentée en dict", |
| "une classe file de priorité basée sur heapq", |
| "une fonction qui détecte les cycles dans un graphe orienté", |
| "un context-manager qui chronomètre un bloc", |
| "une fonction qui normalise des chemins de fichiers", |
| "un itérateur par fenêtres glissantes sur une liste"] |
| for t in code_en: |
| P.append(("code", "en", f"Write Python: {t}. Code with docstring, then a short usage example.")) |
| for t in code_fr: |
| P.append(("code", "fr", f"Écris en Python : {t}. Code avec docstring, puis un court exemple.")) |
| tools = ["wilson polyakov creutz luscher symanzik kogut susskind osterwalder", |
| "glimm jaffe brydges federbush battle magnen rivasseau feldman"] |
| for j, grp in enumerate(tools * 3): |
| lang = "en" if j % 2 == 0 else "fr" |
| fs = grp.split()[j % 4:][:6] |
| con = ("Generate one JSON tool call per line, format " |
| '{"name":"read_file","arguments":{"path":"/notes/<x>.md","offset":<100*i>,"limit":150}}, for x in: ' |
| if lang == "en" else |
| "Génère un appel d'outil JSON par ligne, format " |
| '{"name":"read_file","arguments":{"path":"/notes/<x>.md","offset":<100*i>,"limit":150}}, pour x dans : ') |
| P.append(("toolcall", lang, con + ", ".join(fs) + ". Nothing else." if lang == "en" else con + ", ".join(fs) + ". Rien d'autre.")) |
| prose_en = ["the history of the metric system", "how vaccines train the immune system", |
| "why the sky is blue"] |
| prose_fr = ["l'histoire du système métrique", "comment fonctionne un moteur à quatre temps", |
| "pourquoi le ciel est bleu"] |
| for t in prose_en: |
| P.append(("prose", "en", f"Write a clear 300-word explanation of {t}.")) |
| for t in prose_fr: |
| P.append(("prose", "fr", f"Rédige une explication claire de 300 mots sur {t}.")) |
| return P |
|
|
|
|
| LP = prompts() |
| print(f" {len(LP)} prompts ({sum(1 for d,l,_ in LP if l=='fr')} FR)") |
| n_ok = n_repro = 0 |
| with open(OUT, "w") as f: |
| for i, (dom, lang, q) in enumerate(LP): |
| try: |
| reps = [] |
| for essai in range(2): |
| d = api({"model": "deepseek-v4-flash", "temperature": 0.0, "max_tokens": 640, |
| "thinking": {"type": "disabled"}, |
| "logprobs": True, "top_logprobs": 20, |
| "messages": [{"role": "user", "content": q}]}) |
| ch = d["choices"][0] |
| reps.append(((ch["message"].get("content") or ""), |
| (ch.get("logprobs") or {}).get("content") or [], d.get("usage", {}))) |
| time.sleep(0.3) |
| texte, lp, usage = reps[0] |
| repro = reps[0][0] == reps[1][0] |
| api_top = [{"t": p["token"], |
| "top": [[q2["token"], q2["logprob"]] for q2 in (p.get("top_logprobs") or [])]} |
| for p in lp] |
| f.write(json.dumps({"id": i, "domaine": dom, "langue": lang, "prompt": q, |
| "texte": texte, "api_top": api_top, "reproduced": repro, |
| "usage": usage}, ensure_ascii=False) + "\n") |
| n_ok += 1; n_repro += repro |
| print(f" [{i+1}/{len(LP)}] {dom}/{lang} {len(texte)} car., reproduit={repro}") |
| except Exception as e: |
| print(f" [{i+1}] ERREUR {dom}/{lang}: {e}", file=sys.stderr) |
| print(f" ⟹ {n_ok} textes, {n_repro} reproduits bit-à-bit ({n_ok - n_repro} divergents = bruit API, gardés et étiquetés)") |
| print("P1A_FINI") |
|
|