-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpuzzle.py
More file actions
1395 lines (1205 loc) · 54 KB
/
Copy pathpuzzle.py
File metadata and controls
1395 lines (1205 loc) · 54 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
"""
Chroniclues — Wikipedia-Grounded Parswords History Escape Room
---------------------------------------------------------------
Pipeline:
1. User submits topic + year.
2. Wikipedia article is fetched and summarised into 5-6 sentences by Gemini.
3. Gemini identifies exactly 3 key historical terms from that summary.
4. Each term becomes a fill-in-the-blank answer.
5. Gemini generates all three Parseword clues in one batch request, guided by
few-shot examples drawn from clue_trainer / the combined CSV dataset.
6. Each clue is validated mechanically; invalid ones are replaced by a
deterministic Python fallback.
7. The three answers fill blanks in the final story paragraph.
Active endpoints:
GET / -> serve the UI
GET /api/health -> service status
GET /api/clue-style -> debug: dataset examples & validation summary
POST /api/escape-room -> generate a story-driven history escape room
"""
from __future__ import annotations
import json
import importlib
import logging
import os
import re
import secrets
from collections import Counter
from pathlib import Path
from time import monotonic, perf_counter
from typing import Any
from threading import Event, Lock
from urllib.parse import quote
import requests
from flask import Flask, jsonify, render_template, request
# ---------------------------------------------------------------------------
# Optional local environment loading
# ---------------------------------------------------------------------------
try:
from dotenv import load_dotenv
load_dotenv("arya_api.env")
except ImportError:
pass
# ---------------------------------------------------------------------------
# Dataset/trainer import. clue_trainer is the single source of truth.
# ---------------------------------------------------------------------------
TRAINER_LOAD_ERROR = ""
try:
from clue_trainer import ( # type: ignore
CLUE_EXAMPLES,
CLUE_FORMULA,
DATASET_PATH,
DATASET_SUMMARY,
FEWSHOT_BLOCK,
ROWS as DATASET_ROWS,
SCHEMA_CLUE_EXAMPLES,
VALIDATION_REPORT,
)
_TRAINER_LOADED = bool(DATASET_ROWS)
except Exception as _exc:
CLUE_EXAMPLES: dict = {}
CLUE_FORMULA: str = ""
FEWSHOT_BLOCK: str = ""
DATASET_ROWS: list = []
SCHEMA_CLUE_EXAMPLES: dict = {}
VALIDATION_REPORT: dict = {"passed": 0, "total": 0, "failed": []}
DATASET_SUMMARY: dict = {}
DATASET_PATH = Path(os.getenv("CLUE_DATASET", "cryptic_parseword_combined.csv")).expanduser().resolve()
TRAINER_LOAD_ERROR = f"{type(_exc).__name__}: {_exc}"
_TRAINER_LOADED = False
logging.exception("clue_trainer could not be loaded")
# ---------------------------------------------------------------------------
# App + config
# ---------------------------------------------------------------------------
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
app = Flask(__name__)
# Prevent accidental duplicate browser submissions from triggering duplicate
# Gemini work. Requests for the same topic/year share one in-flight generation,
# and a just-completed result is reused briefly.
_GENERATION_STATE_LOCK = Lock()
_GENERATION_IN_FLIGHT: dict[tuple[str, str], Event] = {}
_GENERATION_CACHE: dict[tuple[str, str], tuple[float, dict[str, Any]]] = {}
GENERATION_CACHE_TTL_SECONDS = float(os.getenv("GENERATION_CACHE_TTL_SECONDS", "15"))
GENERATION_WAIT_TIMEOUT_SECONDS = float(os.getenv("GENERATION_WAIT_TIMEOUT_SECONDS", "300"))
# Gemini 2.0 Flash is the stable GA model; override via env var if needed.
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "") or os.getenv("GOOGLE_API_KEY", "")
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-2.0-flash")
# Number of trainer examples placed in each Gemini clue prompt.
MAX_DATASET_EXAMPLES_PER_OP = int(os.getenv("MAX_DATASET_EXAMPLES_PER_OP", "5"))
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
STOP_WORDS = {
"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "of", "for",
"with", "by", "from", "as", "is", "was", "were", "are", "be", "been", "being",
"it", "its", "this", "that", "these", "those", "their", "they", "he", "she",
"his", "her", "who", "which", "when", "where", "what", "how", "also", "after",
"before", "during", "over", "into", "through", "had", "has", "have", "would",
"could", "should", "did", "does", "do", "not", "no", "more", "most", "many",
"some", "such", "other", "new", "first", "second", "third", "later", "early",
"late", "century", "period", "history", "world", "area", "number", "time",
"years", "year", "became", "made", "called", "known", "used", "including",
}
# Generate three rooms. Each request randomly selects three different
# operations that are present in the dataset and mechanically validated here.
CLUE_COUNT = 3
RANDOM_OPERATION_POOL = [
"hidden_word",
"deletion",
"reverse",
"anagram",
"container",
"selection",
]
ALLOWED_OPS = set(RANDOM_OPERATION_POOL)
NARRATIVE_STYLES = [
"a chronological account that moves from background to turning point to consequence",
"a cause-and-effect narrative focused on why events unfolded",
"a turning-point narrative centered on one decisive historical change",
"a people-and-institutions narrative showing how actors shaped events",
"a before-during-after narrative that emphasizes historical transformation",
"a concise documentary-style narrative with varied sentence openings",
]
CLUE_STYLE_DIRECTIONS = [
"definition first, then compact wordplay",
"wordplay first, with the definition naturally integrated",
"a smooth sentence-like surface",
"a terse newspaper-headline surface",
"a slightly narrative surface without becoming a history question",
"a concise dataset-like surface using different wording from the examples",
]
OPERATION_INDICATORS = {
"deletion": ["losing its head", "beheaded", "curtailed"],
"reverse": ["going back", "reversed", "turned"],
"hidden_word": ["found in", "concealed in", "within"],
"anagram": ["confused:", "scrambled:", "mixed:"],
"selection": ["initially", "first letters of"],
"container": ["inside", "holding", "around", "embracing"],
}
QUIZ_PATTERNS = re.compile(
r"^\s*(what|what's|who|when|where|which|why|how)\b"
r"|\bwhat\s+(is|are|was|were|did|does|do)\b"
r"|\bname\s+the\b|\btell\s+me\b|\bdescribe\b|\?",
re.IGNORECASE,
)
# ---------------------------------------------------------------------------
# Gemini / LangChain helpers
# ---------------------------------------------------------------------------
def gemini_configured() -> bool:
return bool(GEMINI_API_KEY and "YOUR_" not in GEMINI_API_KEY)
def invoke_gemini(prompt: str, temperature: float = 0.25) -> str:
"""Call Gemini through LangChain and return the text response."""
if not gemini_configured():
raise RuntimeError("Set GEMINI_API_KEY or GOOGLE_API_KEY.")
os.environ.setdefault("GOOGLE_API_KEY", GEMINI_API_KEY)
try:
output_parsers = importlib.import_module("langchain_core.output_parsers")
prompts = importlib.import_module("langchain_core.prompts")
google_genai = importlib.import_module("langchain_google_genai")
except ImportError as exc:
raise RuntimeError(
"LangChain Gemini packages missing. Run: "
"pip install langchain langchain-core langchain-google-genai google-generativeai"
) from exc
model = getattr(google_genai, "ChatGoogleGenerativeAI")(
model=GEMINI_MODEL, temperature=temperature, max_retries=2,
)
chain = (
getattr(prompts, "ChatPromptTemplate").from_messages([
("system", "Return only the requested JSON or text. Do not wrap output in markdown fences."),
("human", "{prompt}"),
])
| model
| getattr(output_parsers, "StrOutputParser")()
)
return str(chain.invoke({"prompt": prompt}))
# ---------------------------------------------------------------------------
# Dataset helpers — rows are already normalized by clue_trainer
# ---------------------------------------------------------------------------
def _normalize_op(operation: str) -> str:
key = str(operation or "").strip().lower().replace("-", "_").replace(" ", "_")
return {
"reversal": "reverse", "reverse": "reverse",
"hidden": "hidden_word", "hiddenword": "hidden_word", "hidden_word": "hidden_word",
"container_insertion": "container", "insertion": "container", "container": "container",
"deletion": "deletion", "anagram": "anagram",
"homophone": "homophone", "selection": "selection",
}.get(key, key)
def _dataset_examples_for_op(operation: str, limit: int = MAX_DATASET_EXAMPLES_PER_OP) -> list[dict]:
"""Return a fresh random sample of examples for an operation."""
op = _normalize_op(operation)
pool: list[dict] = []
for row in DATASET_ROWS:
if _normalize_op(row.get("operation", "")) != op:
continue
clue = str(row.get("clue_text", "")).strip()
answer = str(row.get("answer", "")).strip().upper()
if clue and answer:
pool.append({"clue": clue, "answer": answer, "operation": op})
if not pool:
return []
sample_size = min(max(1, limit), len(pool))
return secrets.SystemRandom().sample(pool, sample_size)
def _choose_operations() -> list[str]:
"""Choose three distinct operations that have dataset examples."""
available = [
operation
for operation in RANDOM_OPERATION_POOL
if any(
_normalize_op(row.get("operation", "")) == operation
for row in DATASET_ROWS
)
]
if len(available) < CLUE_COUNT:
raise RuntimeError(
f"Need at least {CLUE_COUNT} dataset-supported operations; found {available}."
)
return secrets.SystemRandom().sample(available, CLUE_COUNT)
def _examples_block(operation: str) -> str:
examples = _dataset_examples_for_op(operation)
if not examples:
return "No matching dataset examples were found for this operation."
return "\n".join(
f"- clue: {example['clue']}\n"
f" answer: {example['answer']}\n"
f" operation: {example['operation']}"
for example in examples
)
# ---------------------------------------------------------------------------
# Wikipedia retrieval
# ---------------------------------------------------------------------------
def fetch_wikipedia(topic: str) -> dict[str, Any]:
"""Fetch the best-matching Wikipedia article for a topic."""
if not topic.strip():
return {"ok": False, "title": "", "url": "", "extract": "", "error": "No topic provided"}
api = "https://en.wikipedia.org/w/api.php"
hdrs = {"User-Agent": "Chroniclues/1.0 (student project)"}
try:
sr = requests.get(api, params={
"action": "query", "list": "search",
"srsearch": topic.strip(), "srlimit": 1,
"format": "json", "utf8": 1,
}, headers=hdrs, timeout=12)
sr.raise_for_status()
results = sr.json().get("query", {}).get("search", [])
if not results:
return {"ok": False, "title": "", "url": "", "extract": "", "error": "No Wikipedia page found"}
title = results[0]["title"]
er = requests.get(api, params={
"action": "query", "prop": "extracts",
"explaintext": 1, "exsectionformat": "plain",
"titles": title, "format": "json", "utf8": 1, "redirects": 1,
}, headers=hdrs, timeout=12)
er.raise_for_status()
pages = er.json().get("query", {}).get("pages", {})
extract = next(iter(pages.values()), {}).get("extract", "").strip()
if not extract:
return {"ok": False, "title": title, "url": "", "extract": "", "error": "No extract"}
url = "https://en.wikipedia.org/wiki/" + quote(title.replace(" ", "_"))
return {"ok": True, "title": title, "url": url, "extract": extract[:6000], "error": ""}
except Exception as exc:
log.warning("Wikipedia fetch failed: %s", exc)
return {"ok": False, "title": "", "url": "", "extract": "", "error": str(exc)}
# ---------------------------------------------------------------------------
# Story planning — Gemini summarises Wikipedia and picks 3 key terms
# ---------------------------------------------------------------------------
_STORY_PROMPT = """\
You are a history educator writing a short narrative for a three-clue historical
escape room from a Wikipedia article.
TOPIC : {topic}
YEAR : {year}
SOURCE : {wiki_title}
WIKIPEDIA TEXT:
{wiki_extract}
INSTRUCTIONS:
A. Write a STORY SUMMARY of 4 to 5 connected sentences about {topic}.
Use this narrative approach: {narrative_style}.
Ground every factual statement in the Wikipedia text.
Vary sentence length and sentence openings. Do not begin with stock wording
such as "The story of...", "As events developed...", or "By the end...".
B. Choose exactly 3 KEY TERMS from your own story_summary.
- Every answer must appear verbatim as a standalone word in story_summary.
- Each answer must be one word, 4-12 letters, uppercase A-Z only.
- All answers must be different.
- Prefer specific people, institutions, places, technologies, or movements.
- Avoid generic words such as CAUSE, EVENT, POWER, PLACE, TIME, WORLD,
PEOPLE, CHANGE, FORCE, ISSUE, HISTORY, and PERIOD.
C. For each term, provide:
- definition: a 2-6 word definition that does not state the answer
- fact: one sentence explaining the term's historical importance
Do not create blank tags and do not create a story template. The application
will insert blanks directly into story_summary after validating that every term
appears in it.
Return only this JSON object:
{{
"topic": "{topic}",
"year": "{year}",
"source_title": "{wiki_title}",
"source_url": "{wiki_url}",
"story_summary": "4-5 sentence topic-specific prose summary",
"terms": [
{{"answer": "FIRSTTERM", "definition": "short phrase", "fact": "one sentence"}},
{{"answer": "SECONDTERM", "definition": "short phrase", "fact": "one sentence"}},
{{"answer": "THIRDTERM", "definition": "short phrase", "fact": "one sentence"}}
]
}}
"""
_CLUE_PROMPT = """\
You are a Parseword (cryptic wordplay) clue writer.
Return a single raw JSON object only. No markdown.
OPERATION: {operation}
TARGET ANSWER: {answer} ({letter_count} letters)
DEFINITION: {definition}
DATASET EXAMPLES FOR THIS OPERATION:
{examples_block}
STRICT MECHANICAL RULES:
hidden_word : answer is a contiguous substring of source_word.
clue_text contains "found in" or "concealed in" and visibly contains source_word as words.
anagram : sorted(source_word) == sorted(answer).
clue_text contains "confused:" or "mixed:" and visibly contains source_word.
reverse : source_word reversed == answer.
clue_text contains "going back" or "reversed" and visibly contains source_word.
deletion : source_word[1:] == answer.
clue_text contains "losing its head" or "beheaded" and visibly contains source_word.
selection : initial letters of the words in source_word spell the answer.
clue_text contains "initially" or "first letters of" and visibly contains source_word.
container : source_word appears strictly inside answer (not equal to full answer).
clue_text contains "holding" or "inside".
ADDITIONAL RULES:
- clue_text must end with ({letter_count}).
- Do NOT use a question mark.
- Do NOT reveal the answer directly in the definition part.
- The clue must read as natural English, imitating the dataset examples above.
OUTPUT SCHEMA:
{{
"clue_text": "...",
"operation": "{operation}",
"source_word": "SOURCE",
"transformation": "SOURCE -> operation -> {answer}",
"hint": "wordplay hint only, no answer",
"validation_explanation": "mechanical proof"
}}
"""
_BATCH_CLUE_PROMPT = """\
You are a Parseword cryptic-wordplay clue writer.
Generate exactly three clues in one response. Return only one raw JSON object.
Do not use markdown or commentary outside JSON.
TARGETS:
{targets_json}
DATASET EXAMPLES GROUPED BY OPERATION:
{examples_text}
MECHANICAL RULES:
hidden_word:
- answer is a contiguous substring of source_word
- clue_text contains "found in", "concealed in", or "within"
- source_word is visibly present in clue_text
delete/deletion:
- removing the first letter of source_word produces answer
- clue_text contains "losing its head" or "beheaded"
- source_word is visibly present in clue_text
reverse:
- reversing source_word produces answer
- clue_text contains "going back", "reversed", or "turned"
- source_word is visibly present in clue_text
anagram:
- sorted(source_word) equals sorted(answer)
- clue_text contains "confused:", "scrambled:", or "mixed:"
- source_word is visibly present in clue_text
container:
- source_word is a proper contiguous substring strictly inside answer
- clue_text contains "inside", "holding", "around", or "embracing"
- the clue surface must visibly include source_word
selection:
- the initial letters of the words in source_word spell answer
- clue_text contains "initially" or "first letters of"
- source_word is visibly present in clue_text
VARIATION RULES:
- Follow each target's style_direction.
- Do not reuse the same sentence frame across the three clues.
- Do not merely copy or lightly edit a dataset example.
- Vary indicator choice whenever the operation permits it.
- Make each clue read like a different human-written clue.
GENERAL RULES:
- Preserve each blank_id and operation exactly.
- Each clue_text must end with the correct letter count, such as (7).
- Do not use a question mark.
- Do not reveal the answer in the definition.
- Keep each clue concise and natural.
- Use the supplied dataset only as style guidance.
Return exactly this structure:
{{
"clues": [
{{
"blank_id": "blank_1",
"clue_text": "...",
"operation": "the exact requested operation",
"source_word": "SOURCE",
"transformation": "mechanical transformation",
"hint": "wordplay hint without the answer",
"validation_explanation": "mechanical proof"
}}
]
}}
"""
# ---------------------------------------------------------------------------
# Text helpers
# ---------------------------------------------------------------------------
def _clean_letters(v: Any) -> str:
return re.sub(r"[^A-Z]", "", str(v or "").upper())
def _clean_answer(v: Any) -> str:
return _clean_letters(v)[:12]
def _usable_answer(answer: str) -> bool:
return (
4 <= len(answer) <= 12
and answer.isalpha()
and answer.lower() not in STOP_WORDS
)
def _extract_json(raw: str) -> dict[str, Any]:
stripped = re.sub(r"```(?:json)?", "", str(raw)).strip()
m = re.search(r"\{.*\}", stripped, re.DOTALL)
if not m:
raise ValueError("No JSON object in model response")
parsed = json.loads(m.group())
if not isinstance(parsed, dict):
raise ValueError("Model JSON was not an object")
return parsed
def _fill_story(template: str, answers: dict[str, str]) -> str:
filled = str(template or "")
for blank_id, answer in answers.items():
filled = filled.replace(f"[[{blank_id}]]", str(answer).upper())
return filled
def _definition_for_term(answer: str) -> str:
"""Produce a minimal safe definition when Gemini didn't supply one."""
return f"key historical term ({len(answer)} letters)"
def _clean_definition(definition: Any, answer: str) -> str:
d = re.sub(r"\s+", " ", str(definition or "")).strip()
if not d or len(d.split()) > 8 or _clean_letters(d) == answer:
return _definition_for_term(answer)
return d
def _template_has_all_blanks(template: str) -> bool:
"""Require every blank exactly once and reject unexpected blank markers."""
expected = {f"blank_{i}" for i in range(1, CLUE_COUNT + 1)}
found = re.findall(r"\[\[(blank_\d+)\]\]", template or "")
return set(found) == expected and all(found.count(blank_id) == 1 for blank_id in expected)
def _source_sentences(text: str) -> list[str]:
return [
sentence.strip()
for sentence in re.split(r"(?<=[.!?])\s+", text or "")
if len(sentence.strip()) > 20
]
def _answer_occurs_in_summary(summary: str, answer: str) -> bool:
if not summary or not answer:
return False
return bool(re.search(r"\b" + re.escape(answer) + r"\b", summary, re.IGNORECASE))
def _sentence_for_answer(summary: str, answer: str) -> str:
for sentence in _source_sentences(summary):
if _answer_occurs_in_summary(sentence, answer):
return sentence
return ""
def _summary_term_candidates(summary: str) -> list[str]:
"""Rank usable one-word terms that actually occur in the generated summary."""
tokens = re.findall(r"\b[A-Za-z][A-Za-z'-]*\b", summary or "")
scores: Counter[str] = Counter()
first_position: dict[str, int] = {}
for index, token in enumerate(tokens):
answer = _clean_answer(token)
if not _usable_answer(answer):
continue
if answer not in first_position:
first_position[answer] = index
scores[answer] += 1
if token[:1].isupper():
scores[answer] += 4
if len(answer) >= 7:
scores[answer] += 1
return sorted(
scores,
key=lambda answer: (-scores[answer], first_position.get(answer, 10**9)),
)
def _inject_blanks_into_summary(summary: str, terms: list[dict[str, Any]]) -> str:
"""Create the puzzle text only by replacing words in the actual summary."""
result = re.sub(r"\s+", " ", summary or "").strip()
for term in terms:
answer = str(term.get("answer", "")).strip()
blank_id = str(term.get("blank_id", "")).strip()
if not answer or not blank_id:
raise ValueError("Cannot build story template from an incomplete term.")
pattern = re.compile(r"\b" + re.escape(answer) + r"\b", re.IGNORECASE)
result, replacements = pattern.subn(f"[[{blank_id}]]", result, count=1)
if replacements != 1:
raise ValueError(
f"Answer {answer!r} does not occur as a standalone word in story_summary."
)
if not _template_has_all_blanks(result):
raise ValueError("Summary injection did not create exactly three blanks.")
return result
def _sentence_containing_blank(template: str, blank_id: str) -> str:
needle = f"[[{blank_id}]]"
for part in re.split(r"(?<=[.!?])\s+", template or ""):
if needle in part:
return part.strip()
return ""
# ---------------------------------------------------------------------------
# Wikipedia fallback term extractor (used when Gemini is unavailable)
# ---------------------------------------------------------------------------
def _fallback_terms(wiki: dict[str, Any], topic: str, n: int = CLUE_COUNT) -> list[str]:
extract = wiki.get("extract", "") or ""
topic_words = {_clean_letters(w) for w in re.split(r"\W+", topic) if len(w) >= 4}
counts: Counter = Counter()
for word in re.findall(r"\b[A-Z][a-z]{3,11}\b", extract):
u = _clean_answer(word)
if _usable_answer(u):
counts[u] += 3
for word in re.findall(r"\b[a-z]{4,12}\b", extract.lower()):
u = _clean_answer(word)
if _usable_answer(u):
counts[u] += 1
ranked = [w for w, _ in counts.most_common()]
for w in topic_words:
if len(ranked) >= n:
break
if 4 <= len(w) <= 12 and w not in ranked:
ranked.append(w)
for fb in ["ARCHIVE", "RECORD", "SOURCE", "MOMENT", "FIGURE", "DETAIL"]:
if len(ranked) >= n:
break
if fb not in ranked:
ranked.append(fb)
return ranked[:n]
# ---------------------------------------------------------------------------
# Story plan — Gemini path + deterministic fallback
# ---------------------------------------------------------------------------
def _build_story_plan(topic: str, year: str, wiki: dict[str, Any]) -> dict[str, Any]:
"""Ask Gemini to summarise the Wikipedia article and identify 3 key terms."""
narrative_style = secrets.choice(NARRATIVE_STYLES)
prompt = _STORY_PROMPT.format(
topic = topic.strip(),
year = year.strip() or "the relevant period",
wiki_title = wiki.get("title", topic),
wiki_url = wiki.get("url", ""),
wiki_extract= wiki.get("extract", ""),
narrative_style=narrative_style,
)
if gemini_configured():
try:
raw = invoke_gemini(prompt, temperature=0.50)
plan = _extract_json(raw)
plan = _repair_plan(plan, topic, year, wiki)
ok, reason = _validate_plan(plan)
if ok:
plan["story_plan_mode"] = "gemini"
log.info("Story template origin: %s", plan.get("template_origin"))
return plan
log.warning("Gemini plan failed validation: %s", reason)
except Exception as exc:
log.warning("Gemini story plan failed: %s", exc)
return _deterministic_plan(topic, year, wiki)
def _repair_plan(plan: dict[str, Any], topic: str, year: str, wiki: dict[str, Any]) -> dict[str, Any]:
"""Keep only terms found in Gemini's summary, then inject blanks into that summary."""
prose_summary = re.sub(
r"\s+",
" ",
str(plan.get("story_summary") or "").strip(),
)
if not prose_summary:
prose_summary = " ".join(_source_sentences(str(wiki.get("extract", "")))[:5])
if not prose_summary:
raise ValueError("No story summary was available for blank insertion.")
raw_terms = plan.get("terms", []) if isinstance(plan.get("terms"), list) else []
seen: set[str] = set()
terms: list[dict[str, Any]] = []
# Prefer Gemini's terms, but only when they are actual words in the summary.
for raw in raw_terms:
if not isinstance(raw, dict):
continue
answer = _clean_answer(raw.get("answer", ""))
if (
not _usable_answer(answer)
or answer in seen
or not _answer_occurs_in_summary(prose_summary, answer)
):
continue
seen.add(answer)
terms.append({
"blank_id": f"blank_{len(terms) + 1}",
"answer": answer,
"definition": _clean_definition(raw.get("definition", ""), answer),
"fact": str(raw.get("fact") or _sentence_for_answer(prose_summary, answer)).strip(),
})
if len(terms) == CLUE_COUNT:
break
# Fill missing slots only with words that occur in the same generated summary.
for answer in _summary_term_candidates(prose_summary):
if len(terms) == CLUE_COUNT:
break
if answer in seen:
continue
seen.add(answer)
terms.append({
"blank_id": f"blank_{len(terms) + 1}",
"answer": answer,
"definition": _definition_for_term(answer),
"fact": _sentence_for_answer(prose_summary, answer),
})
if len(terms) != CLUE_COUNT:
raise ValueError(
f"Could not identify {CLUE_COUNT} usable terms inside story_summary."
)
# Never accept or construct a separate stock template. The puzzle paragraph
# is always Gemini's own summary with three words replaced in place.
template = _inject_blanks_into_summary(prose_summary, terms)
return {
"topic": str(plan.get("topic") or topic),
"year": str(plan.get("year") or year),
"source_title": str(plan.get("source_title") or wiki.get("title", "")),
"source_url": str(plan.get("source_url") or wiki.get("url", "")),
"story_summary": prose_summary,
"final_story_template": template,
"terms": terms,
"template_origin": "gemini_summary_word_replacement",
}
def _validate_plan(plan: dict[str, Any]) -> tuple[bool, str]:
terms = plan.get("terms", [])
if not isinstance(terms, list) or len(terms) != CLUE_COUNT:
return False, f"expected {CLUE_COUNT} terms, got {len(terms) if isinstance(terms, list) else '?'}"
seen: set[str] = set()
for i, term in enumerate(terms, 1):
a = _clean_answer(term.get("answer", ""))
if term.get("blank_id") != f"blank_{i}":
return False, f"blank_id mismatch at position {i}"
if not _usable_answer(a):
return False, f"unusable answer '{a}' at blank_{i}"
if a in seen:
return False, f"duplicate answer '{a}'"
seen.add(a)
if not _template_has_all_blanks(str(plan.get("final_story_template", ""))):
return False, "final_story_template missing blanks"
return True, "ok"
def _deterministic_plan(topic: str, year: str, wiki: dict[str, Any]) -> dict[str, Any]:
"""Fallback that still derives blanks directly from source prose, never a stock template."""
summary = " ".join(_source_sentences(str(wiki.get("extract", "")))[:5])
if not summary:
raise RuntimeError(
"Could not build a story because both Gemini planning and Wikipedia text were unavailable."
)
candidates = _summary_term_candidates(summary)
if len(candidates) < CLUE_COUNT:
raise RuntimeError(
f"Wikipedia summary contained fewer than {CLUE_COUNT} usable terms."
)
# Randomize among strong source-derived candidates so fallback puzzles are
# not tied to the same words on every request.
candidate_pool = candidates[: min(12, len(candidates))]
answers = secrets.SystemRandom().sample(candidate_pool, CLUE_COUNT)
terms = [
{
"blank_id": f"blank_{index}",
"answer": answer,
"definition": _definition_for_term(answer),
"fact": _sentence_for_answer(summary, answer),
}
for index, answer in enumerate(answers, 1)
]
template = _inject_blanks_into_summary(summary, terms)
return {
"topic": topic,
"year": year,
"source_title": wiki.get("title", ""),
"source_url": wiki.get("url", ""),
"story_summary": summary,
"final_story_template": template,
"terms": terms,
"story_plan_mode": "wikipedia_summary_fallback",
"template_origin": "wikipedia_summary_word_replacement",
}
# ---------------------------------------------------------------------------
# Clue generation
# ---------------------------------------------------------------------------
def _make_anagram_source(word: str) -> str:
w = _clean_answer(word)
if len(w) <= 3:
return w[::-1]
s = w[2:] + w[:2]
return s if s != w else w[::-1]
_SELECTION_WORDS = {
"A": "ancient", "B": "bold", "C": "chroniclers", "D": "document",
"E": "enduring", "F": "forgotten", "G": "guarded", "H": "histories",
"I": "important", "J": "journals", "K": "keep", "L": "legacies",
"M": "mark", "N": "notable", "O": "origins", "P": "preserve",
"Q": "quietly", "R": "records", "S": "stories", "T": "through",
"U": "uncover", "V": "valuable", "W": "worlds", "X": "xenial",
"Y": "young", "Z": "zealous",
}
def _make_selection_source(answer: str) -> str:
"""Build a phrase whose initial letters spell the answer."""
return " ".join(_SELECTION_WORDS[letter] for letter in _clean_answer(answer))
def _build_clue_python(answer: str, definition: str, operation: str) -> dict[str, Any]:
"""Deterministic, mechanically guaranteed Parseword clue."""
answer = _clean_answer(answer)
n = len(answer)
d = definition.strip().rstrip(".") or "key historical term"
operation = _normalize_op(operation)
if operation == "hidden_word":
carrier = f"ARCHIVE{answer}ROOM"
return {
"clue_text": f"{d} found in archive {answer.lower()} room ({n})",
"operation": "hidden_word",
"source_word": carrier,
"transformation": f"{answer} hidden inside {carrier}",
"hint": f"Look inside 'archive {answer.lower()} room'.",
"validation_explanation": f"{answer} is a contiguous substring of {carrier}.",
"clue_generation": "python_builder",
}
if operation == "anagram":
src = _make_anagram_source(answer)
return {
"clue_text": f"{d}, confused: {src} ({n})",
"operation": "anagram",
"source_word": src,
"transformation": f"{src} rearranged → {answer}",
"hint": f"Rearrange {src}.",
"validation_explanation": f"sorted({src}) == sorted({answer}).",
"clue_generation": "python_builder",
}
if operation == "reverse":
src = answer[::-1]
return {
"clue_text": f"{d}, going back: {src} ({n})",
"operation": "reverse",
"source_word": src,
"transformation": f"{src} reversed → {answer}",
"hint": f"Reverse {src}.",
"validation_explanation": f"{src}[::-1] = {answer}.",
"clue_generation": "python_builder",
}
if operation == "deletion":
head = "S" if not answer.startswith("S") else "T"
src = head + answer
return {
"clue_text": f"{d}, losing its head: {src} ({n})",
"operation": "deletion",
"source_word": src,
"transformation": f"{src} → remove {head} → {answer}",
"hint": f"Remove the first letter of {src}.",
"validation_explanation": f"{src}[1:] = {answer}.",
"clue_generation": "python_builder",
}
if operation == "selection":
phrase = _make_selection_source(answer)
return {
"clue_text": f"{d}, initially: {phrase} ({n})",
"operation": "selection",
"source_word": phrase,
"transformation": f"initial letters of {phrase} → {answer}",
"hint": "Take the first letter of each word.",
"validation_explanation": f"Initial letters of '{phrase}' spell {answer}.",
"clue_generation": "python_builder",
}
if operation == "container" and n >= 4:
inner = answer[1:-1]
outer = answer[0] + answer[-1]
return {
"clue_text": f"{d}, holding {inner.lower()} inside {outer.lower()} ({n})",
"operation": "container",
"source_word": inner,
"transformation": f"{outer} holding {inner} → {answer}",
"hint": f"Middle letters {inner} inside outer {outer}.",
"validation_explanation": f"{inner} appears inside {answer}.",
"clue_generation": "python_builder",
}
# ultimate fallback — hidden word always works
return _build_clue_python(answer, definition, "hidden_word")
def _generate_clue_gemini(answer: str, definition: str, operation: str) -> dict[str, Any]:
"""Ask Gemini to write a dataset-style clue, fall back to Python builder."""
operation = _normalize_op(operation)
if not gemini_configured():
return _build_clue_python(answer, definition, operation)
prompt = _CLUE_PROMPT.format(
operation = operation,
examples_block = _examples_block(operation),
answer = answer,
definition = definition,
letter_count = len(answer),
)
try:
raw = invoke_gemini(prompt, temperature=0.2)
parsed = _extract_json(raw)
candidate = {
"clue_text": str(parsed.get("clue_text", "")).strip(),
"operation": operation,
"source_word": str(parsed.get("source_word", "")).strip(),
"transformation": str(parsed.get("transformation", "")).strip(),
"hint": str(parsed.get("hint", "")).strip(),
"validation_explanation": str(parsed.get("validation_explanation", "")).strip(),
"clue_generation": "gemini_dataset_fewshot",
"dataset_examples_used": len(_dataset_examples_for_op(operation)),
}
return candidate
except Exception as exc:
log.warning("Gemini clue generation failed for %s (%s): %s", answer, operation, exc)
return _build_clue_python(answer, definition, operation)
def _batch_examples_text(operations: list[str], examples_per_operation: int = 3) -> str:
sections: list[str] = []
for operation in dict.fromkeys(operations):
sections.append(f"[{operation.upper()}]")
examples = _dataset_examples_for_op(operation, limit=examples_per_operation)
if not examples:
sections.append("No dataset examples available.")
continue
for example in examples:
sections.append(
f"- clue: {example['clue']}\n"
f" answer: {example['answer']}"
)
return "\n".join(sections)
def _generate_clues_gemini_batch(
terms: list[dict[str, Any]],
operations: list[str],
) -> list[dict[str, Any]]:
"""Generate all three clues with one Gemini request."""
if not gemini_configured():
raise RuntimeError("Gemini is not configured.")
if len(operations) != CLUE_COUNT:
raise ValueError(f"Expected {CLUE_COUNT} operations, got {len(operations)}.")
style_directions = secrets.SystemRandom().sample(
CLUE_STYLE_DIRECTIONS,
CLUE_COUNT,
)
targets: list[dict[str, Any]] = []
for index, term in enumerate(terms[:CLUE_COUNT]):
answer = _clean_answer(term.get("answer", ""))
operation = operations[index]
definition = _clean_definition(term.get("definition", ""), answer)
targets.append({
"blank_id": f"blank_{index + 1}",
"answer": answer,
"letter_count": len(answer),
"definition": definition,
"operation": operation,
"style_direction": style_directions[index],
})
prompt = _BATCH_CLUE_PROMPT.format(
targets_json=json.dumps(targets, ensure_ascii=False, indent=2),
examples_text=_batch_examples_text(
[str(target["operation"]) for target in targets],
examples_per_operation=3,
),
)
raw = invoke_gemini(prompt, temperature=0.2)
parsed = _extract_json(raw)
raw_clues = parsed.get("clues")
if not isinstance(raw_clues, list):
raise ValueError("Gemini batch response is missing a clues list.")
target_by_blank = {str(target["blank_id"]): target for target in targets}
generated: list[dict[str, Any]] = []
for item in raw_clues:
if not isinstance(item, dict):
continue
blank_id = str(item.get("blank_id", "")).strip()
target = target_by_blank.get(blank_id)
if target is None:
continue
generated.append({
"blank_id": blank_id,
"clue_text": str(item.get("clue_text", "")).strip(),
"operation": str(target["operation"]),
"source_word": str(item.get("source_word", "")).strip(),
"transformation": str(item.get("transformation", "")).strip(),
"hint": str(item.get("hint", "")).strip(),