-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1198 lines (988 loc) · 40.5 KB
/
app.py
File metadata and controls
1198 lines (988 loc) · 40.5 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
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Sequence
from flask import Flask, jsonify, redirect, render_template, request, session, url_for
from game_logic import (
DESTRUCTION_ZONE_SIZE,
calculate_board_size,
count_remaining_words,
initialize_game_state,
resolve_turn,
)
from game_logic_blocks import (
BLOCKS_COMBO_THRESHOLD,
initialize_blocks_state,
occupied_neighbors,
occupied_word_indices,
resolve_blocks_turn,
serialize_blocks_grid,
)
from game_logic_restriction import (
RestrictionRule,
initialize_restriction_state,
load_restriction_rules,
local_rule_supported,
resolve_restriction_turn,
validate_clue_locally,
)
from llm_client import (
BlocksCandidate,
BlocksPrimaryChoiceResult,
BlocksCandidateScore,
BlocksCandidateScoringResult,
build_ranker_from_env,
format_startup_probe_message,
normalize_word,
run_startup_probe,
)
from persistence import BestRunSummary, RunStore, build_run_store
from settings import Settings, get_settings
SETTINGS = get_settings()
BASE_DIR = SETTINGS.base_dir
ASSETS_DIR = SETTINGS.assets_dir
DEFAULT_VOCAB_FILE = SETTINGS.default_vocab_file
RESTRICTION_RULES_FILE = SETTINGS.restriction_rules_file
CONFIGURED_VOCAB_FILE = SETTINGS.configured_vocab_file
SELECTED_PACK_SESSION_KEY = "selected_pack_id"
SELECTED_MODE_SESSION_KEY = "selected_mode_id"
ACTIVE_LLM_PROVIDER = SETTINGS.semantris_llm_provider
MODE_IDS = {
"iteration": "iteration",
"restriction": "restriction",
"blocks": "blocks",
}
MODE_PAGE_ENDPOINTS = {
MODE_IDS["iteration"]: "iteration_mode",
MODE_IDS["restriction"]: "restriction_mode",
MODE_IDS["blocks"]: "blocks_mode",
}
BLOCKS_PRIMARY_BATCH_SIZE = 8
BLOCKS_SCORING_BATCH_SIZE = 6
app = Flask(__name__)
app.secret_key = SETTINGS.flask_secret_key or os.urandom(24)
RUN_STORE = build_run_store(SETTINGS)
def _env_flag(name: str) -> bool:
if name == "SEMANTRIS_DEBUG_BLOCKS_LLM":
return SETTINGS.semantris_debug_blocks_llm
return os.getenv(name, "0").strip().lower() in {"1", "true", "yes", "on"}
def _emit_blocks_app_debug_trace(label: str, payload: Any) -> None:
if not _env_flag("SEMANTRIS_DEBUG_BLOCKS_LLM"):
return
print(f"[Blocks App Debug] {label}={payload}", flush=True)
@dataclass
class BlocksLlmAggregate:
latency_ms: int = 0
providers: list[str] = field(default_factory=list)
used_fallback: bool = False
warnings: list[str] = field(default_factory=list)
def record(self, result: Any) -> None:
self.latency_ms += max(0, int(getattr(result, "latency_ms", 0) or 0))
provider = getattr(result, "provider", None)
if isinstance(provider, str) and provider and provider not in self.providers:
self.providers.append(provider)
if bool(getattr(result, "used_fallback", False)):
self.used_fallback = True
warning = getattr(result, "warning", None)
if isinstance(warning, str) and warning and warning not in self.warnings:
self.warnings.append(warning)
@property
def provider_label(self) -> str | None:
return _combine_provider_labels(*self.providers)
@property
def warning_text(self) -> str | None:
return _join_warnings(*self.warnings)
def _partition_evenly(items: Sequence[Any], max_batch_size: int) -> list[list[Any]]:
if max_batch_size <= 0:
raise ValueError("Batch size must be positive.")
if not items:
return []
batch_count = max(1, (len(items) + max_batch_size - 1) // max_batch_size)
batches: list[list[Any]] = [[] for _ in range(batch_count)]
for index, item in enumerate(items):
batches[index % batch_count].append(item)
return [batch for batch in batches if batch]
def load_vocabulary(vocab_file: Path) -> list[str]:
if not vocab_file.exists():
raise FileNotFoundError(f"Vocabulary file not found: {vocab_file}")
deduped_words: list[str] = []
seen: set[str] = set()
with vocab_file.open("r", encoding="utf-8") as handle:
for raw_line in handle:
word = raw_line.strip()
if not word:
continue
normalized = normalize_word(word)
if normalized in seen:
continue
seen.add(normalized)
deduped_words.append(word)
if not deduped_words:
raise ValueError(f"Vocabulary file is empty: {vocab_file}")
return deduped_words
@dataclass(frozen=True)
class VocabularyPack:
pack_id: str
file_path: Path
display_name: str
words: tuple[str, ...]
@property
def word_count(self) -> int:
return len(self.words)
def build_vocabulary_catalog(assets_dir: Path) -> dict[str, VocabularyPack]:
catalog: dict[str, VocabularyPack] = {}
for vocab_file in sorted(assets_dir.glob("*.txt")):
pack_id = vocab_file.stem
if pack_id in catalog:
raise ValueError(f"Duplicate vocabulary pack id: {pack_id}")
catalog[pack_id] = VocabularyPack(
pack_id=pack_id,
file_path=vocab_file,
display_name=pack_id,
words=tuple(load_vocabulary(vocab_file)),
)
if not catalog:
raise ValueError(f"No vocabulary packs found in {assets_dir}")
return catalog
def resolve_default_pack_id(catalog: dict[str, VocabularyPack]) -> str:
configured_id = CONFIGURED_VOCAB_FILE.stem
if configured_id in catalog:
return configured_id
default_id = DEFAULT_VOCAB_FILE.stem
if default_id in catalog:
return default_id
return next(iter(catalog))
VOCABULARY_CATALOG = build_vocabulary_catalog(ASSETS_DIR)
DEFAULT_VOCAB_PACK_ID = resolve_default_pack_id(VOCABULARY_CATALOG)
RESTRICTION_RULES = load_restriction_rules(RESTRICTION_RULES_FILE)
RESTRICTION_RULES_BY_ID = {rule.rule_id: rule for rule in RESTRICTION_RULES}
RANKER = build_ranker_from_env(provider_name=ACTIVE_LLM_PROVIDER, settings=SETTINGS)
def selected_pack_id_from_session() -> str:
pack_id = session.get(SELECTED_PACK_SESSION_KEY)
if isinstance(pack_id, str) and pack_id in VOCABULARY_CATALOG:
return pack_id
return DEFAULT_VOCAB_PACK_ID
def selected_mode_id_from_session() -> str:
mode_id = session.get(SELECTED_MODE_SESSION_KEY)
if isinstance(mode_id, str) and mode_id in MODE_IDS.values():
return mode_id
return MODE_IDS["iteration"]
def get_selected_pack() -> VocabularyPack:
return VOCABULARY_CATALOG[selected_pack_id_from_session()]
def vocabulary_pack_options() -> list[dict[str, Any]]:
return [
{
"id": pack.pack_id,
"display_name": pack.display_name,
"word_count": pack.word_count,
}
for pack in VOCABULARY_CATALOG.values()
]
def words_for_indices(indices: list[int], vocabulary: tuple[str, ...]) -> list[str]:
return [vocabulary[index] for index in indices]
def _game_result_for_state(state: dict[str, Any]) -> str | None:
game_result = state.get("game_result")
if isinstance(game_result, str):
return game_result
if state.get("game_over"):
return "win"
return None
def _elapsed_seconds_for_state(state: dict[str, Any]) -> int:
started_at_ms = int(state.get("started_at_ms", 0) or 0)
ended_at_ms = int(state.get("ended_at_ms", started_at_ms) or started_at_ms)
return max(0, round((ended_at_ms - started_at_ms) / 1000))
def _best_run_payload(summary: BestRunSummary | None) -> dict[str, Any] | None:
if summary is None:
return None
return {
"run_record_id": summary.run_record_id,
"score": summary.score,
"turns": summary.turns,
"elapsed_seconds": summary.elapsed_seconds,
"created_at": summary.created_at_iso,
}
def _state_with_persistence_metadata(
state: dict[str, Any],
*,
mode_id: str,
pack: VocabularyPack,
) -> dict[str, Any]:
updated_state = dict(state)
updated_state.setdefault("persisted_run_id", None)
updated_state.setdefault("persisted_run_is_new_best", False)
if "best_run_summary" not in updated_state:
updated_state["best_run_summary"] = _best_run_payload(
RUN_STORE.best_run_for(mode_id=mode_id, pack_id=pack.pack_id)
)
return updated_state
def _persist_completed_run_if_needed(
state: dict[str, Any],
*,
mode_id: str,
pack: VocabularyPack,
) -> dict[str, Any]:
updated_state = _state_with_persistence_metadata(state, mode_id=mode_id, pack=pack)
if not updated_state.get("game_over"):
return updated_state
if updated_state.get("persisted_run_id") is not None:
return updated_state
recorded = RUN_STORE.record_completed_run(
mode_id=mode_id,
pack_id=pack.pack_id,
vocabulary_name=pack.file_path.name,
score=int(updated_state.get("score", 0) or 0),
turns=int(updated_state.get("turn_count", 0) or 0),
elapsed_seconds=_elapsed_seconds_for_state(updated_state),
game_result=_game_result_for_state(updated_state) or "win",
provider_label=updated_state.get("last_provider"),
used_fallback=bool(updated_state.get("used_fallback", False)),
)
updated_state["persisted_run_id"] = recorded.run_record_id
updated_state["persisted_run_is_new_best"] = recorded.is_new_best
updated_state["best_run_summary"] = _best_run_payload(recorded.best_run)
return updated_state
def _persistence_payload(state: dict[str, Any]) -> dict[str, Any]:
return {
"run_record_id": state.get("persisted_run_id"),
"run_saved": state.get("persisted_run_id") is not None,
"is_new_best": bool(state.get("persisted_run_is_new_best", False)),
"best_run": state.get("best_run_summary"),
}
def serialize_iteration_state(state: dict[str, Any], pack: VocabularyPack) -> dict[str, Any]:
board_words = words_for_indices(state["board_indices"], pack.words)
target_index = state.get("target_index")
target_word = pack.words[target_index] if target_index is not None else None
remaining_words = count_remaining_words(pack.word_count, state["used_mask"])
danger_zone_size = min(DESTRUCTION_ZONE_SIZE, len(board_words))
return {
"mode_id": state.get("mode_id", MODE_IDS["iteration"]),
"score": state["score"],
"board": board_words,
"target_word": target_word,
"turn_count": state["turn_count"],
"started_at_ms": state["started_at_ms"],
"ended_at_ms": state.get("ended_at_ms"),
"last_latency_ms": state.get("last_latency_ms"),
"last_provider": state.get("last_provider"),
"used_fallback": state.get("used_fallback", False),
"last_warning": state.get("last_warning"),
"last_clue": state.get("last_clue"),
"game_over": state.get("game_over", False),
"game_result": _game_result_for_state(state),
"vocabulary_name": state["vocabulary_name"],
"board_goal_size": min(calculate_board_size(state["score"]), pack.word_count),
"danger_zone_size": danger_zone_size,
"danger_zone_words": board_words[-danger_zone_size:],
"remaining_words": remaining_words,
"seen_words": pack.word_count - remaining_words,
"total_vocabulary": pack.word_count,
"run_exhausted": remaining_words == 0,
"persistence": _persistence_payload(state),
}
def serialize_restriction_state(state: dict[str, Any], pack: VocabularyPack) -> dict[str, Any]:
payload = serialize_iteration_state(state, pack)
active_rule = RESTRICTION_RULES_BY_ID.get(str(state.get("active_rule_id", "")).strip())
payload.update(
{
"mode_id": MODE_IDS["restriction"],
"strike_count": state.get("strike_count", 0),
"max_strikes": state.get("max_strikes", 0),
"active_rule_id": state.get("active_rule_id"),
"active_rule_name": active_rule.display_name if active_rule else "Unknown rule",
"active_rule_description": active_rule.description if active_rule else "No rule loaded.",
"last_rule_passed": state.get("last_rule_passed"),
"last_rule_reason": state.get("last_rule_reason"),
}
)
return payload
def serialize_blocks_state(state: dict[str, Any], pack: VocabularyPack) -> dict[str, Any]:
remaining_words = count_remaining_words(pack.word_count, state["used_mask"])
last_primary_index = state.get("last_primary_index")
last_scored_cells = []
for item in state.get("last_scored_cells", []):
index = item.get("index")
if index is None:
continue
last_scored_cells.append(
{
"cell": item.get("cell"),
"word": pack.words[index],
"score": item.get("score"),
}
)
return {
"mode_id": MODE_IDS["blocks"],
"score": state["score"],
"turn_count": state["turn_count"],
"started_at_ms": state["started_at_ms"],
"ended_at_ms": state.get("ended_at_ms"),
"last_latency_ms": state.get("last_latency_ms"),
"last_provider": state.get("last_provider"),
"used_fallback": state.get("used_fallback", False),
"last_warning": state.get("last_warning"),
"last_clue": state.get("last_clue"),
"game_over": state.get("game_over", False),
"game_result": _game_result_for_state(state),
"vocabulary_name": state["vocabulary_name"],
"remaining_words": remaining_words,
"seen_words": pack.word_count - remaining_words,
"total_vocabulary": pack.word_count,
"grid_width": state["grid_width"],
"grid_height": state["grid_height"],
"cells": serialize_blocks_grid(state["grid_indices"], pack.words, state["grid_width"]),
"target_occupied_cells": state["target_occupied_cells"],
"last_primary_word": pack.words[last_primary_index] if last_primary_index is not None else None,
"last_primary_cell": state.get("last_primary_cell"),
"last_chain_words": words_for_indices(list(state.get("last_chain_indices", [])), pack.words),
"last_chain_size": state.get("last_chain_size", 0),
"last_scored_cells": last_scored_cells,
"persistence": _persistence_payload(state),
}
def _commit_session_state(pack: VocabularyPack, mode_id: str, state: dict[str, Any]) -> None:
session.clear()
session[SELECTED_PACK_SESSION_KEY] = pack.pack_id
session[SELECTED_MODE_SESSION_KEY] = mode_id
session.update(state)
session.modified = True
def initialize_iteration_session(pack: VocabularyPack | None = None) -> dict[str, Any]:
pack = pack or get_selected_pack()
state = initialize_game_state(
vocabulary_size=pack.word_count,
vocabulary_name=pack.file_path.name,
)
state = {
**state,
"mode_id": MODE_IDS["iteration"],
"game_result": None,
}
state = _state_with_persistence_metadata(state, mode_id=MODE_IDS["iteration"], pack=pack)
_commit_session_state(pack, MODE_IDS["iteration"], state)
return state
def initialize_restriction_session(pack: VocabularyPack | None = None) -> dict[str, Any]:
pack = pack or get_selected_pack()
state = initialize_restriction_state(
vocabulary_size=pack.word_count,
vocabulary_name=pack.file_path.name,
rules=RESTRICTION_RULES,
)
state = _state_with_persistence_metadata(state, mode_id=MODE_IDS["restriction"], pack=pack)
_commit_session_state(pack, MODE_IDS["restriction"], state)
return state
def initialize_blocks_session(pack: VocabularyPack | None = None) -> dict[str, Any]:
pack = pack or get_selected_pack()
state = initialize_blocks_state(
vocabulary_size=pack.word_count,
vocabulary_name=pack.file_path.name,
)
state = _state_with_persistence_metadata(state, mode_id=MODE_IDS["blocks"], pack=pack)
_commit_session_state(pack, MODE_IDS["blocks"], state)
return state
def initialize_session(pack: VocabularyPack | None = None) -> dict[str, Any]:
return initialize_iteration_session(pack)
def _initialize_mode_session(mode_id: str, pack: VocabularyPack | None = None) -> dict[str, Any]:
if mode_id == MODE_IDS["iteration"]:
return initialize_iteration_session(pack)
if mode_id == MODE_IDS["restriction"]:
return initialize_restriction_session(pack)
if mode_id == MODE_IDS["blocks"]:
return initialize_blocks_session(pack)
raise ValueError(f"Unsupported mode id: {mode_id}")
def _mode_state_matches(
session_state: dict[str, Any],
mode_id: str,
pack: VocabularyPack,
) -> bool:
if session_state.get(SELECTED_MODE_SESSION_KEY) != mode_id:
return False
if session_state.get("mode_id") != mode_id:
return False
if session_state.get("vocabulary_name") != pack.file_path.name:
return False
if mode_id in {MODE_IDS["iteration"], MODE_IDS["restriction"]}:
return "board_indices" in session_state
if mode_id == MODE_IDS["blocks"]:
return "grid_indices" in session_state
return False
def _current_mode_state(mode_id: str) -> dict[str, Any]:
pack = get_selected_pack()
session_state = dict(session)
if not _mode_state_matches(session_state, mode_id, pack):
return _initialize_mode_session(mode_id, pack)
finalized_state = _persist_completed_run_if_needed(session_state, mode_id=mode_id, pack=pack)
if finalized_state != session_state:
_commit_session_state(pack, mode_id, finalized_state)
return finalized_state
def current_state() -> dict[str, Any]:
return _current_mode_state(MODE_IDS["iteration"])
def current_iteration_state() -> dict[str, Any]:
return _current_mode_state(MODE_IDS["iteration"])
def current_restriction_state() -> dict[str, Any]:
return _current_mode_state(MODE_IDS["restriction"])
def current_blocks_state() -> dict[str, Any]:
return _current_mode_state(MODE_IDS["blocks"])
def _selected_pack_from_form() -> VocabularyPack | None:
pack_id = str(request.form.get("vocabulary_pack_id", "")).strip()
return VOCABULARY_CATALOG.get(pack_id)
def _page_endpoint_for_mode(mode_id: str) -> str:
return MODE_PAGE_ENDPOINTS.get(mode_id, MODE_PAGE_ENDPOINTS[MODE_IDS["iteration"]])
def _current_target_word(state: dict[str, Any], pack: VocabularyPack) -> str | None:
target_index = state.get("target_index")
if target_index is None:
return None
return pack.words[target_index]
def _combine_provider_labels(*providers: str | None) -> str | None:
labels: list[str] = []
for provider in providers:
if not provider or provider in labels:
continue
labels.append(provider)
if not labels:
return None
if len(labels) == 1:
return labels[0]
return "/".join(labels)
def _join_warnings(*warnings: str | None) -> str | None:
parts: list[str] = []
for warning in warnings:
if not warning or warning in parts:
continue
parts.append(warning)
if not parts:
return None
return " ".join(parts)
def _build_blocks_candidates(
cells: Sequence[int],
grid_indices: Sequence[int | None],
pack: VocabularyPack,
) -> list[BlocksCandidate]:
return [
BlocksCandidate(candidate_id=cell, word=pack.words[word_index])
for cell in cells
if (word_index := grid_indices[cell]) is not None
]
def _select_blocks_primary_candidate(
clue: str,
candidates: Sequence[BlocksCandidate],
) -> BlocksPrimaryChoiceResult:
if not candidates:
raise ValueError("Blocks mode requires at least one occupied candidate.")
if len(candidates) == 1:
return BlocksPrimaryChoiceResult(
candidate_id=candidates[0].candidate_id,
latency_ms=0,
provider="local-single-candidate",
used_fallback=False,
warning=None,
)
aggregate = BlocksLlmAggregate()
round_candidates = list(candidates)
round_number = 1
while len(round_candidates) > 1:
batches = _partition_evenly(round_candidates, BLOCKS_PRIMARY_BATCH_SIZE)
_emit_blocks_app_debug_trace(
f"primary_round_{round_number}_batches",
[[(candidate.candidate_id, candidate.word) for candidate in batch] for batch in batches],
)
winners: list[BlocksCandidate] = []
winner_trace: list[dict[str, Any]] = []
for batch in batches:
if len(batch) == 1:
selected_id = batch[0].candidate_id
batch_provider = "local-bye"
batch_used_fallback = False
batch_warning = None
else:
result = RANKER.pick_blocks_primary_candidate(clue, batch)
aggregate.record(result)
selected_id = result.candidate_id
batch_provider = result.provider
batch_used_fallback = result.used_fallback
batch_warning = result.warning
batch_lookup = {candidate.candidate_id: candidate for candidate in batch}
winner = batch_lookup[selected_id]
winners.append(winner)
winner_trace.append(
{
"candidate_id": winner.candidate_id,
"word": winner.word,
"provider": batch_provider,
"used_fallback": batch_used_fallback,
"warning": batch_warning,
}
)
_emit_blocks_app_debug_trace(f"primary_round_{round_number}_winners", winner_trace)
round_candidates = winners
round_number += 1
return BlocksPrimaryChoiceResult(
candidate_id=round_candidates[0].candidate_id,
latency_ms=aggregate.latency_ms,
provider=aggregate.provider_label or "local-single-candidate",
used_fallback=aggregate.used_fallback,
warning=aggregate.warning_text,
)
def _score_blocks_frontier(
clue: str,
state: dict[str, Any],
pack: VocabularyPack,
primary_cell: int,
) -> tuple[dict[int, int], BlocksLlmAggregate]:
grid_indices = list(state["grid_indices"])
width = int(state["grid_width"])
height = int(state["grid_height"])
aggregate = BlocksLlmAggregate()
scored_cells: dict[int, int] = {primary_cell: 100}
expanding_cells = [primary_cell]
seen_cells: set[int] = {primary_cell}
wave_number = 1
while expanding_cells:
frontier_cells: list[int] = []
for cell in expanding_cells:
for neighbor in occupied_neighbors(grid_indices, cell, width, height):
if neighbor in seen_cells or grid_indices[neighbor] is None:
continue
seen_cells.add(neighbor)
frontier_cells.append(neighbor)
if not frontier_cells:
break
frontier_cells = sorted(set(frontier_cells))
frontier_candidates = _build_blocks_candidates(frontier_cells, grid_indices, pack)
batches = _partition_evenly(frontier_candidates, BLOCKS_SCORING_BATCH_SIZE)
_emit_blocks_app_debug_trace(
f"scoring_wave_{wave_number}_batches",
[[(candidate.candidate_id, candidate.word) for candidate in batch] for batch in batches],
)
wave_scores: dict[int, int] = {}
for batch in batches:
result = RANKER.score_blocks_candidates(clue, batch)
aggregate.record(result)
for item in result.scored_candidates:
wave_scores[item.candidate_id] = item.score
scored_cells[item.candidate_id] = item.score
scored_trace = [
{
"candidate_id": cell,
"word": pack.words[grid_indices[cell]],
"score": wave_scores[cell],
}
for cell in frontier_cells
if cell in wave_scores and grid_indices[cell] is not None
]
_emit_blocks_app_debug_trace(f"scoring_wave_{wave_number}_scores", scored_trace)
expanding_cells = [
cell
for cell in frontier_cells
if wave_scores.get(cell, 0) >= BLOCKS_COMBO_THRESHOLD
]
_emit_blocks_app_debug_trace(f"scoring_wave_{wave_number}_advancing", expanding_cells)
wave_number += 1
return scored_cells, aggregate
@app.get("/")
def index() -> str:
return render_template(
"home.html",
vocabulary_packs=vocabulary_pack_options(),
selected_pack_id=selected_pack_id_from_session(),
selected_mode_id=selected_mode_id_from_session(),
)
@app.get("/iteration-mode")
def iteration_mode() -> str:
return render_template("arcade.html")
@app.post("/start-iteration-mode")
def start_iteration_mode() -> Any:
pack = _selected_pack_from_form()
if pack is None:
return ("Unknown vocabulary pack.", 400)
initialize_iteration_session(pack)
return redirect(url_for("iteration_mode"))
@app.get("/restriction-mode")
def restriction_mode() -> str:
return render_template("restriction.html")
@app.post("/start-restriction-mode")
def start_restriction_mode() -> Any:
pack = _selected_pack_from_form()
if pack is None:
return ("Unknown vocabulary pack.", 400)
initialize_restriction_session(pack)
return redirect(url_for("restriction_mode"))
@app.get("/blocks-mode")
def blocks_mode() -> str:
return render_template("blocks.html")
@app.post("/start-blocks-mode")
def start_blocks_mode() -> Any:
pack = _selected_pack_from_form()
if pack is None:
return ("Unknown vocabulary pack.", 400)
initialize_blocks_session(pack)
return redirect(url_for("blocks_mode"))
@app.get("/play")
def play() -> Any:
return redirect(url_for(_page_endpoint_for_mode(selected_mode_id_from_session())))
@app.get("/api/game/state")
def game_state() -> Any:
state = current_iteration_state()
pack = get_selected_pack()
return jsonify({"state": serialize_iteration_state(state, pack)})
@app.post("/api/game/new")
def new_game() -> Any:
pack = get_selected_pack()
state = initialize_iteration_session(pack)
return jsonify(
{
"message": "New run started.",
"state": serialize_iteration_state(state, pack),
}
)
@app.post("/api/game/turn")
def game_turn() -> Any:
state = current_iteration_state()
pack = get_selected_pack()
if state.get("game_over"):
return jsonify({"error": "This run is finished. Start a new game to play again."}), 400
payload = request.get_json(silent=True) or {}
clue = str(payload.get("clue", "")).strip()
if not clue:
return jsonify({"error": "Enter a clue before submitting."}), 400
board_indices = state["board_indices"]
board_words = words_for_indices(board_indices, pack.words)
board_lookup = {
normalize_word(word): index
for index, word in zip(board_indices, board_words)
}
ranking = RANKER.rank_words(clue, board_words)
ranked_indices = [board_lookup[normalize_word(word)] for word in ranking.ranked_words]
turn = resolve_turn(
state=state,
ranked_indices_most_to_least=ranked_indices,
vocabulary_size=pack.word_count,
)
updated_state = {
**turn.state,
"mode_id": MODE_IDS["iteration"],
"last_latency_ms": ranking.latency_ms,
"last_provider": ranking.provider,
"used_fallback": ranking.used_fallback,
"last_warning": ranking.warning,
"last_clue": clue,
}
updated_state = _persist_completed_run_if_needed(
updated_state,
mode_id=MODE_IDS["iteration"],
pack=pack,
)
_commit_session_state(pack, MODE_IDS["iteration"], updated_state)
return jsonify(
{
"message": _build_turn_message(
turn.resolution,
len(turn.words_removed_indices),
updated_state,
pack.word_count,
),
"resolution": turn.resolution,
"ranked_board": words_for_indices(turn.ranked_board_indices, pack.words),
"new_board": words_for_indices(turn.new_board_indices, pack.words),
"words_removed": words_for_indices(turn.words_removed_indices, pack.words),
"spawned_words": words_for_indices(turn.spawned_indices, pack.words),
"target_word_before": _current_target_word(state, pack),
"state": serialize_iteration_state(updated_state, pack),
}
)
@app.get("/api/restriction/state")
def restriction_state() -> Any:
state = current_restriction_state()
pack = get_selected_pack()
return jsonify({"state": serialize_restriction_state(state, pack)})
@app.post("/api/restriction/new")
def new_restriction_game() -> Any:
pack = get_selected_pack()
state = initialize_restriction_session(pack)
return jsonify(
{
"message": "New restriction run started.",
"state": serialize_restriction_state(state, pack),
}
)
def _active_rule_from_state(state: dict[str, Any]) -> RestrictionRule:
rule_id = str(state.get("active_rule_id", "")).strip()
rule = RESTRICTION_RULES_BY_ID.get(rule_id)
if rule is None:
raise ValueError(f"Unknown restriction rule id: {rule_id}")
return rule
@app.post("/api/restriction/turn")
def restriction_turn() -> Any:
state = current_restriction_state()
pack = get_selected_pack()
if state.get("game_over"):
return jsonify({"error": "This run is finished. Start a new game to play again."}), 400
payload = request.get_json(silent=True) or {}
clue = str(payload.get("clue", "")).strip()
if not clue:
return jsonify({"error": "Enter a clue before submitting."}), 400
rule = _active_rule_from_state(state)
board_indices = state["board_indices"]
board_words = words_for_indices(board_indices, pack.words)
board_lookup = {
normalize_word(word): index
for index, word in zip(board_indices, board_words)
}
target_word_before = _current_target_word(state, pack)
if local_rule_supported(rule):
rule_passed, rule_reason = validate_clue_locally(rule, clue)
if rule_passed:
ranking = RANKER.rank_words(clue, board_words)
ranked_indices = [board_lookup[normalize_word(word)] for word in ranking.ranked_words]
turn = resolve_restriction_turn(
state=state,
rule=rule,
rule_passed=True,
rule_reason=rule_reason,
ranked_indices_most_to_least=ranked_indices,
vocabulary_size=pack.word_count,
allow_bonus=True,
rules=RESTRICTION_RULES,
)
updated_state = {
**turn.state,
"last_latency_ms": ranking.latency_ms,
"last_provider": ranking.provider,
"used_fallback": ranking.used_fallback,
"last_warning": ranking.warning,
"last_clue": clue,
}
else:
turn = resolve_restriction_turn(
state=state,
rule=rule,
rule_passed=False,
rule_reason=rule_reason,
ranked_indices_most_to_least=None,
vocabulary_size=pack.word_count,
allow_bonus=False,
rules=RESTRICTION_RULES,
)
updated_state = {
**turn.state,
"last_latency_ms": 0,
"last_provider": "local-rule-validator",
"used_fallback": False,
"last_warning": None,
"last_clue": clue,
}
else:
judgment = RANKER.judge_restricted_clue(rule.description, clue, board_words)
ranked_indices = None
if judgment.ranked_words is not None:
ranked_indices = [board_lookup[normalize_word(word)] for word in judgment.ranked_words]
turn = resolve_restriction_turn(
state=state,
rule=rule,
rule_passed=judgment.rule_passed,
rule_reason=judgment.short_reason,
ranked_indices_most_to_least=ranked_indices,
vocabulary_size=pack.word_count,
allow_bonus=judgment.rule_passed and not judgment.used_fallback,
rules=RESTRICTION_RULES,
)
updated_state = {
**turn.state,
"last_latency_ms": judgment.latency_ms,
"last_provider": judgment.provider,
"used_fallback": judgment.used_fallback,
"last_warning": judgment.warning,
"last_clue": clue,
}
updated_state = _persist_completed_run_if_needed(
updated_state,
mode_id=MODE_IDS["restriction"],
pack=pack,
)
_commit_session_state(pack, MODE_IDS["restriction"], updated_state)
return jsonify(
{
"message": _build_restriction_turn_message(turn, updated_state, pack.word_count),
"resolution": turn.resolution,
"rule_passed": bool(updated_state.get("last_rule_passed")),
"rule_reason": updated_state.get("last_rule_reason"),
"strike_delta": updated_state.get("strike_count", 0) - state.get("strike_count", 0),
"bonus_multiplier_applied": turn.bonus_multiplier_applied,
"ranked_board": (
words_for_indices(turn.ranked_board_indices, pack.words)
if turn.ranked_board_indices is not None
else None
),
"new_board": words_for_indices(turn.new_board_indices, pack.words),
"words_removed": words_for_indices(turn.words_removed_indices, pack.words),
"spawned_words": words_for_indices(turn.spawned_indices, pack.words),
"penalty_words": words_for_indices(turn.penalty_indices, pack.words),
"target_word_before": target_word_before,
"state": serialize_restriction_state(updated_state, pack),
}
)