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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# scripts/pull_phasmophobia_wiki.py

from __future__ import annotations

import json
import re
import time
from pathlib import Path
from urllib.parse import quote

import requests
from bs4 import BeautifulSoup
from tqdm.auto import tqdm


API_URL = "https://phasmophobia.fandom.com/api.php"
BASE_URL = "https://phasmophobia.fandom.com/wiki"

OUT_DIR = Path("Resources/Documents")
OUT_DOCS = OUT_DIR / "phasmophobia_wiki_docs.jsonl"
OUT_CHUNKS = OUT_DIR / "phasmophobia_wiki_chunks.jsonl"


SESSION = requests.Session()
SESSION.headers.update({
    "User-Agent": "MultimodalReasoningBot/0.1 clean-document-pull"
})

REMOVE_SELECTORS = [
    "script",
    "style",
    "noscript",
    "figure",
    "img",
    "audio",
    "video",
    "iframe",
    "sup.reference",
    ".reference",
    ".references",
    ".reflist",
    ".mw-editsection",
    ".mw-empty-elt",
    ".toc",
    "#toc",
    ".portable-infobox",
    ".infobox",
    ".navbox",
    ".metadata",
    ".ambox",
    ".catlinks",
    ".printfooter",
    ".noprint",
    ".thumb",
    ".gallery",
    ".wikia-gallery",
    ".pi-image",
    ".pi-data",
    ".pi-header",
    ".pi-title",
    ".page-header",
    ".page-footer",
    ".license-description",
    ".WikiaArticleFooter",
    ".rail-module",
]


SKIP_TITLE_PREFIXES = (
    "User:",
    "User talk:",
    "Talk:",
    "File:",
    "Template:",
    "Category:",
    "Help:",
    "Forum:",
    "Blog:",
    "MediaWiki:",
    "Module:",
)


SKIP_EXACT_TITLES = {
    "Main Page",
}


BAD_LINE_PATTERNS = [
    r"^advertisement$",
    r"^contents$",
    r"^categories$",
    r"^references$",
    r"^gallery$",
    r"^trivia$",
    r"^see also$",
    r"^external links$",
    r"^community content is available",
    r"^fandom apps",
    r"^take your favorite fandoms",
    r"^explore properties",
    r"^view mobile site",
    r"^follow on",
    r"^sign in",
    r"^create a free account",
]


def api_get(params: dict) -> dict:
    params = {
        "format": "json",
        "formatversion": "2",
        **params,
    }

    for attempt in range(5):
        r = SESSION.get(API_URL, params=params, timeout=30)

        if r.status_code == 429:
            time.sleep(2 + attempt)
            continue

        r.raise_for_status()
        return r.json()

    raise RuntimeError(f"API failed after retries: {params}")


def get_all_pages() -> list[dict]:
    pages = []
    apcontinue = None

    while True:
        params = {
            "action": "query",
            "list": "allpages",
            "apnamespace": 0,
            "aplimit": "max",
            "apfilterredir": "nonredirects",
        }

        if apcontinue:
            params["apcontinue"] = apcontinue

        data = api_get(params)
        pages.extend(data.get("query", {}).get("allpages", []))

        cont = data.get("continue", {})
        apcontinue = cont.get("apcontinue")

        if not apcontinue:
            break

    clean = []

    for page in pages:
        title = page["title"].strip()

        if title in SKIP_EXACT_TITLES:
            continue

        if title.startswith(SKIP_TITLE_PREFIXES):
            continue

        clean.append(page)

    return clean


def get_parsed_html(pageid: int) -> str | None:
    data = api_get({
        "action": "parse",
        "pageid": pageid,
        "prop": "text|displaytitle",
        "redirects": "1",
        "disableeditsection": "1",
        "disabletoc": "1",
    })

    parsed = data.get("parse")
    if not parsed:
        return None

    text = parsed.get("text")

    if isinstance(text, dict):
        return text.get("*")

    return text


def clean_line(line: str) -> str:
    line = re.sub(r"\[\s*edit\s*\]", "", line, flags=re.I)
    line = re.sub(r"\[\d+\]", "", line)
    line = re.sub(r"\s+", " ", line)
    return line.strip()


def is_bad_line(line: str) -> bool:
    if not line:
        return True

    low = line.lower().strip()

    if len(low) <= 1:
        return True

    for pattern in BAD_LINE_PATTERNS:
        if re.search(pattern, low):
            return True

    if low.startswith("http://") or low.startswith("https://"):
        return True

    if "retrieved from" in low:
        return True

    if "fandom.com" in low and len(low.split()) < 16:
        return True

    return False


def html_to_clean_text(html: str, keep_tables: bool = False) -> str:
    soup = BeautifulSoup(html, "lxml")

    root = soup.select_one(".mw-parser-output")
    if root is None:
        root = soup

    for selector in REMOVE_SELECTORS:
        for tag in root.select(selector):
            tag.decompose()

    if not keep_tables:
        for tag in root.find_all("table"):
            tag.decompose()

    blocks = []

    for tag in root.find_all(["h2", "h3", "h4", "p", "li"]):
        text = clean_line(tag.get_text(" ", strip=True))

        if is_bad_line(text):
            continue

        if tag.name in {"h2", "h3", "h4"}:
            # Keep useful section boundaries, but not table-of-contents garbage.
            blocks.append(f"\n## {text}\n")
        else:
            blocks.append(text)

    text = "\n".join(blocks)
    text = re.sub(r"\n{3,}", "\n\n", text)
    text = re.sub(r"[ \t]{2,}", " ", text)
    return text.strip()


def title_to_url(title: str) -> str:
    return f"{BASE_URL}/{quote(title.replace(' ', '_'))}"


def pull_docs(limit: int | None = None, test_pages: list[str] | None = None) -> list[dict]:
    OUT_DIR.mkdir(parents=True, exist_ok=True)

    if test_pages:
        all_pages = get_all_pages()
        wanted = {x.lower() for x in test_pages}
        pages = [p for p in all_pages if p["title"].lower() in wanted]
    else:
        pages = get_all_pages()

    if limit is not None:
        pages = pages[:limit]

    print(f"[Pull] Pages selected: {len(pages)}")

    records = []

    for page in tqdm(pages, desc="Pulling Phasmophobia wiki"):
        pageid = int(page["pageid"])
        title = page["title"].strip()

        try:
            html = get_parsed_html(pageid)

            if not html:
                continue

            text = html_to_clean_text(html, keep_tables=False)

            # Skip pages that are only nav/category/etc.
            if len(text.split()) < 40:
                continue

            records.append({
                "source": "phasmophobia.fandom.com",
                "pageid": pageid,
                "title": title,
                "url": title_to_url(title),
                "text": text,
            })

            time.sleep(0.05)

        except Exception as e:
            print(f"[WARN] Failed {title}: {e}")

    return records


def chunk_text(text: str, chunk_words: int = 256, overlap: int = 48) -> list[str]:
    words = text.split()

    if len(words) <= chunk_words:
        return [" ".join(words)]

    chunks = []
    step = max(1, chunk_words - overlap)

    for start in range(0, len(words), step):
        piece = words[start:start + chunk_words]

        if len(piece) < 40:
            continue

        chunks.append(" ".join(piece))

    return chunks


def save_docs(records: list[dict]) -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)

    with OUT_DOCS.open("w", encoding="utf-8") as f:
        for record in records:
            f.write(json.dumps(record, ensure_ascii=False) + "\n")

    print(f"[Save] Docs: {OUT_DOCS} ({len(records)} records)")


def save_chunks(records: list[dict], chunk_words: int = 256, overlap: int = 48) -> None:
    count = 0

    with OUT_CHUNKS.open("w", encoding="utf-8") as f:
        for record in records:
            chunks = chunk_text(
                record["text"],
                chunk_words=chunk_words,
                overlap=overlap,
            )

            for chunk_id, chunk in enumerate(chunks):
                f.write(json.dumps({
                    "source": record["source"],
                    "title": record["title"],
                    "url": record["url"],
                    "pageid": record["pageid"],
                    "chunk_id": chunk_id,
                    "text": chunk,
                }, ensure_ascii=False) + "\n")

                count += 1

    print(f"[Save] Chunks: {OUT_CHUNKS} ({count} chunks)")


def preview(records: list[dict], max_docs: int = 5, chars: int = 1200) -> None:
    for record in records[:max_docs]:
        print("=" * 100)
        print(record["title"])
        print(record["url"])
        print("-" * 100)
        print(record["text"][:chars])


def quality_check(records: list[dict]) -> None:
    bad_markers = [
        "Advertisement",
        "Fandom Apps",
        "Take your favorite fandoms",
        "View Mobile Site",
        "Create a Free Account",
        "Sign In",
        "Retrieved from",
    ]

    print("\n[Quality Check]")

    for marker in bad_markers:
        hits = [
            r["title"]
            for r in records
            if marker.lower() in r["text"].lower()
        ]

        print(f"{marker!r}: {len(hits)} hits")

        if hits[:5]:
            print("  sample:", hits[:5])


def main():
    # Test first against known pages I checked manually:
    # Phasmophobia, Ghost, Map
    test = False

    if test:
        records = pull_docs(test_pages=["Phasmophobia", "Ghost", "Map"])
    else:
        records = pull_docs()

    save_docs(records)
    save_chunks(records, chunk_words=256, overlap=48)
    quality_check(records)
    preview(records, max_docs=3)


if __name__ == "__main__":
    main()