File size: 3,139 Bytes
6118a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Convert public memory datasets into compact JSONL used by train_v4.py.

- iapp/iapp_wiki_qa_squad (Thai Wikipedia extractive QA)  -> chunks + question + answer span
- Muennighoff/babi (20 bAbI tasks, state tracking / updates) -> story lines + question + answer
- nayohan/multi_session_chat (MSC) -> chit-chat sessions used ONLY as interference between sessions
- KimmoZZZ/locomo (LoCoMo) -> kept raw for evaluation only
"""
import ast, json, re, sys
from pathlib import Path
import pandas as pd

SRC = Path(__file__).resolve().parent / "external"
OUT = SRC / "prepared"
OUT.mkdir(exist_ok=True)


def sent_chunks(text: str, max_chars: int = 160) -> list[str]:
    parts = [p.strip() for p in re.split(r"(?<=[\s])(?=\S)|\n", text) if p.strip()]
    chunks, cur = [], ""
    for p in parts:
        if cur and len(cur) + len(p) + 1 > max_chars:
            chunks.append(cur.strip()); cur = p
        else:
            cur = (cur + " " + p) if cur else p
    if cur.strip():
        chunks.append(cur.strip())
    return chunks


def prep_iapp():
    for split in ("train", "validation", "test"):
        df = pd.read_parquet(SRC / f"iapp_wiki_qa_squad__{split}-00000-of-00001.parquet")
        rows = []
        for _, r in df.iterrows():
            ans = r["answers"]
            texts = list(ans["text"]) if hasattr(ans, "keys") or isinstance(ans, dict) else []
            if not texts or not texts[0].strip():
                continue
            a = str(texts[0]).strip()
            chunks = sent_chunks(str(r["context"]))
            gold = [i for i, c in enumerate(chunks) if a in c]
            if not gold or len(a) > 60:
                continue
            g = gold[0]
            lo = max(0, g - 1)
            rows.append({"title": r["title"], "chunks": chunks[lo:g + 2], "q": str(r["question"]).strip(), "a": a})
        (OUT / f"iapp_{split}.jsonl").write_text("\n".join(json.dumps(x, ensure_ascii=False) for x in rows), encoding="utf-8")
        print("iapp", split, len(rows))


def prep_babi():
    for split in ("train", "valid", "test"):
        rows = []
        for line in open(SRC / f"babi__babi_{split}.jsonl", encoding="utf-8"):
            x = json.loads(line)
            lines = [l.strip() for l in x["passage"].split("\n") if l.strip()]
            if len(lines) > 24:
                continue
            rows.append({"task": int(x["task"]), "lines": lines, "q": x["question"].strip(), "a": str(x["answer"]).strip()})
        (OUT / f"babi_{split}.jsonl").write_text("\n".join(json.dumps(x, ensure_ascii=False) for x in rows), encoding="utf-8")
        print("babi", split, len(rows))


def prep_msc():
    df = pd.read_parquet(next(SRC.glob("multi_session_chat__validation-*.parquet")))
    rows = []
    for _, r in df.iterrows():
        d = r["dialogue"]
        utts = [str(u) for u in (list(d) if not isinstance(d, str) else ast.literal_eval(d))]
        if len(utts) >= 4:
            rows.append(utts[:12])
    (OUT / "msc_chitchat.jsonl").write_text("\n".join(json.dumps(x, ensure_ascii=False) for x in rows), encoding="utf-8")
    print("msc", len(rows))


prep_iapp(); prep_babi(); prep_msc()