-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
348 lines (309 loc) · 11.9 KB
/
Copy pathmain.py
File metadata and controls
348 lines (309 loc) · 11.9 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
"""
Greco — chess analysis with engine evaluation and AI narration.
Pipeline:
PGN source (file / URL / inline) → importers.py
→ analyzer.py (Stockfish per-position evaluation)
→ triage.py (commentary tier assignment)
→ narrator.py (Claude narrative + psychology)
→ outputs.py (assemble Markdown with move list + boards + eval graph)
→ optional HTML via outputs.markdown_to_html
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
from analyzer import analyze_pgn
from importers import load_pgn
from narrator import generate_narrative
from outputs import archive_reported_pgn, assemble_report, markdown_to_html
from triage import annotate_with_tiers, tier_distribution
BANNER = r"""
_____
/ ____|
| | __ _ __ ___ ___ ___
| | |_ || '__|/ _ \/ __|/ _ \
| |__| || | | __/ (__| (_) |
\_____||_| \___|\___|\___/
chess engine + AI narrator
"""
USE_CASE_DESCRIPTIONS = {
"companion": "warm friend sharing the game with you",
"coaching": "diagnostic focus on your decision-making; ends with 'patterns to work on'",
"commentary": "YouTube-style video script with [SCENE BREAK] markers",
}
def _progress_printer(done: int, total: int) -> None:
bar_width = 30
filled = int(bar_width * done / total)
bar = "#" * filled + "-" * (bar_width - filled)
sys.stderr.write(f"\r engine [{bar}] {done}/{total}")
sys.stderr.flush()
if done == total:
sys.stderr.write("\n")
def _prompt_use_case() -> str:
sys.stderr.write("\nWhat is this analysis for?\n")
options = list(USE_CASE_DESCRIPTIONS.items())
for i, (key, desc) in enumerate(options, start=1):
sys.stderr.write(f" {i}. {key} — {desc}\n")
sys.stderr.write("Pick 1, 2, or 3 [default 1]: ")
sys.stderr.flush()
try:
choice = input().strip()
except EOFError:
return "companion"
if not choice:
return "companion"
if choice in ("1", "2", "3"):
return options[int(choice) - 1][0]
if choice in USE_CASE_DESCRIPTIONS:
return choice
sys.stderr.write(f"Didn't understand '{choice}', defaulting to companion.\n")
return "companion"
def main() -> int:
parser = argparse.ArgumentParser(
prog="greco",
description=(
"Greco — analyze a chess game by combining Stockfish engine evaluation "
"with Claude's narrative writing and psychological commentary."
),
)
src = parser.add_mutually_exclusive_group()
src.add_argument("--pgn-file", type=str, help="Path to a PGN file")
src.add_argument("--pgn", type=str, help="PGN text passed directly")
src.add_argument("--pgn-url", type=str, help="Lichess URL/game ID, or a chess.com game URL (chess.com also needs --chesscom-user)")
src.add_argument("--source", type=str, help="Auto-detected source: file path, Lichess or chess.com URL, or raw PGN text")
parser.add_argument(
"--chesscom-user", type=str, default=None,
help="Your Chess.com username — required when the source is a chess.com URL "
"(the public API is per-player, so Greco looks the game up in this "
"player's recent archives)",
)
parser.add_argument(
"--white-context",
type=str,
default=None,
help="Free-form context about the White player (e.g. 'world #1 known for endgame technique')",
)
parser.add_argument(
"--black-context",
type=str,
default=None,
help="Free-form context about the Black player",
)
parser.add_argument(
"--user-is",
choices=["white", "black", "neither"],
default="neither",
help="If the user themselves played as one side, name it for first-person commentary",
)
parser.add_argument(
"--use-case",
choices=["companion", "coaching", "commentary"],
default=None,
help=(
"Voice of the report. If not given, Greco will ask interactively. "
"companion = friend sharing the game; coaching = diagnostic; commentary = video script."
),
)
parser.add_argument(
"--user-note",
type=str,
default=None,
help="A personal note about the game (e.g. 'I'm proud of the queen sacrifice'). Greco will respond to it directly.",
)
# Engine settings.
parser.add_argument(
"--engine",
type=str,
default=os.environ.get("STOCKFISH_PATH"),
help="Path to the Stockfish binary (or set STOCKFISH_PATH)",
)
parser.add_argument("--depth", type=int, default=18, help="Engine search depth (default 18)")
parser.add_argument(
"--time-per-move",
type=float,
default=None,
help="Seconds of engine time per position (overrides --depth)",
)
parser.add_argument("--multipv", type=int, default=3, help="Top N moves to consider (default 3)")
# Claude settings.
parser.add_argument(
"--model",
type=str,
default="claude-sonnet-4-6",
help="Claude model to use (default claude-sonnet-4-6; try claude-opus-4-7 for richer prose)",
)
parser.add_argument(
"--max-tokens",
type=int,
default=16000,
help="Max output tokens for the narrative (default 16000 — long games with many notable moves need the headroom)",
)
# Output settings.
parser.add_argument("--output", type=Path, default=None, help="Write Markdown to this file (also creates a sibling _assets/ folder)")
parser.add_argument(
"--format",
choices=["md", "html", "both"],
default="both",
help=(
"Output format (default both). 'html' is self-contained: every board "
"and the eval graph is embedded directly in the file — no links to "
"open, and you can print it to PDF from your browser (Ctrl+P)."
),
)
parser.add_argument(
"--boards-at",
choices=["off", "tier3", "tier2", "all"],
default="tier3",
help="Insert board diagrams for moves at the chosen tier and above (default tier3)",
)
parser.add_argument(
"--no-eval-graph",
action="store_true",
help="Skip the eval-graph PNG",
)
parser.add_argument(
"--save-analysis",
type=Path,
default=None,
help="Optional path to dump the raw engine analysis as JSON (useful for debugging)",
)
# Text-to-speech (Windows built-in voice; no extra install).
parser.add_argument(
"--speak",
action="store_true",
help="Read the narrative aloud when finished (Windows voice).",
)
parser.add_argument(
"--audio",
type=Path,
default=None,
help="Save the spoken narrative to a .wav file at this path.",
)
parser.add_argument(
"--voice-rate",
type=int,
default=0,
help="Speech rate from -10 (slow) to 10 (fast). Default 0.",
)
args = parser.parse_args()
# Choose a source.
source_string = args.source or args.pgn_file or args.pgn_url or args.pgn
if not source_string:
parser.error("Provide --pgn-file, --pgn-url, --pgn, or --source")
if not args.engine:
parser.error("Stockfish path required: pass --engine or set STOCKFISH_PATH")
if not os.environ.get("ANTHROPIC_API_KEY"):
parser.error("ANTHROPIC_API_KEY environment variable is not set")
print(BANNER, file=sys.stderr)
pgn_text, source_desc = load_pgn(source_string, chesscom_username=args.chesscom_user)
print(f"Loaded PGN from {source_desc}", file=sys.stderr)
# Resolve use_case (interactive prompt if not given).
use_case = args.use_case
if use_case is None:
if sys.stdin.isatty():
use_case = _prompt_use_case()
else:
use_case = "companion"
flipped_for_black = args.user_is == "black"
user_context = {
"white_player": args.white_context,
"black_player": args.black_context,
"user_is": args.user_is,
"player_named": bool(args.white_context or args.black_context),
}
print("Analyzing positions with Stockfish...", file=sys.stderr)
game = analyze_pgn(
pgn_text,
engine_path=args.engine,
depth=args.depth,
multipv=args.multipv,
time_limit=args.time_per_move,
progress_cb=_progress_printer,
)
print(f"Analyzed {len(game.moves)} moves.", file=sys.stderr)
print("Assigning commentary tiers...", file=sys.stderr)
tiers = annotate_with_tiers(game, user_context)
dist = tier_distribution(tiers)
print(
f" tier distribution: 0={dist[0]} 1={dist[1]} 2={dist[2]} 3={dist[3]}",
file=sys.stderr,
)
if args.save_analysis:
import dataclasses
import json
payload = {
"schema": 1, # consumed by tools/verify_report.py; bump if MoveAnalysis changes shape
"headers": game.headers,
"result": game.result,
"final_eval_cp": game.final_eval_cp,
"final_mate": game.final_mate,
"moves": [dataclasses.asdict(m) for m in game.moves],
"tiers": tiers,
}
args.save_analysis.write_text(json.dumps(payload, indent=2), encoding="utf-8")
print(f" wrote raw analysis to {args.save_analysis}", file=sys.stderr)
print(
f"Generating narrative with {args.model} in '{use_case}' voice... (streaming live)\n",
file=sys.stderr,
)
# If the source was a local file, pass its path so the narrator can recover
# player names from the filename when the PGN headers lack them (feature 5).
from pathlib import Path as _Path
try:
source_path = source_string if _Path(source_string).is_file() else None
except OSError:
source_path = None
narrative = generate_narrative(
game,
tiers,
user_context,
model=args.model,
max_tokens=args.max_tokens,
live_stream_to=sys.stderr,
use_case=use_case,
user_note=args.user_note,
source_path=source_path,
boards_at=args.boards_at,
)
# Text-to-speech (works whether or not a report file is written).
if args.speak or args.audio:
try:
from tts import save_audio, speak_text, to_speakable_text
spoken = to_speakable_text(narrative)
if args.audio:
wav = save_audio(spoken, args.audio, rate=args.voice_rate)
size_mb = wav.stat().st_size / (1024 * 1024)
print(f"Wrote audio narration to {wav} ({size_mb:.1f} MB)", file=sys.stderr)
if args.speak:
print("Reading the narrative aloud...", file=sys.stderr)
speak_text(spoken, rate=args.voice_rate)
except Exception as exc: # never let TTS failure sink the whole run
print(f"(Text-to-speech failed: {exc})", file=sys.stderr)
if not args.output:
# No output path: just print the narrative to stdout.
print(narrative)
return 0
md_path = assemble_report(
game,
tiers,
narrative,
output_md=args.output,
boards_at=args.boards_at,
render_eval_graph=not args.no_eval_graph,
flipped_for_black=flipped_for_black,
)
print(f"Wrote Markdown report to {md_path}", file=sys.stderr)
if args.format in ("html", "both"):
html_path = markdown_to_html(md_path, game=game, flipped=flipped_for_black)
print(f"Wrote HTML report to {html_path}", file=sys.stderr)
# The game now has a report: file the source PGN from the Chess Game Files
# library root into 'Games with Reports' (no-op for URL/text sources and
# for files that live anywhere else).
if source_path:
filed = archive_reported_pgn(source_path)
if filed:
print(f"Filed the PGN into '{filed.parent.name}'", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())