File size: 17,333 Bytes
2f0ea11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python3
"""v4-Zaehldaten (deterministisch): Zeichen zaehlen, Buchstabenhaeufigkeit, Buchstaben insgesamt, Woerter zaehlen.

Ohne System-Prompt, ohne Persona, ohne Zaehlshow: <think> mit Spreizung/Zaehlung, danach ein normaler Satz.
Jedes Beispiel wird gegen die bekannte Wahrheit validiert. Testtexte (alle Test-Sets) sind ausgeschlossen.

Ausgabe: v4/counting_v4.jsonl (Felder: messages, kind, text). Aufruf: v4_data.py [--selftest]
"""
import json
import os
import random
import re
import string
import sys
from collections import Counter
from pathlib import Path

os.environ["CUDA_VISIBLE_DEVICES"] = ""
sys.path.insert(0, "/mnt/models/graf_zahl")
from generate_hardcore_massive import TC, TO  # noqa: E402
from v3_data import (SPACE, code_like, compound, load_sentences, misc_string, rand_alnum, rand_sym, runs, sym)  # noqa: E402
import v4_tests  # noqa: E402

PLATTE = "/home/david/Schreibtisch/Platte"
V4 = Path(f"{PLATTE}/models/graf_zahl/v4")
SEED = 44
COUNTS = {"len_old": 1900, "len_de_word": 700, "len_de_sent": 500, "len_en_sent": 330, "len_en_word": 250, "len_code_misc": 320,
          "len_periodic": 480, "len_long": 420, "letter": 1500, "letters_all": 350, "words": 400}


# ----------------------------------------------------------------------------- Think-Bloecke
def think_len(text):
    n = len(text)
    lines = [TO, f"Wort: {text}", "Spreizung: " + " - ".join(sym(c) for c in text), "Zählung:"]
    lines += [f"[Position {i}: {sym(c)}] -> Zähler: {i}." for i, c in enumerate(text, 1)]
    lines += [f"Zur Sicherheit nachgezählt: {n}.", TC]
    return "\n".join(lines)


def think_tally(text, label, pred):
    tally, lines = 0, [TO, f"Wort: {text}", f"Gesucht: {label}", "Spreizung: " + " - ".join(sym(c) for c in text), "Zählung:"]
    for i, c in enumerate(text, 1):
        hit = pred(c)
        tally += hit
        lines.append(f"[Position {i}: {sym(c)}] -> {'ja!' if hit else 'nein.'} Bisher: {tally}.")
    lines += [f"Zur Sicherheit nachgezählt: {tally}.", TC]
    return "\n".join(lines), tally


def think_words(text):
    words = text.split()
    lines = [TO, f"Satz: {text}", "Zählung nach Wörtern (durch Leerzeichen getrennt):"]
    lines += [f"[Wort {i}: {w}] -> Zähler: {i}." for i, w in enumerate(words, 1)]
    lines += [f"Zur Sicherheit nachgezählt: {len(words)}.", TC]
    return "\n".join(lines), len(words)


# ----------------------------------------------------------------------------- Antwort-Saetze
def echo_ok(text):
    return len(text) <= 30 and "„" not in text and "“" not in text and "\n" not in text


def ans_len(text, n, lang, letters_word):
    unit_de = "Buchstaben" if letters_word else "Zeichen"
    unit_en = "letters" if letters_word else "characters"
    if lang == "de":
        if " " not in text and text.isalpha() and echo_ok(text):
            return f"Das Wort „{text}“ hat {n} {unit_de}."
        if " " in text:
            return f"Der Text hat {n} {unit_de} (Leerzeichen eingerechnet)." if not letters_word else f"Der Text hat {n} Zeichen (Leerzeichen eingerechnet)."
        return f"Der String hat {n} Zeichen."
    if " " not in text and text.isalpha() and echo_ok(text):
        return f"The word “{text}” has {n} {unit_en}."
    if " " in text:
        return f"The text has {n} characters (spaces included)."
    return f"The string has {n} characters."


def cap(s):
    return s[:1].upper() + s[1:]


def ans_letter(text, c, k, lang):
    what_de = "die Ziffer" if c.isdigit() else "der Buchstabe"
    what_en = "digit" if c.isdigit() else "letter"
    if lang == "de":
        if echo_ok(text):
            return f"In „{text}“ kommt {what_de} „{c}“ nicht vor (0-mal)." if k == 0 else f"{cap(what_de)} „{c}“ kommt {k}-mal in „{text}“ vor."
        return f"{cap(what_de)} „{c}“ kommt nicht vor (0-mal)." if k == 0 else f"{cap(what_de)} „{c}“ kommt {k}-mal vor."
    if echo_ok(text):
        return f"The {what_en} “{c}” does not appear in “{text}” (0 times)." if k == 0 else f"The {what_en} “{c}” appears {k} times in “{text}”."
    return f"The {what_en} “{c}” does not appear (0 times)." if k == 0 else f"The {what_en} “{c}” appears {k} times."


def ans_words(n, lang):
    if lang == "de":
        return "Der Satz hat 1 Wort." if n == 1 else f"Der Satz hat {n} Wörter."
    return "The sentence has 1 word." if n == 1 else f"The sentence has {n} words."


# ----------------------------------------------------------------------------- Prompts
LEN_DE = ["Wie viele Zeichen hat {q}?", "Wie viele Zeichen hat das Wort {q}?", "Zähle die Zeichen in {q}.", "Wie lang ist {q}?",
          "Bitte zähle alle Zeichen von {q}.", "Hey, wie viele Zeichen hat {q}?", "Kannst du mir sagen, wie viele Zeichen {q} hat?",
          "Zerlege und zähle: {q}", "Wie viele Zeichen hat der String {q}?"]
LEN_EN = ["How many characters does {q} have?", "How many characters are in {q}?", "Count the characters in {q}.",
          "What is the length of {q}?", "How long is {q} (in characters)?"]
LETTER_DE = ["Wie viele {c} sind in {q}?", "Wie oft kommt der Buchstabe {c} in {q} vor?", "Zähle die {c} in {q}.", "Wie viele {c} hat {q}?",
             "Wie oft steckt ein {c} in {q}?", "Kommt in {q} ein {c} vor? Wie oft?", "Zähle bitte alle {c} in dem Wort {q}."]
LETTER_EN = ["How many {c}'s are in {q}?", "How many times does the letter {c} appear in {q}?", "Count the {c} in {q}.",
             "How often does {c} occur in {q}?"]
LETTERS_ALL_DE = ["Wie viele Buchstaben hat {q}?", "Wie viele Buchstaben (ohne Leerzeichen und Satzzeichen) hat {q}?", "Zähle nur die Buchstaben in {q}."]
LETTERS_ALL_EN = ["How many letters are in {q}?", "Count only the letters in {q} (no spaces or punctuation)."]
WORDS_DE = ["Wie viele Wörter hat dieser Satz: {q}?", "Zähle die Wörter in {q}.", "Wie viele Wörter sind in {q}?", "Aus wie vielen Wörtern besteht {q}?"]
WORDS_EN = ["How many words are in {q}?", "Count the words in {q}.", "How many words does this sentence have: {q}"]


def quote(s):
    for a, b in (("'", "'"), ('"', '"'), ("«", "»")):
        if a not in s and b not in s:
            return f"{a}{s}{b}"
    return f"«{s}»"


def fmt_q(text, r, bare_ok=True):
    if bare_ok and " " not in text and text.isalpha() and r.random() < 0.35:
        return text
    return quote(text)


# ----------------------------------------------------------------------------- Beispiel-Builder
def ex(kind, text, user, assistant, extra=None):
    d = {"messages": [{"role": "user", "content": user}, {"role": "assistant", "content": assistant}], "kind": kind, "text": text}
    if extra:
        d.update(extra)
    return d


def make_len(text, lang, r):
    words_only = " " not in text and text.isalpha()
    tpl = r.choice(LEN_DE if lang == "de" else LEN_EN)
    if lang == "de" and words_only and r.random() < 0.2:
        tpl = "Wie viele Buchstaben hat {q}?"
    user = tpl.format(q=fmt_q(text, r))
    if " " in text and r.random() < 0.35:
        user += " Leerzeichen zählen mit." if lang == "de" else " Count the spaces too."
    letters_word = words_only and "Buchstaben" in user
    return ex("len", text, user, think_len(text) + "\n" + ans_len(text, len(text), lang, letters_word))


def make_letter(text, c, lang, r):
    think, k = think_tally(text, f"{c} (Groß-/Kleinschreibung egal)", lambda x: x.lower() == c.lower())
    tpl = r.choice(LETTER_DE if lang == "de" else LETTER_EN)
    user = tpl.format(c=c, q=fmt_q(text, r))
    return ex("letter", text, user, think + "\n" + ans_letter(text, c, k, lang), {"target": c})


def make_letters_all(text, lang, r):
    think, k = think_tally(text, "alle Buchstaben (ohne Leerzeichen, Ziffern und Satzzeichen)", lambda x: x.isalpha())
    tpl = r.choice(LETTERS_ALL_DE if lang == "de" else LETTERS_ALL_EN)
    user = tpl.format(q=quote(text))
    ans = (f"Der Text hat {k} Buchstaben." if lang == "de" else f"The text has {k} letters.")
    return ex("letters_all", text, user, think + "\n" + ans, {"target": "*"})


def make_words(text, lang, r):
    think, n = think_words(text)
    tpl = r.choice(WORDS_DE if lang == "de" else WORDS_EN)
    return ex("words", text, tpl.format(q=quote(text)), think + "\n" + ans_words(n, lang))


# ----------------------------------------------------------------------------- Validierung
NUM_RE = re.compile(r"(\d+)(?:-mal| times| Zeichen| characters| Buchstaben| letters| Wörter| words| Wort| word)")


def final_number(after_think):
    m = NUM_RE.findall(after_think)
    if m:
        return int(m[-1])
    nums = re.findall(r"\d+", after_think)
    return int(nums[-1]) if nums else None


def validate(e):
    a = e["messages"][1]["content"]
    text, kind = e["text"], e["kind"]
    if kind == "len":
        think, truth = think_len(text), len(text)
    elif kind == "letter":
        c = e["target"]
        think, truth = think_tally(text, f"{c} (Groß-/Kleinschreibung egal)", lambda x: x.lower() == c.lower())
    elif kind == "letters_all":
        think, truth = think_tally(text, "alle Buchstaben (ohne Leerzeichen, Ziffern und Satzzeichen)", lambda x: x.isalpha())
    else:
        think, truth = think_words(text)
    if not a.startswith(think + "\n"):
        return "Think-Block weicht ab"
    fn = final_number(a[len(think) + 1:])
    return None if fn == truth else f"Endzahl {fn} != {truth}"


# ----------------------------------------------------------------------------- Textquellen
def periodic(r, lo, hi):
    n = r.randint(lo, hi)
    alph = string.ascii_letters + string.digits + "!#$%&*+=?_.:;,@/|~^"
    unit_len = r.choice([1, 1, 2, 2, 2, 3, 3, 4])
    unit = "".join(r.choice(alph) for _ in range(unit_len))
    if r.random() < 0.4:
        unit = unit + " "                       # z. B. 'ha ha ha ', 'a a a '
    s = (unit * (n // len(unit) + 2))[:n]
    return s.strip() if r.random() < 0.8 else s.rstrip()


def load_excluded():
    strings = set(v4_tests.all_test_strings())
    words = set()
    for f in ("ab_test_results.json", "generalization_results.json", "v3/independent_results_v3.json", "v3/heldout_v3.json"):
        p = Path(f"{PLATTE}/models/graf_zahl/{f}")
        if p.exists():
            for r in json.load(open(p, encoding="utf-8")):
                t = r.get("wort") or r.get("text")
                strings.add(t)
    for t in list(strings):
        if t.isalpha() and len(t) >= 6:
            words.add(t.lower())
    return words, strings


def load_v3_texts(excl_words, excl_strings):
    out = []
    for line in open(f"{PLATTE}/models/graf_zahl/v3/dataset_v3_plain.jsonl", encoding="utf-8"):
        t = re.search(r"^Wort: (.+)$", json.loads(line)["messages"][2]["content"], re.M).group(1)
        if t not in excl_strings and not any(w in t.lower() for w in excl_words):
            out.append(t)
    return sorted(set(out))


def natural_words(sentences):
    ws = set()
    for s in sentences:
        for w in s.split():
            w = w.strip(".,;:!?()\"'-")
            if 5 <= len(w) <= 18 and w.isalpha():
                ws.add(w)
    return sorted(ws)


def build(seed=SEED):
    r = random.Random(seed)
    excl_words, excl_strings = load_excluded()
    de_sent = load_sentences(excl_words)
    pools = json.load(open(V4 / "replay_prompts.json", encoding="utf-8"))
    en_sent = [s for s in pools["en_sentences"] if not any(w in s.lower() for w in excl_words)]
    de_words = [w for w in natural_words(de_sent) if w.lower() not in excl_words]
    en_words = [w for w in pools["en_words"] if w.lower() not in excl_words]
    old = load_v3_texts(excl_words, excl_strings)
    old_words = [t for t in old if t.isalpha()]
    print(f"Pools: DE-Saetze {len(de_sent)}, EN-Saetze {len(en_sent)}, DE-Woerter {len(de_words)}, EN-Woerter {len(en_words)}, "
          f"alte Texte {len(old)} (davon Woerter {len(old_words)})", flush=True)

    taken, rows = set(), []

    def add(e, cat):
        key = (e["kind"], e["text"], e.get("target"))
        if key in taken or e["text"] in excl_strings or e["text"] != e["text"].strip() or "  " in e["text"] or not (1 <= len(e["text"]) <= 95):
            return False
        if validate(e) is not None:
            raise AssertionError((cat, e["text"], validate(e)))
        taken.add(key)
        e["cat"] = cat
        rows.append(e)
        return True

    def lang_for(text_lang):
        return text_lang if r.random() < 0.88 else ("en" if text_lang == "de" else "de")

    def fill(cat, n, gen):
        c = tries = 0
        while c < n and tries < n * 60:
            tries += 1
            item = gen()
            if item is not None:
                c += add(item, cat)

    fill("len_old", COUNTS["len_old"], lambda: make_len(r.choice(old), lang_for("de"), r))
    fill("len_de_word", COUNTS["len_de_word"], lambda: make_len(r.choice(de_words), lang_for("de"), r))
    fill("len_de_sent", COUNTS["len_de_sent"], lambda: make_len(r.choice(de_sent), lang_for("de"), r))
    fill("len_en_sent", COUNTS["len_en_sent"], lambda: make_len(r.choice(en_sent), lang_for("en"), r))
    fill("len_en_word", COUNTS["len_en_word"], lambda: make_len(r.choice(en_words), lang_for("en"), r))
    fill("len_code_misc", COUNTS["len_code_misc"], lambda: make_len(code_like(r, de_words[:400]) if r.random() < 0.6 else misc_string(r, de_words[:400]), lang_for("de"), r))
    fill("len_periodic", COUNTS["len_periodic"], lambda: make_len(periodic(r, 6, 90), lang_for("de"), r))

    def long_text():
        k = r.random()
        if k < 0.30: return rand_alnum(r, r.randint(46, 90))
        if k < 0.50: return rand_sym(r, r.randint(46, 90))
        if k < 0.70: return compound(r, [w for w in old_words if 5 <= len(w) <= 30], 46, 90)
        return r.choice([s for s in (de_sent if r.random() < 0.7 else en_sent) if len(s) >= 46] or [None])
    fill("len_long", COUNTS["len_long"], lambda: (lambda t: make_len(t, lang_for("de"), r) if t else None)(long_text()))

    def letter_item():
        src = r.random()
        if src < 0.40: text, lang = r.choice(de_words), "de"
        elif src < 0.55: text, lang = r.choice(old_words), "de"
        elif src < 0.72: text, lang = r.choice(de_sent), "de"
        elif src < 0.90: text, lang = r.choice(en_words if r.random() < 0.6 else en_sent), "en"
        elif src < 0.95: text, lang = periodic(r, 6, 40), "de"
        else: text, lang = rand_alnum(r, r.randint(8, 30)), "de"
        if not text:
            return None
        chars = [c for c in text if c.isalnum()]
        if not chars:
            return None
        mode = r.random()
        counts = Counter(c.lower() for c in chars)
        if mode < 0.14:
            absent = [c for c in "abcdefghijklmnopqrstuvwxyz" if c not in counts]
            if not absent: return None
            c = r.choice(absent)
        elif mode < 0.55:
            multi = [c for c, k in counts.items() if k >= 2]
            c = r.choice(multi or list(counts))
        else:
            c = r.choice(list(counts))
        if r.random() < 0.2 and c.isalpha():
            c = c.upper()
        return make_letter(text, c, lang_for(lang), r)
    fill("letter", COUNTS["letter"], letter_item)

    fill("letters_all", COUNTS["letters_all"], lambda: (lambda s: make_letters_all(s, "de" if s in de_sent_set else "en", r))(r.choice(de_sent if r.random() < 0.75 else en_sent)))
    fill("words", COUNTS["words"], lambda: (lambda s: make_words(s, "de" if s in de_sent_set else "en", r))(r.choice(de_sent if r.random() < 0.75 else en_sent)))
    return rows


de_sent_set = set()


def main():
    global de_sent_set
    V4.mkdir(parents=True, exist_ok=True)
    de_sent_set = set(load_sentences(load_excluded()[0]))
    rows = build()
    random.Random(SEED).shuffle(rows)
    with open(V4 / "counting_v4.jsonl", "w", encoding="utf-8") as f:
        for e in rows:
            f.write(json.dumps(e, ensure_ascii=False) + "\n")
    print(f"\n{len(rows)} Zaehl-Beispiele, alle gegen die Wahrheit validiert -> {V4 / 'counting_v4.jsonl'}")
    print("nach Aufgabentyp:", dict(Counter(e['kind'] for e in rows)))
    print("nach Quelle:", dict(Counter(e['cat'] for e in rows)))
    L = [len(e["text"]) for e in rows]
    print(f"Textlaenge: Median {sorted(L)[len(L)//2]}, max {max(L)}; > 45 Zeichen: {sum(l > 45 for l in L)}, mit Leerzeichen: {sum(' ' in e['text'] for e in rows)}")


def selftest():
    r = random.Random(1)
    for kind_fn in (lambda: make_len("Erdbee re", "de", r), lambda: make_letter("Erdbeere", "r", "de", r), lambda: make_letter("Zebra", "q", "en", r),
                    lambda: make_letters_all("Hallo, Welt 2!", "de", r), lambda: make_words("Der Hund läuft.", "de", r), lambda: make_len("abababab", "en", r)):
        e = kind_fn()
        assert validate(e) is None, e
        e["messages"][1]["content"] = e["messages"][1]["content"].replace("nachgezählt: ", "nachgezählt: 9")
        assert validate(e) is not None
    e = make_letter("Erdbeere", "r", "de", r)
    assert "Bisher: 2." in e["messages"][1]["content"] and "kommt 2-mal" in e["messages"][1]["content"], e["messages"][1]["content"]
    p = periodic(r, 6, 40)
    assert 1 <= len(p) <= 40
    print("Selbsttest bestanden. Beispiel-Buchstabe:\n" + e["messages"][0]["content"] + "\n" + e["messages"][1]["content"])


if __name__ == "__main__":
    selftest() if "--selftest" in sys.argv else main()