Datasets:
Download code/generate_hardcore_massive.py from Davidmg0815/spreizzaehler-daten: direct link, hf CLI and curl.
- Browser
- Download file 25.3 kB
-
https://huggingface.co/datasets/Davidmg0815/spreizzaehler-daten/resolve/main/code/generate_hardcore_massive.py
- Command line
-
hf download hf://datasets/Davidmg0815/spreizzaehler-daten/code/generate_hardcore_massive.py
-
curl -L -o generate_hardcore_massive.py https://huggingface.co/datasets/Davidmg0815/spreizzaehler-daten/resolve/main/code/generate_hardcore_massive.py
25.3 kB
| #!/usr/bin/env python3 | |
| """Hardcore-Datensatz: deutsche Woerter mit Dreifach-/Doppelbuchstaben und lange Komposita, | |
| Antworten im Graf-Zahl-Stil mit "Spreiz-Technik" im think-Block. | |
| Phase 1: Das 27B liefert Wortlisten je Kategorie; Eigenschaften (Dreifachfolge, Doppelbuchstabe, | |
| Laenge) und Testwort-Ausschluss werden per Code erzwungen. Dreifachfolgen kann das 27B nicht | |
| buchstabengenau bilden: dafuer baut der Code Komposita aus kuratierten Bausteinen (Schiff + Fahrt). | |
| Phase 2: Das 27B schreibt fuer jedes Wort den Antworttext. Weil das Wort bekannt ist, wird der | |
| think-Block (Wort, Spreizung, Zaehlung) und die Zahlwort-Folge exakt gegen die Wahrheit | |
| geprueft; nur fehlerfreie Antworten werden geschrieben (Append, resume-faehig). | |
| Aufruf: generate_hardcore_massive.py --show-prompts | --selftest | --probe | (ohne Argument: Produktion) | |
| --probe: 3 Beispiele in eigene Dateien (*_probe), damit die Produktion nicht den Mini-Pool laedt. | |
| Konfiguration per Umgebung: GEN_PORT (8292), GEN_CONCURRENCY (3), GEN_MAX (800), GEN_TEMPERATURE (0.3) | |
| """ | |
| import json | |
| import os | |
| import random | |
| import re | |
| import sys | |
| import threading | |
| import time | |
| import urllib.request | |
| from collections import Counter | |
| from concurrent.futures import ThreadPoolExecutor, wait | |
| from itertools import groupby | |
| from pathlib import Path | |
| PROJECT_DIR = Path("/mnt/models/graf_zahl") | |
| PLATTE = "/home/david/Schreibtisch/Platte" | |
| OUT_PATH = PROJECT_DIR / "dataset_hardcore.jsonl" | |
| POOL_PATH = PROJECT_DIR / "word_pool_hardcore.json" | |
| RESCUED_PATH = PROJECT_DIR / "hardcore_rescued_words.jsonl" | |
| MASSIVE_V2 = PROJECT_DIR / "dataset_massive_v2.jsonl" | |
| V2_PATH = PROJECT_DIR / "dataset_v2.jsonl" | |
| TEST_RESULTS = Path(f"{PLATTE}/models/graf_zahl/ab_test_results.json") | |
| TOKENIZER_DIR = f"{PLATTE}/models/graf_zahl/qwen_healed_merged" | |
| MODEL_ID = "/mnt/models/qwen38-1gpu/Huihui-Qwen3.8-27B-abliterated-UD-IQ4_XS.gguf" | |
| GEN_PORT = int(os.environ.get("GEN_PORT", "8292")) | |
| GEN_CONCURRENCY = int(os.environ.get("GEN_CONCURRENCY", "3")) | |
| GEN_MAX = int(os.environ.get("GEN_MAX", "800")) | |
| GEN_TEMPERATURE = float(os.environ.get("GEN_TEMPERATURE", "0.3")) | |
| API_URL = f"http://127.0.0.1:{GEN_PORT}/v1/chat/completions" | |
| MIN_LEN, MAX_LEN = 7, 45 | |
| MAX_TOKENS_EXAMPLE = 3000 | |
| MAX_RETRY_PER_WORD = 5 | |
| QUOTAS = {"dreifach": 0.35, "doppelt": 0.35, "lang": 0.30} | |
| POOL_FACTOR = 1.4 | |
| MAX_POOL_REQUESTS = 60 | |
| TO = "<" + "think" + ">" | |
| TC = "<" + "/think" + ">" | |
| LETTERS = re.compile(r"^[A-Za-zÄÖÜäöüß]+$") | |
| THEMEN = ["Seefahrt", "Küche und Kochen", "Büro und Verwaltung", "Natur und Wald", "Technik und Maschinen", | |
| "Sport", "Medizin", "Handwerk", "Verkehr und Bahn", "Versicherung und Recht", "Landwirtschaft", | |
| "Wetter", "Schule und Bildung", "Musik", "Bau und Architektur", "Haushalt und Möbel", "Tiere", | |
| "Essen und Getränke", "Behörden", "Reisen und Urlaub", "Energie und Umwelt", "Handel und Geld", | |
| "Kleidung und Mode", "Garten"] | |
| # --------------------------------------------------------------------------- | |
| # Prompts | |
| # --------------------------------------------------------------------------- | |
| SYSTEM_WORDS = ("Du bist Experte für deutsche Rechtschreibung und Wortbildung. Du antwortest AUSSCHLIESSLICH " | |
| "mit einem JSON-Array aus Strings. Kein Markdown, keine Erklärungen, keine Nummerierung.") | |
| WORD_REQUESTS = { | |
| "dreifach": ("Nenne {n} deutsche Substantive zum Thema \"{thema}\", in denen ein Buchstabe dreimal (oder öfter) " | |
| "direkt hintereinander vorkommt, weil zwei Wortteile zusammenstoßen. Beispiele für das Prinzip: " | |
| "Schneeeule, Fetttropfen, Programmmusik, Teeernte. Regeln: nur Buchstaben, ohne Bindestrich, " | |
| "{lo} bis {hi} Zeichen lang, jedes Wort nur einmal."), | |
| "doppelt": ("Nenne {n} deutsche Substantive zum Thema \"{thema}\", die mindestens einen Doppelbuchstaben " | |
| "(derselbe Buchstabe zweimal direkt hintereinander) enthalten, aber KEINE Dreifachfolge. " | |
| "Beispiele: Sonnenschirm, Blitzgewitter, Ballonfahrt, Wollmütze. Regeln: nur Buchstaben, ohne " | |
| "Bindestrich, {lo} bis {hi} Zeichen lang, jedes Wort nur einmal."), | |
| "lang": ("Nenne {n} extrem lange deutsche Komposita zum Thema \"{thema}\" mit 25 bis {hi} Buchstaben. " | |
| "Beispiel für die Art: Rechtsschutzversicherungsgesellschaft. Regeln: nur Buchstaben, ohne " | |
| "Bindestrich, jedes Wort nur einmal."), | |
| } | |
| EXAMPLE_WORD = "Schneeeule" | |
| def canonical_number(n): | |
| ones = ["", "Eins", "Zwei", "Drei", "Vier", "Fünf", "Sechs", "Sieben", "Acht", "Neun", "Zehn", "Elf", "Zwölf", | |
| "Dreizehn", "Vierzehn", "Fünfzehn", "Sechzehn", "Siebzehn", "Achtzehn", "Neunzehn"] | |
| tens = {2: "zwanzig", 3: "dreißig", 4: "vierzig", 5: "fünfzig", 6: "sechzig", 7: "siebzig", 8: "achtzig", | |
| 9: "neunzig"} | |
| if n < 20: | |
| return ones[n] | |
| t, u = divmod(n, 10) | |
| if u == 0: | |
| return tens[t].capitalize() | |
| unit = "ein" if u == 1 else ones[u].lower() | |
| return (unit + "und" + tens[t]).capitalize() | |
| def build_think(word): | |
| chars = list(word) | |
| n = len(chars) | |
| lines = [TO, f"Wort: {word}", "Spreizung: " + " - ".join(chars), "Zählung:"] | |
| lines += [f"[Position {i}: {c}] -> Zähler: {i}." for i, c in enumerate(chars, 1)] | |
| lines += [f"Zur Sicherheit nachgezählt: {n}.", TC] | |
| return "\n".join(lines) | |
| def build_performance(n, comments): | |
| parts = [f"{canonical_number(i)}! Ah ah ah! ({comments[i - 1]})" for i in range(1, n + 1)] | |
| return " ".join(parts) + f" Das sind {n}." | |
| def system_example(): | |
| w, n = EXAMPLE_WORD, len(EXAMPLE_WORD) | |
| demo = build_think(w) + "\n" + build_performance(n, ["Donner", "Blitz"] * (n // 2)) | |
| return ( | |
| "Du schreibst Trainingsdaten für „Graf Zahl“. Du bekommst ein deutsches Wort und schreibst die Antwort des " | |
| "Grafen auf die Frage, wie viele Zeichen das Wort hat.\n\n" | |
| "Im " + TO + "-Block wendest du die SPREIZ-TECHNIK an, bevor du zählst:\n" | |
| "1. Zuerst das Wort nennen und es SPREIZEN: jedes Zeichen einzeln, getrennt durch ' - '.\n" | |
| "2. Dann Zeichen für Zeichen mit Position und Zähler durchgehen. Kein Schätzen, keine Gruppen.\n" | |
| "3. Doppelte und dreifache Buchstaben werden JEDES Mal einzeln aufgeführt und gezählt. Ein Buchstabe, der " | |
| "dreimal hintereinander steht, bekommt drei Positionen.\n" | |
| "4. Zum Schluss 'Zur Sicherheit nachgezählt: N.'\n\n" | |
| "Außerhalb des Blocks zählt der Graf laut bis N: jede Zahl als deutsches Zahlwort, dann 'Ah ah ah!' und " | |
| "eine kurze Donner/Blitz-Anmerkung in Klammern. Am Ende 'Das sind N.'\n\n" | |
| "Antworte NUR mit dem Antworttext. Kein JSON, kein Markdown, keine Erklärung davor oder danach.\n" | |
| "WICHTIG: Nach der Zeile 'Zur Sicherheit nachgezählt: N.' MUSS zwingend das Zählspektakel folgen (alle " | |
| "Zahlen von Eins bis N mit 'Ah ah ah!'). Beende die Antwort erst nach 'Das sind N.'\n\n" | |
| f"FORMAT (Beispiel für das Wort „{w}“, nur zur Orientierung; nutze das Wort aus der Nutzernachricht):\n" | |
| + demo | |
| ) | |
| def user_example(word): | |
| return f"Wort: {word}\nAnzahl der Zeichen (bereits geprüft): {len(word)}" | |
| USER_TEMPLATES = ["Wie viele Zeichen hat das Wort '{w}'?", "Zähle die Zeichen in '{w}'.", | |
| "Wie viele Buchstaben hat '{w}'?", "Bitte zähle die Zeichen des Wortes '{w}'.", | |
| "Zerlege und zähle das Wort: '{w}'"] | |
| # --------------------------------------------------------------------------- | |
| # Validierung | |
| # --------------------------------------------------------------------------- | |
| POS_RE = re.compile(r"\[Position\s*(\d+)\s*:\s*(.)\s*\]\s*(?:->|→)\s*Z[äa]hler\s*:\s*(\d+)\.?") | |
| PERF_RE = re.compile(r"([A-Za-zäöüÄÖÜß]+)!\s*Ah ah ah!\s*\(([^()\n]{1,80})\)") | |
| def max_run(w): | |
| return max(len(list(g)) for _, g in groupby(w.lower())) | |
| def word_ok(word, kat, exclude): | |
| if not LETTERS.match(word) or not (MIN_LEN <= len(word) <= MAX_LEN): | |
| return False | |
| low = word.lower() | |
| if any(t in low for t in exclude): | |
| return False | |
| r = max_run(word) | |
| if kat == "dreifach": | |
| return r >= 3 | |
| if kat == "doppelt": | |
| return r == 2 | |
| return len(word) >= 25 | |
| def validate_example(word, text): | |
| """Prueft die Antwort des 27B gegen das bekannte Wort. Rueckgabe: (assistant_text, fehler).""" | |
| text = text.replace(TO, "").replace(TC, "").strip() | |
| n = len(word) | |
| sm_end = re.search(rf"Zur Sicherheit nachgezählt:\s*{n}\.", text) | |
| if not sm_end: | |
| return None, "Sicherheitszeile fehlt oder falsch" | |
| think, perf = text[:sm_end.end()], text[sm_end.end():] | |
| wm = re.search(r"^Wort:\s*(.+)$", think, re.MULTILINE) | |
| if not wm or wm.group(1).strip() != word: | |
| return None, "Zeile 'Wort:' falsch" | |
| sm = re.search(r"^Spreizung:\s*(.+)$", think, re.MULTILINE) | |
| if not sm or [c.strip() for c in sm.group(1).split(" - ")] != list(word): | |
| return None, "Spreizung stimmt nicht mit dem Wort ueberein" | |
| pos = POS_RE.findall(think) | |
| if len(pos) != n: | |
| return None, f"{len(pos)} Positionen statt {n}" | |
| for i, (p, c, z) in enumerate(pos, 1): | |
| if int(p) != i or int(z) != i or c != word[i - 1]: | |
| return None, f"Position {i} falsch" | |
| items = PERF_RE.findall(perf) | |
| if len(items) != n: | |
| return None, f"{len(items)} Zahlen im Spektakel statt {n}" | |
| for i, (num, _) in enumerate(items, 1): | |
| if num.lower() != canonical_number(i).lower(): | |
| return None, f"Zahlwort {i}: {num!r}" | |
| if not re.search(rf"Das sind {n}\.\s*$", perf): | |
| return None, "Schluss 'Das sind N.' fehlt" | |
| return build_think(word) + "\n" + build_performance(n, [c.strip() for _, c in items]), None | |
| def load_thunder_comments(): | |
| """Haeufigste Donner/Blitz-Kommentare aus den bereinigten alten Daten (fuer den Fallback).""" | |
| c = Counter() | |
| if MASSIVE_V2.exists(): | |
| for line in open(MASSIVE_V2, encoding="utf-8"): | |
| a = json.loads(line)["messages"][2]["content"] | |
| for _, cm in PERF_RE.findall(a): | |
| cm = cm.strip() | |
| if cm and len(cm) <= 40 and not re.search(r"\d", cm): | |
| c[cm] += 1 | |
| return [k for k, _ in c.most_common(40)] or ["Donner", "Blitz"] | |
| def synthesize(word, comments, seed): | |
| """Komplettes Beispiel deterministisch aus der Wahrheit (Think-Block + Zaehlspektakel).""" | |
| rng = random.Random(seed) | |
| n = len(word) | |
| return build_think(word) + "\n" + build_performance(n, [rng.choice(comments) for _ in range(n)]) | |
| # --------------------------------------------------------------------------- | |
| # API | |
| # --------------------------------------------------------------------------- | |
| def call_model(system, user, max_tokens, temperature): | |
| payload = {"model": MODEL_ID, | |
| "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}], | |
| "max_tokens": max_tokens, "temperature": temperature, | |
| "chat_template_kwargs": {"enable_thinking": False}} | |
| req = urllib.request.Request(API_URL, data=json.dumps(payload).encode("utf-8"), | |
| headers={"Content-Type": "application/json"}, method="POST") | |
| with urllib.request.urlopen(req, timeout=600) as resp: | |
| return json.loads(resp.read().decode("utf-8"))["choices"][0]["message"]["content"] | |
| def parse_word_list(text): | |
| text = re.sub(r"^```[a-zA-Z]*\s*|\s*```$", "", text.strip()) | |
| a, b = text.find("["), text.rfind("]") | |
| if a == -1 or b <= a: | |
| return [] | |
| try: | |
| data = json.loads(text[a:b + 1], strict=False) | |
| except json.JSONDecodeError: | |
| return [] | |
| return [w.strip() for w in data if isinstance(w, str)] | |
| def load_excluded(): | |
| if not TEST_RESULTS.exists(): | |
| print(f"WARNUNG: {TEST_RESULTS} fehlt, Testwoerter werden NICHT ausgeschlossen!", flush=True) | |
| return set() | |
| return {r["wort"].lower() for r in json.load(open(TEST_RESULTS, encoding="utf-8"))} | |
| def build_category(kat, need, exclude, seen, seen_lock): | |
| got, reqs = [], 0 | |
| while len(got) < need and reqs < MAX_POOL_REQUESTS: | |
| reqs += 1 | |
| thema = random.choice(THEMEN) | |
| prompt = WORD_REQUESTS[kat].format(n=40, thema=thema, lo=MIN_LEN, hi=MAX_LEN) | |
| try: | |
| words = parse_word_list(call_model(SYSTEM_WORDS, prompt, 2000, 1.0)) | |
| except Exception as e: | |
| print(f" [{kat}] API-Fehler: {e}", flush=True) | |
| time.sleep(3) | |
| continue | |
| for w in words: | |
| with seen_lock: | |
| if w.lower() in seen or not word_ok(w, kat, exclude): | |
| continue | |
| seen.add(w.lower()) | |
| got.append(w) | |
| print(f" [{kat}] Anfrage {reqs} ({thema}): Pool {len(got)}/{need}", flush=True) | |
| return kat, got | |
| # Das 27B kann Dreifachfolgen nicht buchstabengenau bilden (es liefert nur Doppelbuchstaben oder Unsinn). | |
| # Deshalb: kuratierte Bausteine. A endet auf einen Doppelbuchstaben x, B beginnt mit x -> A+B hat x dreimal. | |
| TRIPLE_PARTS = { | |
| "f": ("Schiff Stoff Griff Kraftstoff Kunststoff Sauerstoff Wasserstoff Brennstoff Treibstoff Baustoff Werkstoff " | |
| "Zellstoff Farbstoff Klebstoff Sprengstoff Rohstoff Füllstoff Nährstoff Kohlenstoff Handgriff Türgriff", | |
| "Fahrt Flasche Farbe Fabrik Faser Filter Fläche Flocke Fluss Folie Fenster Feder Fetzen Fracht Flotte " | |
| "Fähre Falle Form Fass Frachter Fach Fleck"), | |
| "l": ("Ball Stall Fall Wall Zoll Schall Knall Metall Ausfall Anfall", | |
| "Lampe Licht Leiter Laden Leine Latte Land Lager Lehre Linie Liga Lauf Loch Lied Last Luft Lösung"), | |
| "t": ("Bett Brett Blatt Watt Fett Ballett Kabinett Brikett Schnitt Tritt Schritt", | |
| "Tuch Tisch Tasche Tür Turm Teller Tropfen Tanz Tee Tag Treppe Tier Ton Tor Trommel Truhe"), | |
| "e": ("Tee See Schnee Kaffee Klee Idee Fee Allee Armee Moschee Orchidee", | |
| "Ernte Ei Eule Ente Ecke Eis Erbse Elefant Ersatz Essen Ebene Echse Eimer Ehe"), | |
| "s": ("Fluss Nuss Kuss Guss Schluss Pass Fass Kongress Prozess Stress Abfluss Zufluss Schloss", | |
| "Sack Salz Schale Sand Saft Sonne Suppe Straße Stein Sturm Schiff Schlamm Stelle Spiel Spur Schrank " | |
| "Stück Schlüssel Strich"), | |
| "m": ("Schlamm Programm Stamm Damm Kamm Klamm Gramm Diagramm Kilogramm Telegramm", | |
| "Musik Meister Masse Mauer Motor Messe Milch Maschine Mühle Mantel Modell Mappe"), | |
| "n": ("Zinn Kinn Sinn Mann Gewinn Beginn Bann Wahnsinn", "Nadel Nerv Nase Name Nest Nuss Nummer Nachricht"), | |
| "z": ("Jazz", "Zeit Zentrum Zug Zimmer Zirkus Zauber"), | |
| "o": ("Zoo", "Orchester Ordnung Ort Ohr"), | |
| "p": ("Stopp Trupp", "Punkt Platz Pause Preis Plan"), | |
| } | |
| def triple_candidates(exclude): | |
| cands = [] | |
| for x, (a_words, b_words) in TRIPLE_PARTS.items(): | |
| for a in a_words.split(): | |
| assert a[-1].lower() == a[-2].lower() == x, a | |
| for b in b_words.split(): | |
| assert b[0].lower() == x, b | |
| c = a + b[0].lower() + b[1:] | |
| if word_ok(c, "dreifach", exclude): | |
| cands.append(c) | |
| return list(dict.fromkeys(cands)) | |
| def build_triple(kat, need, exclude, seen, seen_lock): | |
| cands = triple_candidates(exclude) | |
| random.shuffle(cands) | |
| got = [] | |
| for w in cands: | |
| if len(got) >= need: | |
| break | |
| with seen_lock: | |
| if w.lower() in seen: | |
| continue | |
| seen.add(w.lower()) | |
| got.append(w) | |
| print(f" [dreifach] {len(cands)} Komposita aus kuratierten Bausteinen, Pool {len(got)}/{need}", flush=True) | |
| return kat, got | |
| def build_pool(target, exclude): | |
| tok = None | |
| try: | |
| from transformers import AutoTokenizer | |
| tok = AutoTokenizer.from_pretrained(TOKENIZER_DIR) | |
| except Exception as e: | |
| print(f"Tokenizer nicht ladbar ({e}), keine Token-Priorisierung.", flush=True) | |
| seen, seen_lock = set(), threading.Lock() | |
| with ThreadPoolExecutor(max_workers=max(1, min(GEN_CONCURRENCY, len(QUOTAS)))) as ex: | |
| futs = [ex.submit(build_triple if kat == "dreifach" else build_category, kat, max(1, int(target * share * POOL_FACTOR)), exclude, seen, seen_lock) | |
| for kat, share in QUOTAS.items()] | |
| results = [f.result() for f in futs] | |
| pool = [] | |
| for kat, got in results: | |
| for w in got: | |
| rep = False | |
| if tok is not None: | |
| p = tok.tokenize(w) | |
| rep = any(a == b for a, b in zip(p, p[1:])) | |
| pool.append({"wort": w, "kat": kat, "gleiche_tokens_hintereinander": rep}) | |
| json.dump(pool, open(POOL_PATH, "w", encoding="utf-8"), ensure_ascii=False, indent=1) | |
| return pool | |
| # --------------------------------------------------------------------------- | |
| # Selbsttest / Prompt-Anzeige (ohne API) | |
| # --------------------------------------------------------------------------- | |
| def selftest(): | |
| assert [canonical_number(i) for i in (1, 12, 20, 21, 30, 31, 45)] == \ | |
| ["Eins", "Zwölf", "Zwanzig", "Einundzwanzig", "Dreißig", "Einunddreißig", "Fünfundvierzig"] | |
| for w in ("Schneeeule", "Fetttropfen", "Rechtsschutzversicherungsgesellschaft"): | |
| n = len(w) | |
| good = build_think(w) + "\n" + build_performance(n, ["Donner"] * n) | |
| out, err = validate_example(w, good) | |
| assert err is None and out == good, (w, err) | |
| w = "Schneeeule" | |
| n = len(w) | |
| good = build_think(w) + "\n" + build_performance(n, ["Blitz"] * n) | |
| bad = { | |
| "Spreizung ohne ein e": good.replace("e - e - e", "e - e"), | |
| "falsches Zahlwort": good.replace("Fünf!", "Vier!", 1), | |
| "fehlende Position": good.replace("[Position 6: e] -> Zähler: 6.\n", ""), | |
| "falsches Endergebnis": good.replace(f"Das sind {n}.", f"Das sind {n + 1}."), | |
| "Zaehler falsch": good.replace("Zähler: 7.", "Zähler: 8.", 1), | |
| "Sicherheitszeile fehlt": good.replace(f"Zur Sicherheit nachgezählt: {n}.\n", ""), | |
| } | |
| no_tags, err = validate_example(w, good.replace(TO + "\n", "").replace("\n" + TC, "")) | |
| assert err is None and no_tags == good, "Antwort ohne Tags muss akzeptiert und neu aufgebaut werden" | |
| for name, txt in bad.items(): | |
| assert validate_example(w, txt)[1] is not None, f"Fehler nicht erkannt: {name}" | |
| syn = synthesize("Sprengstofffabrik", ["Donner", "Blitz"], 1) | |
| assert validate_example("Sprengstofffabrik", syn)[1] is None, "Fallback-Beispiel muss die Validierung bestehen" | |
| assert word_ok("Schneeeule", "dreifach", set()) and not word_ok("Schneeeule", "doppelt", set()) | |
| assert word_ok("Sonnenschirm", "doppelt", set()) and not word_ok("Sonnenschirm", "dreifach", set()) | |
| assert not word_ok("Kaffeemaschinenhalter", "doppelt", {"kaffeemaschine"}) | |
| print("Selbsttest bestanden: Validierung erkennt alle 6 manipulierten Antworten, akzeptiert Antworten ohne Tags, Fallback-Synthese valide, Zahlwoerter 1..45 ok.") | |
| def show_prompts(): | |
| print("=" * 78 + "\nPHASE 1 - Wortliste (System)\n" + "=" * 78 + "\n" + SYSTEM_WORDS) | |
| for kat, t in WORD_REQUESTS.items(): | |
| print(f"\n--- User-Prompt Kategorie '{kat}' ---\n" + t.format(n=40, thema="Seefahrt", lo=MIN_LEN, hi=MAX_LEN)) | |
| print("\n" + "=" * 78 + "\nPHASE 2 - Beispiel (System)\n" + "=" * 78 + "\n" + system_example()) | |
| print("\n--- User-Prompt (pro Wort) ---\n" + user_example("Schifffahrt")) | |
| # --------------------------------------------------------------------------- | |
| # Produktion | |
| # --------------------------------------------------------------------------- | |
| def main(): | |
| global OUT_PATH, POOL_PATH, GEN_MAX | |
| if "--show-prompts" in sys.argv: | |
| return show_prompts() | |
| if "--selftest" in sys.argv: | |
| return selftest() | |
| if "--probe" in sys.argv: | |
| OUT_PATH = PROJECT_DIR / "dataset_hardcore_probe.jsonl" | |
| POOL_PATH = PROJECT_DIR / "word_pool_hardcore_probe.json" | |
| GEN_MAX = 3 | |
| OUT_PATH.unlink(missing_ok=True) | |
| POOL_PATH.unlink(missing_ok=True) | |
| print("PROBE-MODUS: 3 Beispiele, Ausgabe in *_probe-Dateien.", flush=True) | |
| v2_system = next(m["content"] for m in json.loads(open(V2_PATH).readline())["messages"] if m["role"] == "system") | |
| exclude = load_excluded() | |
| done = set() | |
| if OUT_PATH.exists(): | |
| for line in open(OUT_PATH, encoding="utf-8"): | |
| done.add(re.search(r"Wort: (\S+)", json.loads(line)["messages"][2]["content"]).group(1).lower()) | |
| print(f"API {API_URL} | Concurrency {GEN_CONCURRENCY} | Ziel {GEN_MAX} | ausgeschlossene Testwoerter {len(exclude)} " | |
| f"| schon vorhanden {len(done)}", flush=True) | |
| try: | |
| slots = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{GEN_PORT}/slots", timeout=10).read()) | |
| print(f"Server hat {len(slots)} Slot(s).", flush=True) | |
| except Exception: | |
| pass | |
| if POOL_PATH.exists(): | |
| pool = json.load(open(POOL_PATH, encoding="utf-8")) | |
| print(f"Wortpool aus {POOL_PATH} geladen: {len(pool)} Woerter", flush=True) | |
| else: | |
| print("Phase 1: Wortpool generieren ...", flush=True) | |
| pool = build_pool(GEN_MAX, exclude) | |
| for kat in QUOTAS: | |
| ws = [p for p in pool if p["kat"] == kat] | |
| print(f" {kat}: {len(ws)} Woerter, davon {sum(p['gleiche_tokens_hintereinander'] for p in ws)} mit " | |
| f"gleichen Tokens hintereinander", flush=True) | |
| todo, by_kat = [], {k: [p for p in pool if p["kat"] == k and p["wort"].lower() not in done] for k in QUOTAS} | |
| for k in by_kat: | |
| by_kat[k].sort(key=lambda p: not p["gleiche_tokens_hintereinander"]) | |
| credit = {k: 0.0 for k in QUOTAS} | |
| while len(todo) < GEN_MAX and any(by_kat.values()): | |
| for k, share in QUOTAS.items(): | |
| credit[k] += share | |
| k = max((k for k in QUOTAS if by_kat[k]), key=lambda k: credit[k]) | |
| credit[k] -= 1.0 | |
| todo.append(by_kat[k].pop(0)) | |
| print(f"Phase 2: {len(todo)} Beispiele erzeugen ...", flush=True) | |
| write_lock, stats_lock = threading.Lock(), threading.Lock() | |
| stats = {"ok": 0, "rescued": 0, "invalid": 0, "error": 0, "failed": 0} | |
| sys_prompt = system_example() | |
| comments = load_thunder_comments() | |
| print(f"Fallback-Kommentare: {len(comments)} aus {MASSIVE_V2.name}", flush=True) | |
| def write_example(item, idx, assistant, rescued): | |
| word = item["wort"] | |
| user = random.Random(idx).choice(USER_TEMPLATES).format(w=word) | |
| ex = {"messages": [{"role": "system", "content": v2_system}, {"role": "user", "content": user}, | |
| {"role": "assistant", "content": assistant}]} | |
| with write_lock: | |
| with open(OUT_PATH, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(ex, ensure_ascii=False) + "\n") | |
| if rescued: | |
| with open(RESCUED_PATH, "a", encoding="utf-8") as f: | |
| f.write(json.dumps({"wort": word, "kat": item["kat"]}, ensure_ascii=False) + "\n") | |
| with stats_lock: | |
| stats["rescued" if rescued else "ok"] += 1 | |
| return stats["ok"] + stats["rescued"] | |
| def one(item, idx): | |
| word = item["wort"] | |
| llm_answers = 0 | |
| for attempt in range(MAX_RETRY_PER_WORD): | |
| try: | |
| text = call_model(sys_prompt, user_example(word), MAX_TOKENS_EXAMPLE, GEN_TEMPERATURE) | |
| except Exception as e: | |
| with stats_lock: | |
| stats["error"] += 1 | |
| print(f" [{word}] API-Fehler: {e}", flush=True) | |
| time.sleep(3) | |
| continue | |
| llm_answers += 1 | |
| assistant, err = validate_example(word, text) | |
| if err: | |
| with stats_lock: | |
| stats["invalid"] += 1 | |
| print(f" [{word}] invalid ({attempt + 1}): {err}", flush=True) | |
| continue | |
| total = write_example(item, idx, assistant, rescued=False) | |
| print(f" OK #{total}: [{item['kat']}] {word} (N={len(word)})", flush=True) | |
| return | |
| if llm_answers == 0: | |
| with stats_lock: | |
| stats["failed"] += 1 | |
| print(f" [{word}] nur API-Fehler, KEIN Fallback (Server pruefen)", flush=True) | |
| return | |
| total = write_example(item, idx, synthesize(word, comments, idx), rescued=True) | |
| print(f" GERETTET #{total}: [{item['kat']}] {word} (N={len(word)}) durch Python-Fallback", flush=True) | |
| t0 = time.time() | |
| with ThreadPoolExecutor(max_workers=GEN_CONCURRENCY) as pool_ex: | |
| futs = {pool_ex.submit(one, it, i) for i, it in enumerate(todo)} | |
| while futs: | |
| _, futs = wait(futs, timeout=120) | |
| el = time.time() - t0 | |
| done_n = stats["ok"] + stats["rescued"] | |
| print(f"=== Status: {done_n} fertig ({stats['ok']} vom 27B, {stats['rescued']} gerettet), " | |
| f"{stats['invalid']} invalid, {stats['failed']} ohne Ergebnis, {stats['error']} Fehler | " | |
| f"{el:.0f}s | {done_n / max(el, 1) * 60:.1f}/min ===", flush=True) | |
| print(f"Fertig. {stats['ok'] + stats['rescued']} Beispiele -> {OUT_PATH} " | |
| f"(davon {stats['rescued']} durch Python gerettet, Woerter in {RESCUED_PATH.name})", flush=True) | |
| if __name__ == "__main__": | |
| main() | |