-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretrieve_chess_content.py
More file actions
executable file
·1638 lines (1393 loc) · 61.2 KB
/
retrieve_chess_content.py
File metadata and controls
executable file
·1638 lines (1393 loc) · 61.2 KB
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
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Retrieve and convert chess content for training-data preparation.
This script downloads PGN game databases and Internet Archive chess books,
then converts PGN games into natural-language prose suitable for LLM
training. It is organised into independent **phases** that can be run
individually for easy testing and incremental builds.
Phase 1 — Download PGN databases (PGN Mentor player/event files,
Lumbras Gigabase)
Phase 2 — Convert downloaded PGN to narrative text (pre-1969 filter)
Phase 3 — Download public-domain chess books from Internet Archive
Phase 2 safety mechanisms:
- Per-game parse timeout (GAME_PARSE_TIMEOUT, default 30s)
- Per-file wall-clock timeout (dynamic: FILE_PARSE_TIMEOUT base + per-MB scaling)
- Consecutive-error detection (MAX_CONSECUTIVE_ERRORS, default 10)
- Automatic skip-ahead to the next game on parse failures
- Files sorted largest-first for better parallel utilisation
- Optional parallel mode via --workers N
Post-processed output is written to the *corpus* subdirectory inside
$CHESS_DATA in JSONL format, ready for tokenisation.
Gutenberg chess books are handled separately by retrieve_gutenberg.py
(Chess & Strategy category) — see Chess-Setup.md for details.
Environment Variables:
CHESS_DATA: Base directory for chess data (default: /mnt/data/chess)
"""
import getpass
import glob
import grp
import io
import json
import os
import pwd
import re
import signal
import subprocess
import sys
import tempfile
import time
import zipfile
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from urllib.parse import urljoin, urlparse
import urllib3
import warnings
import requests
from bs4 import BeautifulSoup
# Suppress InsecureRequestWarning for sites with expired SSL certs
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
try:
from tqdm import tqdm
except ImportError:
tqdm = None
try:
import chess
import chess.pgn
HAS_PYTHON_CHESS = True
except ImportError:
HAS_PYTHON_CHESS = False
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
TEMPORAL_CUTOFF_YEAR = 1969
TEMPORAL_CUTOFF_DATE = "1969.07.20"
# Phase 2 — parsing safety limits
GAME_PARSE_TIMEOUT = 30 # seconds: max time for a single read_game() call
FILE_PARSE_TIMEOUT = 300 # seconds: base wall-clock time per PGN file
FILE_TIMEOUT_PER_MB = 30 # seconds: additional time per MB of file size
MAX_CONSECUTIVE_ERRORS = 10 # skip file after N consecutive parse failures
# Requests session defaults
USER_AGENT = (
"Mozilla/5.0 (compatible; DeepRedAI-ChessRetriever/1.0; "
"+https://github.com/DeepRedAI)"
)
REQUEST_TIMEOUT = 60
RETRY_DELAY = 2 # seconds between retries
MAX_RETRIES = 3
# Domains with expired/broken SSL certificates — bypass verification
SSL_BYPASS_DOMAINS = {"pgnmentor.com", "www.pgnmentor.com"}
# ---------------------------------------------------------------------------
# Internet Archive — public-domain chess books (pre-1929 US copyright)
# ---------------------------------------------------------------------------
# Curated list: (archive_org_identifier, title, author, year)
# Only pre-1929 works (safely US public domain)
ARCHIVE_CHESS_BOOKS = [
("my-system-2020",
"My System", "Aron Nimzowitsch", 1925),
("praxisofmysystem00nimz",
"The Praxis of My System", "Aron Nimzowitsch", 1929),
("gameofchess00sieg",
"The Game of Chess", "Siegbert Tarrasch", 1931), # NOTE: verify PD status
("chessplayerscom01staugoog",
"The Chess-Player's Companion", "Howard Staunton", 1849),
("chessplayershan00greegoog",
"The Chess-Player's Handbook", "Howard Staunton", 1847),
("mybestgamesofche0000alek",
"My Best Games of Chess 1908-1923", "Alexander Alekhine", 1924),
("mybestgamesofche00alek",
"My Best Games of Chess 1908-1937", "Alexander Alekhine", 1937),
("principleschess00masogoog",
"The Principles of Chess", "James Mason", 1894),
("artofchesscombin00euge",
"The Art of Chess Combination", "Eugène Znosko-Borovsky", 1936), # verify PD
("howtothinkaheadi0000iaho_p6v5",
"How to Think Ahead in Chess", "I.A. Horowitz", 1951), # verify PD
]
# ---------------------------------------------------------------------------
# Directory bootstrap (reused from retrieve_gutenberg.py pattern)
# ---------------------------------------------------------------------------
def _ensure_directory(path: str) -> None:
"""Create *path* (and parents) and verify the current user can write."""
uid = os.getuid()
user = getpass.getuser()
gid = os.getgid()
group = grp.getgrgid(gid).gr_name
if not os.path.isdir(path):
try:
os.makedirs(path, exist_ok=True)
except PermissionError:
print(f"\nError: cannot create {path} — permission denied.")
print(f"Run the following command first, then retry:\n")
print(f" sudo mkdir -p {path} && sudo chown -R {user}:{group} {path}\n")
sys.exit(1)
dir_stat = os.stat(path)
if dir_stat.st_uid != uid:
try:
subprocess.check_call(
['chown', '-R', f'{user}:{group}', path],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
print(f"Aligned ownership of {path} to {user}:{group}")
except (subprocess.CalledProcessError, PermissionError):
owner = pwd.getpwuid(dir_stat.st_uid).pw_name
print(f"\nError: {path} is owned by uid {dir_stat.st_uid} ({owner}), not {user}.")
print(f"Run the following command first, then retry:\n")
print(f" sudo chown -R {user}:{group} {path}\n")
sys.exit(1)
probe = os.path.join(path, '.write_test')
try:
with open(probe, 'w') as f:
f.write('ok')
os.unlink(probe)
except PermissionError:
print(f"\nError: {path} exists but is not writable by {user}.")
print(f"Run the following command first, then retry:\n")
print(f" sudo chown -R {user}:{group} {path} && sudo chmod -R u+rwX {path}\n")
sys.exit(1)
# ---------------------------------------------------------------------------
# HTTP helpers
# ---------------------------------------------------------------------------
def _get_session() -> requests.Session:
"""Return a requests session with standard headers."""
s = requests.Session()
s.headers.update({"User-Agent": USER_AGENT})
return s
def _needs_ssl_bypass(url: str) -> bool:
"""Return True if the URL's host is in the SSL-bypass list."""
host = urlparse(url).hostname or ""
return host in SSL_BYPASS_DOMAINS
def _download(session: requests.Session, url: str, dest: str,
label: str = "", verbose: bool = False) -> bool:
"""Download *url* to *dest* with retries. Returns True on success."""
if os.path.exists(dest):
if verbose:
print(f" [skip] {label or url} — already downloaded")
return True
verify = not _needs_ssl_bypass(url)
for attempt in range(1, MAX_RETRIES + 1):
try:
if verbose:
print(f" [{attempt}/{MAX_RETRIES}] {label or url}")
resp = session.get(url, timeout=REQUEST_TIMEOUT, stream=True,
verify=verify)
if resp.status_code == 200:
os.makedirs(os.path.dirname(dest), exist_ok=True)
tmp = dest + '.tmp'
with open(tmp, 'wb') as f:
for chunk in resp.iter_content(chunk_size=65536):
f.write(chunk)
os.replace(tmp, dest)
size_kb = os.path.getsize(dest) / 1024
if verbose:
print(f" ✓ {size_kb:,.0f} KB")
return True
elif resp.status_code == 404:
if verbose:
print(f" ✗ 404 Not Found")
return False
else:
if verbose:
print(f" ✗ HTTP {resp.status_code}")
# 503/429 = rate-limited; use longer back-off
if resp.status_code in (429, 503):
time.sleep(RETRY_DELAY * attempt * 3)
except requests.RequestException as exc:
if verbose:
print(f" ✗ {exc}")
if attempt < MAX_RETRIES:
time.sleep(RETRY_DELAY * attempt)
return False
# ===================================================================
# PHASE 1 — Download PGN databases
# ===================================================================
def phase1_download_pgn(chess_dir: str, verbose: bool = False) -> dict:
"""Download PGN game databases from free online sources.
Downloads are saved into $CHESS_DATA/pgn/ with subdirectories:
pgn/pgnmentor/players/ — individual player collections
pgn/pgnmentor/events/ — tournament/event collections
pgn/lumbras/ — Lumbras Gigabase OTB games
Returns a summary dict with counts.
"""
print(f"\n{'='*60}")
print("PHASE 1: Download PGN Databases")
print(f"{'='*60}\n")
pgn_dir = os.path.join(chess_dir, 'pgn')
session = _get_session()
stats = {"downloaded": 0, "skipped": 0, "failed": 0}
# --- 1a. PGN Mentor — Player collections ---
# Scrape files.html for all available player ZIP links, then download
# every player listed on the page. Temporal filtering of individual
# games happens later in Phase 2 using the PGN Date header.
print("── PGN Mentor: Player collections ──")
players_dir = os.path.join(pgn_dir, 'pgnmentor', 'players')
_ensure_directory(players_dir)
# Build player list from files.html — discover all available ZIPs
player_stems: list[tuple[str, str]] = [] # (stem, display_name)
files_html_text: str | None = None
try:
verify = not _needs_ssl_bypass("https://www.pgnmentor.com/files.html")
resp = session.get("https://www.pgnmentor.com/files.html",
timeout=REQUEST_TIMEOUT, verify=verify)
if resp.status_code == 200:
files_html_text = resp.text
# Parse all player ZIP links: href="players/Morphy.zip"
seen_stems: set[str] = set()
for m in re.finditer(
r'href=["\']?players/([A-Za-z][A-Za-z0-9_-]+)\.zip',
files_html_text,
):
stem = m.group(1)
if stem in seen_stems:
continue
seen_stems.add(stem)
# Try to grab display name from adjacent table cell
display = stem # fallback
player_stems.append((stem, display))
if verbose:
print(f" Scraped {len(player_stems)} player ZIPs from files.html")
else:
if verbose:
print(f" ✗ Could not fetch files.html (HTTP {resp.status_code})")
except requests.RequestException as exc:
if verbose:
print(f" ✗ Could not fetch files.html: {exc}")
if not player_stems:
print(" ✗ No player ZIPs discovered — cannot proceed with players")
print(" Check network connectivity to pgnmentor.com")
items = player_stems
if not verbose and tqdm:
items = tqdm(items, desc="Players", unit="file")
for stem, name in items:
# PGN Mentor distributes player files as ZIP archives
dest_pgn = os.path.join(players_dir, f"{stem}.pgn")
if os.path.exists(dest_pgn):
stats["skipped"] += 1
continue
dest_zip = os.path.join(players_dir, f"{stem}.zip")
url_zip = f"https://www.pgnmentor.com/players/{stem}.zip"
downloaded = False
if _download(session, url_zip, dest_zip, label=f"{name} (zip)",
verbose=verbose):
try:
with zipfile.ZipFile(dest_zip, 'r') as zf:
pgn_members = [m for m in zf.namelist()
if m.lower().endswith('.pgn')]
if pgn_members:
# Extract PGN file(s) into players_dir
zf.extractall(players_dir, members=pgn_members)
# Rename first PGN to canonical name if needed
extracted = os.path.join(players_dir, pgn_members[0])
if extracted != dest_pgn and os.path.exists(extracted):
os.replace(extracted, dest_pgn)
downloaded = True
if verbose:
print(f" Extracted {len(pgn_members)} PGN from ZIP")
else:
if verbose:
print(f" ✗ ZIP contains no PGN files")
except zipfile.BadZipFile:
if verbose:
print(f" ✗ ZIP is corrupt")
if os.path.exists(dest_zip):
os.remove(dest_zip)
if downloaded:
stats["downloaded"] += 1
else:
stats["failed"] += 1
if hasattr(items, 'close'):
items.close()
print(f" Players: {stats['downloaded']} downloaded, "
f"{stats['skipped']} skipped, {stats['failed']} failed")
# --- 1b. PGN Mentor — Event / tournament collections ---
# Scrape ALL event PGN links from files.html and apply temporal
# filter — every pre-1969 tournament is in scope.
print("\n── PGN Mentor: Event collections ──")
events_dir = os.path.join(pgn_dir, 'pgnmentor', 'events')
_ensure_directory(events_dir)
dl, sk, fl = 0, 0, 0
event_urls: list[tuple[str, str, str]] = [] # (url, dest, label)
# Reuse page text from player scrape if available, otherwise fetch
if files_html_text is None:
try:
verify = not _needs_ssl_bypass("https://www.pgnmentor.com/files.html")
resp = session.get("https://www.pgnmentor.com/files.html",
timeout=REQUEST_TIMEOUT, verify=verify)
if resp.status_code == 200:
files_html_text = resp.text
else:
if verbose:
print(f" ✗ Could not fetch files.html (HTTP {resp.status_code})")
except requests.RequestException as exc:
if verbose:
print(f" ✗ Could not fetch files.html: {exc}")
if files_html_text:
# Match every href="events/<Name><Year><suffix>.pgn" link
seen: set[str] = set()
for m in re.finditer(
r'href=["\']?(events/([A-Za-z][A-Za-z0-9_-]*?)(\d{4})\w*\.pgn)',
files_html_text,
):
rel_path = m.group(1) # e.g. events/MardelPlata1934.pgn
name_part = m.group(2) # e.g. MardelPlata
year_str = m.group(3) # e.g. 1934
if rel_path in seen:
continue
seen.add(rel_path)
try:
year = int(year_str)
except ValueError:
continue
# Apply temporal filter
if year > TEMPORAL_CUTOFF_YEAR:
continue
fname = os.path.basename(rel_path)
url = f"https://www.pgnmentor.com/{rel_path}"
dest = os.path.join(events_dir, fname)
# Readable label: insert space before year
label = f"{name_part} {year_str}"
event_urls.append((url, dest, label))
if verbose:
print(f" Scraped {len(event_urls)} pre-{TEMPORAL_CUTOFF_YEAR} "
f"event PGN URLs from files.html")
else:
if verbose:
print(" ✗ files.html unavailable — no events will be downloaded")
if not event_urls:
print(" ✗ No event PGN URLs discovered — cannot proceed with events")
print(" Check network connectivity to pgnmentor.com")
ev_items = event_urls
if not verbose and tqdm:
ev_items = tqdm(ev_items, desc="Events", unit="file")
for url, dest, label in ev_items:
if os.path.exists(dest):
sk += 1
elif _download(session, url, dest, label=label, verbose=verbose):
dl += 1
else:
fl += 1
if hasattr(ev_items, 'close'):
ev_items.close()
stats["downloaded"] += dl
stats["skipped"] += sk
stats["failed"] += fl
print(f" Events: {dl} downloaded, {sk} skipped, {fl} failed")
# --- 1c. Lumbras Gigabase (manual download from MEGA) ---
# The download page at lumbrasgigabase.com uses a WordPress download
# manager that redirects to MEGA. Automated download is not feasible,
# so we check for manually placed 7z archives and extract them.
print("\n── Lumbras Gigabase ──")
lg_dir = os.path.join(pgn_dir, 'lumbras')
_ensure_directory(lg_dir)
# Expected 7z archives (manually downloaded from MEGA links on the page)
LUMBRAS_ARCHIVES = [
("LumbrasGigaBase_OTB_0001-1899.7z", "OTB games from year 1 to 1899"),
("LumbrasGigaBase_OTB_1900-1949.7z", "OTB games from 1900 to 1949"),
("LumbrasGigaBase_OTB_1950-1969.7z", "OTB games from 1950 to 1969"),
]
lg_pgn_glob = os.path.join(lg_dir, '*.pgn')
if glob.glob(lg_pgn_glob):
print(" [skip] Lumbras PGN already extracted")
stats["skipped"] += 1
else:
any_found = False
any_missing = False
for arc_name, desc in LUMBRAS_ARCHIVES:
arc_path = os.path.join(lg_dir, arc_name)
if not os.path.exists(arc_path):
any_missing = True
continue
any_found = True
try:
result = subprocess.run(
['7z', 'x', '-y', f'-o{lg_dir}', arc_path],
capture_output=True, text=True, timeout=600,
)
# Count extracted PGN files
extracted = [
line.split('- ')[-1].strip()
for line in result.stdout.splitlines()
if line.strip().lower().endswith('.pgn')
]
pgn_count = len(glob.glob(os.path.join(lg_dir, '*.pgn')))
if result.returncode == 0:
print(f" Extracted PGN from {arc_name} "
f"({pgn_count} PGN file(s) in directory)")
stats["downloaded"] += 1
else:
print(f" ✗ 7z extraction failed for {arc_name}")
if result.stderr:
print(f" {result.stderr.strip()[:200]}")
stats["failed"] += 1
except FileNotFoundError:
print(" ✗ '7z' command not found — install p7zip-full:")
print(" sudo dnf install p7zip-plugins # Fedora")
stats["failed"] += 1
break
except subprocess.TimeoutExpired:
print(f" ✗ Extraction of {arc_name} timed out")
stats["failed"] += 1
if any_missing:
missing = [a for a, _ in LUMBRAS_ARCHIVES
if not os.path.exists(os.path.join(lg_dir, a))]
if not any_found:
print(" ✗ No Lumbras Gigabase archives found.")
else:
print(f" ✗ Missing {len(missing)} archive(s).")
print("")
print(" Manual download required (files are hosted on MEGA):")
print(" 1. Visit: https://lumbrasgigabase.com/en/"
"download-in-pgn-format-en/")
print(" 2. Under the 'Downloads OTB' tab, download these files:")
for a in missing:
print(f" • {a}")
print(f" 3. Place the .7z file(s) in: {lg_dir}/")
print(" 4. Re-run this script (Phase 1) to extract them.")
print("")
stats["failed"] += len(missing)
print(f"\nPhase 1 complete: {stats['downloaded']} downloaded, "
f"{stats['skipped']} skipped, {stats['failed']} failed")
return stats
# ===================================================================
# PHASE 2 — Convert PGN to natural-language narrative
# ===================================================================
def _parse_pgn_date(date_str: str) -> int | None:
"""Extract year from a PGN Date header. Returns None if unparseable."""
if not date_str or date_str == '????.??.??' or date_str == '?':
return None
m = re.match(r'(\d{4})', date_str)
return int(m.group(1)) if m else None
def _format_result(result: str) -> str:
"""Human-readable game result."""
mapping = {
"1-0": "White wins",
"0-1": "Black wins",
"1/2-1/2": "Draw",
}
return mapping.get(result, result)
def _classify_opening(eco: str, opening: str) -> str:
"""Return a short description of the opening from ECO + name."""
if opening:
return opening
if not eco:
return ""
# Broad ECO ranges
if eco.startswith('A'):
return "Flank opening"
if eco.startswith('B'):
return "Semi-open game"
if eco.startswith('C'):
return "Open game"
if eco.startswith('D'):
return "Closed game"
if eco.startswith('E'):
return "Indian defense"
return ""
def _game_to_summary(game) -> str | None:
"""Convert a python-chess game to an Approach-A structured summary.
Returns None if the game lacks sufficient metadata.
"""
h = game.headers
white = h.get("White", "Unknown")
black = h.get("Black", "Unknown")
event = h.get("Event", "?")
date = h.get("Date", "?")
result = h.get("Result", "*")
eco = h.get("ECO", "")
opening = h.get("Opening", "")
# Skip games with no player names
if white in ("?", "Unknown", "") and black in ("?", "Unknown", ""):
return None
lines = []
lines.append(f"Game: {white} vs. {black}")
if event and event != '?':
date_display = date.replace('.??', '').replace('??', '').rstrip('.')
lines.append(f"Event: {event}, {date_display}")
elif date and date != '????.??.??':
lines.append(f"Date: {date}")
opening_desc = _classify_opening(eco, opening)
if opening_desc:
eco_tag = f" ({eco})" if eco else ""
lines.append(f"Opening: {opening_desc}{eco_tag}")
lines.append(f"Result: {_format_result(result)}")
lines.append("")
# Collect moves
board = game.board()
move_strs = []
move_num = 1
for node in game.mainline():
move = node.move
san = board.san(move)
if board.turn == chess.WHITE:
move_strs.append(f"{move_num}.{san}")
else:
move_strs.append(san)
move_num += 1
board.push(move)
if not move_strs:
return None
# Format moves in lines of ~80 chars
move_text = ""
line = ""
for ms in move_strs:
if len(line) + len(ms) + 1 > 78:
move_text += line.rstrip() + "\n"
line = ""
line += ms + " "
if line.strip():
move_text += line.rstrip()
lines.append(move_text)
total_moves = (len(list(game.mainline())) + 1) // 2
lines.append("")
lines.append(f"The game lasted {total_moves} moves and ended in "
f"{_format_result(result).lower()}.")
return "\n".join(lines)
def _game_to_annotated(game) -> str | None:
"""Convert a python-chess game to an Approach-C annotated narrative.
Provides richer description for famous or well-annotated games.
Returns None if game is unsuitable.
"""
h = game.headers
white = h.get("White", "Unknown")
black = h.get("Black", "Unknown")
event = h.get("Event", "?")
date = h.get("Date", "?")
result = h.get("Result", "*")
eco = h.get("ECO", "")
opening = h.get("Opening", "")
if white in ("?", "Unknown", "") and black in ("?", "Unknown", ""):
return None
lines = []
date_display = date.replace('.??', '').replace('??', '').rstrip('.')
event_str = f" at {event}" if event and event != '?' else ""
lines.append(f"{white} vs. {black}{event_str} ({date_display})")
lines.append("")
opening_desc = _classify_opening(eco, opening)
if opening_desc:
eco_tag = f" ({eco})" if eco else ""
lines.append(f"Opening: {opening_desc}{eco_tag}")
lines.append("")
# Walk the game with commentary at key moments
board = game.board()
move_num = 1
move_buffer = []
commentary_lines = []
material_changes = 0
for node in game.mainline():
move = node.move
san = board.san(move)
is_capture = board.is_capture(move)
gives_check = board.gives_check(move)
is_castling = board.is_castling(move)
if board.turn == chess.WHITE:
move_str = f"{move_num}.{san}"
else:
move_str = san
move_num += 1
move_buffer.append(move_str)
# Add inline commentary for significant moves
if is_capture:
material_changes += 1
if gives_check:
move_buffer[-1] += " — check!"
if is_castling:
side = "kingside" if board.is_kingside_castling(move) else "queenside"
move_buffer[-1] += f" — {side} castling"
board.push(move)
# Flush move buffer every 6-8 full moves
if move_num % 7 == 0 and board.turn == chess.WHITE and move_buffer:
commentary_lines.append(" ".join(move_buffer))
move_buffer = []
# Flush remaining moves
if move_buffer:
commentary_lines.append(" ".join(move_buffer))
lines.append("\n".join(commentary_lines))
lines.append("")
total_moves = (len(list(game.mainline())) + 1) // 2
result_desc = _format_result(result).lower()
lines.append(f"After {total_moves} moves the game ended in {result_desc}.")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Phase 2 — parsing helpers (timeout, stuck detection, skip-ahead)
# ---------------------------------------------------------------------------
class _GameParseTimeout(Exception):
"""Raised when a single chess.pgn.read_game() exceeds the time limit."""
pass
def _alarm_handler(signum, frame):
raise _GameParseTimeout()
def _skip_to_next_game(pgn_f) -> bool:
"""Advance *pgn_f* past a malformed game to the next ``[Event`` header.
Returns True if a new game header was found, False on EOF.
"""
while True:
pos = pgn_f.tell()
line = pgn_f.readline()
if not line:
return False
if line.startswith('[Event '):
pgn_f.seek(pos) # back up so read_game sees the header
return True
def _compute_file_timeout(pgn_path: str) -> int:
"""Return a dynamic file-parse timeout (seconds) scaled by file size.
Small files get the base FILE_PARSE_TIMEOUT. Larger files receive
an additional FILE_TIMEOUT_PER_MB seconds per megabyte so that
multi-hundred-MB PGN archives are not prematurely abandoned.
"""
try:
size_mb = os.path.getsize(pgn_path) / (1024 * 1024)
except OSError:
size_mb = 0
return max(FILE_PARSE_TIMEOUT,
int(FILE_PARSE_TIMEOUT + size_mb * FILE_TIMEOUT_PER_MB))
def _process_pgn_file(
pgn_path: str,
pgn_dir: str,
cutoff_year: int,
known_keys: set | frozenset,
annotated_budget: int = 0,
game_timeout: int = GAME_PARSE_TIMEOUT,
file_timeout: int | None = None,
) -> tuple[list[dict], dict]:
"""Process one PGN file with safety timeouts and stuck detection.
Parameters
----------
pgn_path : path to the PGN file
pgn_dir : base PGN directory (for relative-path calculation)
cutoff_year : skip games with a Date header after this year
known_keys : keys already in the corpus (for dedup)
annotated_budget : how many games to convert in annotated mode
game_timeout : max seconds per ``read_game()`` call
file_timeout : max wall-clock seconds for the entire file
Returns
-------
(records, stats) — *records* is a list of dicts ready for JSONL output,
*stats* is a dict of per-file counters.
"""
if file_timeout is None:
file_timeout = _compute_file_timeout(pgn_path)
rel_path = os.path.relpath(pgn_path, pgn_dir)
records: list[dict] = []
stats = {
"games_total": 0,
"games_pre_cutoff": 0,
"games_post_cutoff": 0,
"games_skipped_dup": 0,
"games_skipped_nodata": 0,
"games_timed_out": 0,
"games_parse_error": 0,
"annotated_count": 0,
"file_timed_out": False,
"file_timeout_used": file_timeout,
"consec_error_skip": False,
"error": None,
}
prev_handler = signal.getsignal(signal.SIGALRM)
signal.signal(signal.SIGALRM, _alarm_handler)
file_start = time.monotonic()
consecutive_errors = 0
annotated_left = annotated_budget
local_keys: set[str] = set() # intra-file dedup
try:
with open(pgn_path, 'r', encoding='utf-8', errors='replace') as pgn_f:
while True:
# Per-file wall-clock check
if time.monotonic() - file_start > file_timeout:
stats["file_timed_out"] = True
break
# Read one game with alarm-based timeout
game = None
file_pos = pgn_f.tell()
signal.alarm(game_timeout)
try:
game = chess.pgn.read_game(pgn_f)
except _GameParseTimeout:
stats["games_timed_out"] += 1
consecutive_errors += 1
if consecutive_errors >= MAX_CONSECUTIVE_ERRORS:
stats["consec_error_skip"] = True
break
_skip_to_next_game(pgn_f)
continue
except Exception:
stats["games_parse_error"] += 1
consecutive_errors += 1
if consecutive_errors >= MAX_CONSECUTIVE_ERRORS:
stats["consec_error_skip"] = True
break
# Ensure file pointer advanced; if stuck, skip ahead
if pgn_f.tell() == file_pos:
if not _skip_to_next_game(pgn_f):
break
continue
finally:
signal.alarm(0)
if game is None:
break
consecutive_errors = 0
stats["games_total"] += 1
h = game.headers
# --- Temporal filter ---
year = _parse_pgn_date(h.get("Date", ""))
if year is not None and year > cutoff_year:
stats["games_post_cutoff"] += 1
continue
# Games with no date: include (many historical games lack dates)
stats["games_pre_cutoff"] += 1
# --- Dedup key ---
key = (f"{h.get('White','')}-{h.get('Black','')}-"
f"{h.get('Date','')}-{h.get('Event','')}-"
f"{h.get('Round','')}")
if key in known_keys or key in local_keys:
stats["games_skipped_dup"] += 1
continue
# --- Convert ---
if annotated_left > 0:
text = _game_to_annotated(game)
mode = "annotated"
else:
text = _game_to_summary(game)
mode = "summary"
if text is None:
stats["games_skipped_nodata"] += 1
continue
record = {
"key": key,
"white": h.get("White", ""),
"black": h.get("Black", ""),
"date": h.get("Date", ""),
"event": h.get("Event", ""),
"eco": h.get("ECO", ""),
"opening": h.get("Opening", ""),
"result": h.get("Result", ""),
"source_file": rel_path,
"mode": mode,
"text": text,
"length": len(text),
}
records.append(record)
local_keys.add(key)
if mode == "annotated":
stats["annotated_count"] += 1
annotated_left -= 1
except Exception as exc:
stats["error"] = str(exc)
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, prev_handler)
return records, stats
def phase2_convert_pgn(chess_dir: str, verbose: bool = False,
annotated_limit: int = 1000,
workers: int = 1) -> dict:
"""Parse all downloaded PGN files, filter to pre-1969, convert to text.
Writes JSONL output to $CHESS_DATA/corpus/chess_games.jsonl.
Uses Approach C (annotated) for the first *annotated_limit* games
and Approach A (summary) for the rest.
When *workers* > 1, files are processed in parallel using a process
pool. Annotated mode is disabled in parallel (all summary).
Requires the ``python-chess`` library.
Returns a summary dict.
"""
print(f"\n{'='*60}")
print("PHASE 2: Convert PGN to Narrative Text")
print(f"{'='*60}\n")
if not HAS_PYTHON_CHESS:
print("ERROR: python-chess is required for Phase 2.")
print("Install it with: pip install python-chess")
return {"error": "python-chess not installed"}
pgn_dir = os.path.join(chess_dir, 'pgn')
corpus_dir = os.path.join(chess_dir, 'corpus')
_ensure_directory(corpus_dir)
output_file = os.path.join(corpus_dir, 'chess_games.jsonl')
manifest_file = os.path.join(corpus_dir, 'chess_games.manifest.json')
# Collect all PGN files, sorted largest-first for better parallel
# scheduling and early detection of problematic files.
pgn_files_raw = glob.glob(os.path.join(pgn_dir, '**', '*.pgn'),
recursive=True)
if not pgn_files_raw:
print("No PGN files found. Run Phase 1 first.")
return {"error": "no PGN files", "games": 0}
pgn_files_all = sorted(pgn_files_raw,
key=lambda p: os.path.getsize(p), reverse=True)
total_size = sum(os.path.getsize(f) for f in pgn_files_all)
print(f"Found {len(pgn_files_all)} PGN file(s), "
f"{total_size / (1024*1024):.1f} MB total")
for f in pgn_files_all[:5]:
sz = os.path.getsize(f)
print(f" {os.path.relpath(f, pgn_dir):40s} {sz / (1024*1024):6.1f} MB")
if len(pgn_files_all) > 5:
print(f" ... and {len(pgn_files_all) - 5} more files")
# Load existing game keys to support idempotent re-runs
existing_keys: set[str] = set()
if os.path.exists(output_file):
with open(output_file, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
try:
rec = json.loads(line)
existing_keys.add(rec.get('key', ''))
except json.JSONDecodeError:
pass
print(f"Existing corpus has {len(existing_keys)} games "
f"— will skip duplicates")
# Load manifest of previously-processed PGN files. A file is
# considered "done" if it was fully processed (no timeout / error)
# and its size + mtime haven't changed on disk.
manifest: dict[str, dict] = {}
if os.path.exists(manifest_file):
try:
with open(manifest_file, 'r', encoding='utf-8') as f:
manifest = json.load(f)
except (json.JSONDecodeError, OSError):
manifest = {}
def _is_already_processed(pgn_path: str) -> bool:
"""Return True if *pgn_path* is in the manifest and unchanged."""
rel = os.path.relpath(pgn_path, pgn_dir)
entry = manifest.get(rel)
if entry is None or not entry.get("completed"):
return False
try:
st = os.stat(pgn_path)
return (st.st_size == entry.get("size")
and st.st_mtime == entry.get("mtime"))
except OSError:
return False