#!/usr/bin/env python3 """Translates the German comments of the Reti game (shots/classic-games.pgn, ours) into English once, with the owner's ChatGPT sign-in from ChessPenguin, and puts them into the screenshot cache (target/site-shots/cache) the way the app caches translations — so the "translation" shot shows a real machine translation and never sends anything itself. TRANSLATE_LANG=en cargo test -q -p chesspenguin -- --ignored print_instructions \\ --nocapture | sed -n '/You translate/,/exactly once./p' > /tmp/instructions.txt python3 -I website/shots/translate-for-shots.py /tmp/instructions.txt """ import hashlib, json, os, re, sys, urllib.request ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PGN = os.path.join(ROOT, "website", "shots", "classic-games.pgn") CACHE = os.path.join(ROOT, "target", "site-shots", "cache", "chesspenguin", "translations", "en.jsonl") game = open(PGN, encoding="utf-8").read().split('[Event "Vienna"]')[1] # The text the notation shows: commands cut, words joined by single spaces. texts = [" ".join(re.sub(r"\[%[^\]]*\]", "", c).split()) for c in re.findall(r"\{([^}]*)\}", game)] texts = [t for t in texts if t] instructions = open(sys.argv[1], encoding="utf-8").read() user = json.dumps({"game": {"white": "Reti, Richard", "black": "Tartakower, Savielly", "event": "Vienna", "opening": "B15"}, "comments": [{"id": i, "text": t} for i, t in enumerate(texts)]}, ensure_ascii=False) tokens = json.load(open(os.path.expanduser("~/.config/chesspenguin/credentials.json")))["chatgpt"] body = {"model": "gpt-6.1-sol", "instructions": instructions, "store": False, "stream": True, "input": [{"role": "user", "content": [{"type": "input_text", "text": user}]}]} req = urllib.request.Request("https://api.openai.com/v1/responses", data=json.dumps(body).encode(), method="POST", headers={"Authorization": "Bearer " + tokens["access"], "Content-Type": "application/json", "Accept": "text/event-stream", "User-Agent": "ChessPenguin (website screenshots)"}) out = "" with urllib.request.urlopen(req, timeout=180) as r: for line in r: line = line.decode("utf-8", "replace").strip() if line.startswith("data:"): try: v = json.loads(line[5:]) except ValueError: continue if v.get("type") == "response.output_text.delta": out += v.get("delta", "") got = {t["id"]: t["text"] for t in json.loads(out[out.index("{"):out.rindex("}") + 1])["translations"]} os.makedirs(os.path.dirname(CACHE), exist_ok=True) with open(CACHE, "a", encoding="utf-8") as f: for i, t in enumerate(texts): if i in got: key = hashlib.sha256(b"v2\0" + t.encode()).hexdigest() f.write(json.dumps({"k": key, "t": got[i], "via": "chatgpt gpt-6.1-sol"}, ensure_ascii=False) + "\n") print(f"{t}\n → {got[i]}")