-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstage_processor_localized.py
More file actions
3550 lines (3133 loc) · 163 KB
/
Copy pathstage_processor_localized.py
File metadata and controls
3550 lines (3133 loc) · 163 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
# stage_processor_localized.py
import json
import random
import re
import copy
from typing import Dict, List, Optional, Any, Tuple
from models import Character
import time
from localization import loc
class UniversalParser:
FUNC_CALL_PATTERN = re.compile(r'(?P<func>\w+)\s*\(\s*(?P<args>[^)]*?)\s*\)', re.DOTALL | re.IGNORECASE)
JSON_PATTERN = re.compile(r'\{[^{}]*\}')
@classmethod
def parse(cls, text: str) -> List[Tuple[str, Any]]:
if not text:
return []
results = []
for match in cls.FUNC_CALL_PATTERN.finditer(text):
func_name = match.group('func').strip()
args_str = match.group('args').strip()
args = cls._parse_arguments(args_str)
if args is not None:
results.append((func_name, args))
if not results:
for json_match in cls.JSON_PATTERN.finditer(text):
try:
obj = json.loads(json_match.group())
if 'name' in obj and 'arguments' in obj:
results.append((obj['name'], obj['arguments']))
except:
continue
return results
@classmethod
def _parse_arguments(cls, args_str: str) -> Optional[Any]:
args_str = args_str.strip()
if not args_str:
return None
if args_str.startswith('{') and args_str.endswith('}'):
try:
return json.loads(args_str)
except:
pass
if args_str.startswith('[') and args_str.endswith(']'):
try:
inner = args_str[1:-1].strip()
if not inner:
return []
items = []
for item in cls._split_args_preserve_brackets(inner, sep=','):
item = item.strip()
if item.startswith("'") and item.endswith("'"):
items.append(item[1:-1])
elif item.startswith('"') and item.endswith('"'):
items.append(item[1:-1])
elif item.isdigit():
items.append(int(item))
elif item in ('true', 'True'):
items.append(True)
elif item in ('false', 'False'):
items.append(False)
else:
items.append(item)
return items
except:
pass
parts = cls._split_args_preserve_brackets(args_str, sep=',')
if len(parts) > 1 and not any('=' in p for p in parts):
result = []
for p in parts:
p = p.strip()
if p.startswith("'") and p.endswith("'"):
result.append(p[1:-1])
elif p.startswith('"') and p.endswith('"'):
result.append(p[1:-1])
elif p.isdigit():
result.append(int(p))
elif p in ('true', 'True'):
result.append(True)
elif p in ('false', 'False'):
result.append(False)
else:
result.append(p)
return result
result = {}
for part in parts:
if '=' not in part:
continue
key, value_str = part.split('=', 1)
key = key.strip()
value_str = value_str.strip()
if value_str.startswith("'") and value_str.endswith("'"):
value = value_str[1:-1]
elif value_str.startswith('"') and value_str.endswith('"'):
value = value_str[1:-1]
elif value_str.isdigit():
value = int(value_str)
elif value_str in ('true', 'True'):
value = True
elif value_str in ('false', 'False'):
value = False
elif value_str.startswith('[') and value_str.endswith(']'):
inner = value_str[1:-1].strip()
if inner:
value = [cls._parse_single_value(x.strip()) for x in cls._split_args_preserve_brackets(inner, sep=',')]
else:
value = []
else:
value = value_str
result[key] = value
return result if result else None
@staticmethod
def _split_args_preserve_brackets(text: str, sep=',') -> List[str]:
parts = []
current = []
bracket_level = 0
in_quote = False
quote_char = None
for ch in text:
if ch in ('"', "'") and not in_quote:
in_quote = True
quote_char = ch
elif ch == quote_char and in_quote:
in_quote = False
quote_char = None
elif not in_quote and ch in '([{':
bracket_level += 1
elif not in_quote and ch in ')]}':
bracket_level -= 1
if not in_quote and bracket_level == 0 and ch == sep:
parts.append(''.join(current).strip())
current = []
else:
current.append(ch)
if current:
parts.append(''.join(current).strip())
return parts
@staticmethod
def _parse_single_value(s: str) -> Any:
s = s.strip()
if s.startswith("'") and s.endswith("'"):
return s[1:-1]
if s.startswith('"') and s.endswith('"'):
return s[1:-1]
if s.isdigit():
return int(s)
if s in ('true', 'True'):
return True
if s in ('false', 'False'):
return False
return s
class StageProcessor:
ALL_STAGES = [
"stage1_request_descriptions",
"stage1_create_scene",
"stage1_truth_check",
"stage1_player_action",
"stage1_random_event_determine",
"stage1_random_event_request_objects",
"stage1_random_event_details",
"stage2_npc_action",
"stage3_final",
"stage8_history_check",
"stage11_validation",
"stage12_emotions",
"stage13_auto_character_creator",
"stage11_significant_changes",
"stage4_summary",
"stage10_associative_memory"
]
def __init__(self, main_app):
self.main_app = main_app
self.generation_start_time = None
self.stage = None
self.last_changed_objects = []
self.stage_data = {
"user_message": "",
"original_user_message": "",
"descriptions": {},
"scene_location_id": None,
"scene_character_ids": [],
"scene_item_ids": [],
"scene_scenario_ids": [],
"scene_event_ids": [],
"scene_summary": "",
"scene_narrative": "",
"player_action_dice": None,
"player_action_desc": "",
"event_occurrence_dice": None,
"event_quality_dice": None,
"event_occurred": False,
"event_desc": "",
"event_additional_ids": [],
"npc_actions": {},
"current_npc_index": 0,
"final_response": "",
"truth_violation": "",
"emotion_map": {},
"scene_generation_retries": 0,
"random_event_retries": 0,
"npc_retry_count": 0
}
self.stage_retries = {}
self.dice_queue_d20 = []
self.dice_queue_d100 = []
self._refill_dice_queues()
self.history_check_state = {}
self.original_final_response = ""
self.history_check_iteration_count = 0
self.HISTORY_CHECK_MAX_ITERATIONS = 50
self.debug_mode = False
self.pending_step = False
self.pending_callback = None
self.pending_callback_extra = None
self.pending_stage_name = None
self.pending_debug_inputs = None
self.pending_state_snapshot = None
self.step_history = []
self.current_step_index = -1
self.history_check_queue = []
self.history_check_index = 0
self.history_check_corrected = None
self.history_check_total_pairs = 0
self._validate_prompts()
def _refill_dice_queues(self):
self.dice_queue_d20 = [random.randint(1, 20) for _ in range(5)]
self.dice_queue_d100 = [random.randint(1, 100) for _ in range(5)]
def _pop_dice(self, dice_type: str) -> int:
if dice_type == 'd20':
if not self.dice_queue_d20:
self.dice_queue_d20 = [random.randint(1, 20) for _ in range(5)]
return self.dice_queue_d20.pop(0)
elif dice_type == 'd100':
if not self.dice_queue_d100:
self.dice_queue_d100 = [random.randint(1, 100) for _ in range(5)]
return self.dice_queue_d100.pop(0)
else:
return random.randint(1, 20)
def _get_retry_limit(self, stage_name: str) -> int:
return self.main_app.stage_retry_limits.get(stage_name, 2)
def abort(self):
if not self.main_app.is_generating:
return
self.main_app.stop_generation_flag = True
if self.pending_step:
self.pending_step = False
self.pending_callback = None
self.pending_callback_extra = None
self.pending_stage_name = None
self.pending_debug_inputs = None
self.pending_state_snapshot = None
self.main_app.center_panel.set_step_button_state(False)
self.main_app.is_generating = False
self.main_app.center_panel.set_input_state("normal")
self.main_app.center_panel.update_translation_button_state()
self.main_app.current_debug_log_path = None
self._display_system(loc.tr("messages_aborted"))
if hasattr(self.main_app, 'vn_frame') and self.main_app.vn_frame and self.main_app.vn_frame.winfo_viewable():
self.main_app.vn_frame.set_freeze(False)
def reset(self):
self.main_app.stop_generation_flag = False
if self.pending_step:
self.pending_step = False
self.pending_callback = None
self.pending_callback_extra = None
self.pending_stage_name = None
self.pending_debug_inputs = None
self.pending_state_snapshot = None
self.main_app.center_panel.set_step_button_state(False)
def _validate_prompts(self):
required_prompts = [
"stage1_request_descriptions",
"stage1_create_scene",
"stage1_truth_check",
"stage1_player_action",
"stage1_random_event",
"stage1_random_event_continue",
"stage1_random_event_request_objects",
"stage1_turn_order",
"stage1_validate_scene",
"stage1_validate_random_event",
"stage2_npc_action",
"stage3_final",
"stage4_summary",
"stage8_history_check",
"stage10_associative_memory",
"stage11_validation",
"stage11_significant_changes",
"stage12_emotions",
"stage13_auto_character_creator",
"compress_description",
"dice_rules",
"translator_system"
]
for prompt_name in required_prompts:
content = self.main_app.prompt_manager.get_prompt_content(prompt_name)
if content is None or content.strip() == "":
raise FileNotFoundError(f"Required prompt file '{prompt_name}.json' not found or empty.")
def set_debug_mode(self, enabled: bool):
self.debug_mode = enabled
if not enabled:
self.pending_step = False
self.pending_callback = None
self.pending_callback_extra = None
self.pending_stage_name = None
self.pending_debug_inputs = None
self.pending_state_snapshot = None
self.main_app.center_panel.set_step_button_state(False)
def step_continue(self):
if self.pending_step and self.pending_callback:
if self.pending_state_snapshot:
self._print_debug_section("Текущее состояние перед отправкой запроса", self.pending_state_snapshot, blank_lines_before=1, blank_lines_after=1)
if self.pending_debug_inputs and self.pending_stage_name:
self._print_debug_section(f"Входные данные для этапа {self.pending_stage_name}", self.pending_debug_inputs, blank_lines_before=0, blank_lines_after=1)
cb = self.pending_callback
extra = self.pending_callback_extra
self.pending_step = False
self.pending_callback = None
self.pending_callback_extra = None
self.pending_stage_name = None
self.pending_debug_inputs = None
self.pending_state_snapshot = None
self.main_app.center_panel.set_step_button_state(False)
cb(extra)
def _wait_for_step(self, callback, extra=None, stage_name=None, debug_inputs=None, state_snapshot=None):
if not self.debug_mode:
callback(extra)
return
if self.main_app.stop_generation_flag:
self._display_system(loc.tr("messages_aborted"))
return
self.pending_debug_inputs = debug_inputs
self.pending_state_snapshot = state_snapshot
self.pending_step = True
self.pending_callback = callback
self.pending_callback_extra = extra
self.pending_stage_name = stage_name
self.main_app.center_panel.set_step_button_state(True)
def _print_debug_section(self, title: str, items: Dict[str, Any], blank_lines_before: int = 2, blank_lines_after: int = 1):
if not self.debug_mode:
return
output_lines = []
for _ in range(blank_lines_before):
output_lines.append("")
output_lines.append(f"=== {title} ===")
for key, value in items.items():
value_str = str(value)
if len(value_str) > 500:
value_str = value_str[:500] + "..."
output_lines.append(f">>> {key}: {value_str}")
for _ in range(blank_lines_after):
output_lines.append("")
self.main_app.center_panel.display_message("\n".join(output_lines), "system")
def _get_state_snapshot(self):
snapshot = {}
for key, value in self.stage_data.items():
if value is None:
continue
if isinstance(value, (str, list, dict)):
if not value:
continue
if isinstance(value, str) and len(value) > 300:
snapshot[key] = value[:300] + "..."
else:
snapshot[key] = value
snapshot["dice_queue_d20"] = self.dice_queue_d20.copy()
snapshot["dice_queue_d100"] = self.dice_queue_d100.copy()
return snapshot
def _save_checkpoint(self, stage_name: str):
if not self.debug_mode:
return
snapshot = {
"stage": stage_name,
"stage_data": copy.deepcopy(self.stage_data),
"dice_queue_d20": self.dice_queue_d20.copy(),
"dice_queue_d100": self.dice_queue_d100.copy(),
}
if self.current_step_index < len(self.step_history) - 1:
self.step_history = self.step_history[:self.current_step_index + 1]
self.step_history.append(snapshot)
self.current_step_index += 1
def regenerate_last_step(self):
if not self.debug_mode:
self._display_system(loc.tr("error_debug_mode_off"))
return False
if self.current_step_index <= 0:
self._display_system(loc.tr("error_no_previous_step"))
return False
self.step_history.pop()
self.current_step_index -= 1
prev = self.step_history[self.current_step_index]
self.stage_data = copy.deepcopy(prev["stage_data"])
self.dice_queue_d20 = prev["dice_queue_d20"].copy()
self.dice_queue_d100 = prev["dice_queue_d100"].copy()
stage_to_rerun = prev["stage"]
self.pending_step = False
self.pending_callback = None
self.pending_callback_extra = None
self.pending_stage_name = None
self.pending_debug_inputs = None
self.pending_state_snapshot = None
self.main_app.center_panel.set_step_button_state(False)
self.main_app.center_panel.clear_temp_response()
self.main_app.center_panel.display_system_message(loc.tr("info_regeneration_start", stage=stage_to_rerun))
method_name = f"_{stage_to_rerun}"
if hasattr(self, method_name):
getattr(self, method_name)(retry_count=0)
return True
else:
self._display_system(f"❌ Неизвестный этап {stage_to_rerun}\n")
return False
def get_debug_state(self) -> dict:
if not self.debug_mode:
return {}
return {
"debug_mode": True,
"stage_data": copy.deepcopy(self.stage_data),
"dice_queue_d20": self.dice_queue_d20.copy(),
"dice_queue_d100": self.dice_queue_d100.copy(),
"step_history": copy.deepcopy(self.step_history),
"current_step_index": self.current_step_index,
"pending_stage_name": self.pending_stage_name,
"pending_callback_name": self.pending_callback.__name__ if self.pending_callback else None,
"pending_extra": self.pending_callback_extra,
}
def restore_debug_state(self, state: dict):
if not state.get("debug_mode"):
return
self.debug_mode = True
self.stage_data = copy.deepcopy(state["stage_data"])
self.dice_queue_d20 = state["dice_queue_d20"].copy()
self.dice_queue_d100 = state["dice_queue_d100"].copy()
self.step_history = copy.deepcopy(state["step_history"])
self.current_step_index = state["current_step_index"]
self.pending_stage_name = state.get("pending_stage_name")
self.pending_step = False
self.pending_callback = None
self.pending_callback_extra = None
self.pending_debug_inputs = None
self.pending_state_snapshot = None
self.main_app.center_panel.set_step_button_state(False)
self.main_app.center_panel.display_system_message(loc.tr("info_restored_debug"))
def _safe_format(self, template: str, **kwargs) -> str:
import re
def replacer(match):
key = match.group(1)
return str(kwargs.get(key, match.group(0)))
pattern = re.compile(r'\{([a-zA-Z_][a-zA-Z0-9_]*)\}')
return pattern.sub(replacer, template)
def _log_debug(self, step: str, content: str = "", error: str = None):
if self.main_app.current_debug_log_path:
self.main_app._log_debug(step, content, error)
def _log_full_response(self, stage: str, content: str):
self._log_debug(f"FULL_RESPONSE_{stage}", f"Content:\n{content}")
preview = content[:500] + '...' if len(content) > 500 else content
self._display_thinking(loc.tr("messages_thinking_prefix", stage=stage, preview=preview))
def _display_thinking(self, msg: str):
if hasattr(self.main_app, 'thinking_panel') and self.main_app.thinking_panel:
self.main_app.thinking_panel.append_text(msg + "\n")
else:
self._display_system(f"[THINK] {msg}")
def _get_object_by_id(self, obj_id: str):
return self.main_app._get_object_by_id(obj_id)
def _get_object_description_with_local(self, obj_id: str) -> str:
return self.main_app.get_description_for_model(obj_id)
def _get_latest_associations_for_objects(self, object_ids: List[str]) -> str:
if not object_ids:
return ""
history = self.main_app.conversation_history
if not history:
return ""
latest = {oid: None for oid in object_ids}
for msg in reversed(history):
if msg["role"] != "assistant":
continue
associations = msg.get("associations", {})
if not associations:
continue
for oid in object_ids:
if latest[oid] is None and oid in associations:
latest[oid] = associations[oid]
if all(v is not None for v in latest.values()):
break
lines = []
for oid, assoc in latest.items():
if assoc:
name = self._get_obj_name(oid)
lines.append(f"{name} (ID: {oid}): {assoc}")
return "\n".join(lines) if lines else ""
def _update_last_assistant_associations(self, changes: List[Tuple[str, str]]):
history = self.main_app.conversation_history
if not history:
return
for i in range(len(history)-1, -1, -1):
if history[i]["role"] == "assistant":
if "associations" not in history[i]:
history[i]["associations"] = {}
obj_updates = {}
for obj_id, change_desc in changes:
if obj_id not in obj_updates:
obj_updates[obj_id] = []
obj_updates[obj_id].append(change_desc)
for obj_id, new_lines in obj_updates.items():
existing = history[i]["associations"].get(obj_id, "")
existing_lines = [line.strip() for line in existing.split('\n') if line.strip()]
for new_line in new_lines:
if '->' in new_line:
category = new_line.split('->')[0].strip()
else:
category = None
found = False
if category:
for idx, line in enumerate(existing_lines):
if line.startswith(category + ' ->'):
existing_lines[idx] = new_line
found = True
break
if not found:
existing_lines.append(new_line)
history[i]["associations"][obj_id] = "\n".join(existing_lines)
break
def _fetch_descriptions_sync(self, obj_ids: List[str]):
for obj_id in obj_ids:
obj_id = str(obj_id)
self._display_system(loc.tr("messages_fetching_desc", obj_id=obj_id))
try:
# Получаем базовое описание (включая глобальное и локальное)
base_desc = self._get_object_description_with_local(obj_id)
# Добавляем краткое описание, если оно есть
obj = self._get_object_by_id(obj_id)
if obj and hasattr(obj, 'short_description') and obj.short_description:
short = obj.short_description.strip()
if short:
base_desc = f"Кратко: {short}\nПолное описание: {base_desc}"
desc = base_desc
if obj and hasattr(obj, 'is_player') and obj.is_player:
if "(ИГРОК)" not in desc:
desc += " (ИГРОК)"
self.stage_data["descriptions"][obj_id] = desc
self._display_system(loc.tr("messages_fetch_desc_ok", obj_id=obj_id))
except Exception as e:
self._display_error(loc.tr("messages_fetch_desc_error", obj_id=obj_id, error=str(e)))
self.stage_data["descriptions"][obj_id] = f"Ошибка: {e}"
self._display_system(loc.tr("messages_all_descs_ok"))
def _get_formatted_history(self) -> str:
history = self.main_app.conversation_history
if not history:
return "Нет предыдущих сообщений."
lines = []
for msg in history:
role = "Пользователь" if msg["role"] == "user" else "Ассистент"
lines.append(f"{role}: {msg['content']}")
return "\n".join(lines)
def _stage1_request_descriptions(self, retry_count=0):
if not self.main_app.enabled_stages.get("stage1_request_descriptions", True):
self._log_debug("STAGE1_SKIPPED", "Stage1 disabled")
self._stage1_create_scene()
return
self._log_debug(f"=== STAGE1.1: request_descriptions (attempt {retry_count+1}) ===")
self._display_system(loc.tr("messages_stage1_1", attempt=retry_count+1))
if retry_count > 0:
self.stage_data["descriptions"] = {}
objects_text = []
for lid in self.main_app.current_profile.enabled_locations:
loc_obj = self.main_app.locations.get(lid)
if loc_obj:
assoc = self._get_latest_associations_for_objects([lid])
assoc_str = f" ({assoc})" if assoc else ""
short = loc_obj.short_description.strip() if loc_obj.short_description else ""
short_str = f" [{short}]" if short else ""
objects_text.append(f"Локация: {lid} - {loc_obj.name}{short_str}{assoc_str}")
for cid in self.main_app.current_profile.enabled_characters:
char = self.main_app.characters.get(cid)
if char:
assoc = self._get_latest_associations_for_objects([cid])
assoc_str = f" ({assoc})" if assoc else ""
is_player = char.is_player
player_tag = ' (ИГРОК)' if is_player else ''
short = char.short_description.strip() if char.short_description else ""
short_str = f" [{short}]" if short else ""
objects_text.append(f"Персонаж: {cid} - {char.name}{short_str}{player_tag}{assoc_str}")
for iid in self.main_app.current_profile.enabled_items:
item = self.main_app.items.get(iid)
if item:
assoc = self._get_latest_associations_for_objects([iid])
assoc_str = f" ({assoc})" if assoc else ""
short = item.short_description.strip() if item.short_description else ""
short_str = f" [{short}]" if short else ""
objects_text.append(f"Предмет: {iid} - {item.name}{short_str}{assoc_str}")
for sid in self.main_app.current_profile.enabled_scenarios:
scen = self.main_app.scenarios.get(sid)
if scen:
short = scen.short_description.strip() if scen.short_description else ""
short_str = f" [{short}]" if short else ""
objects_text.append(f"Сценарий: {sid} - {scen.name}{short_str} (описание: {scen.description[:100]}...)")
for eid in self.main_app.current_profile.enabled_emotions:
em = self.main_app.emotions.get(eid)
if em:
short = em.short_description.strip() if em.short_description else ""
short_str = f" [{short}]" if short else ""
objects_text.append(f"Эмоция: {eid} - {em.name}{short_str}")
for evid in self.main_app.current_profile.enabled_events:
ev = self.main_app.events.get(evid)
if ev:
short = ev.short_description.strip() if ev.short_description else ""
short_str = f" [{short}]" if short else ""
objects_text.append(f"Событие: {evid} - {ev.name}{short_str} (описание: {ev.description[:100]}...)")
available = "\n".join(objects_text) if objects_text else "Нет доступных объектов."
max_locs = self.main_app.max_locations_per_scene
max_chars = self.main_app.max_characters_per_scene
max_items = self.main_app.max_items_per_scene
max_scenarios = self.main_app.max_scenarios_per_scene
max_events = self.main_app.max_events_per_scene
prompt_template = self.main_app.prompt_manager.get_prompt_content("stage1_request_descriptions")
if not prompt_template:
raise FileNotFoundError("Prompt 'stage1_request_descriptions' not found.")
user_data = self._safe_format(
prompt_template,
user_message=self.stage_data['user_message'],
available_objects=available,
max_locations=max_locs,
max_characters=max_chars,
max_items=max_items,
max_scenarios=max_scenarios,
max_events=max_events
)
extra_context = {
"available_objects": available,
"max_locations": max_locs,
"max_characters": max_chars,
"max_items": max_items,
"max_scenarios": max_scenarios,
"max_events": max_events,
"user_message": self.stage_data['user_message']
}
full_context = {**self.stage_data, **extra_context}
debug_inputs = {
"available_objects": available,
"max_locations": max_locs,
"max_characters": max_chars,
"max_items": max_items,
"max_scenarios": max_scenarios,
"max_events": max_events,
"user_message": self.stage_data['user_message']
}
self._send_request(
user_data=user_data,
callback=lambda content, extra: self._after_stage1_request_descriptions(content, extra),
extra={"retry_count": retry_count},
stage_name="stage1_request_descriptions",
show_in_thinking=True,
context_data=full_context,
debug_inputs=debug_inputs
)
def _after_stage1_request_descriptions(self, content, extra):
retry_count = extra.get("retry_count", 0)
self._log_full_response("stage1_request_descriptions", content)
tool_calls = self._try_parse_tool_calls_from_text(content, expected_func_names=["send_object_info"])
if len(tool_calls) > 1:
self._log_debug("WARNING", f"Найдено несколько вызовов send_object_info ({len(tool_calls)}), беру последний")
send_call = tool_calls[-1] if tool_calls else None
object_ids = None
if send_call:
try:
args = json.loads(send_call["function"]["arguments"])
if isinstance(args, list):
object_ids = args
elif "object_ids" in args:
object_ids = args["object_ids"]
elif "ids" in args:
object_ids = args["ids"]
elif len(args) == 1 and isinstance(list(args.values())[0], list):
object_ids = list(args.values())[0]
except Exception as e:
self._log_debug("ERROR", f"send_object_info parse error: {e}")
if object_ids is not None and isinstance(object_ids, list) and object_ids:
# Фильтруем только существующие ID
valid_ids = []
for oid in object_ids:
oid_str = str(oid)
if self._object_exists(oid_str):
valid_ids.append(oid_str)
else:
self._display_system(f"⚠️ Игнорирую несуществующий ID: {oid_str}")
if valid_ids:
objects_display = []
for oid in valid_ids:
obj = self.main_app._get_object_by_id(oid)
name = obj.name if obj else oid
objects_display.append(f"{oid} ({name})")
display_str = ", ".join(objects_display)
self._display_system(loc.tr("messages_request_objects", objects=display_str))
self._fetch_descriptions_sync(valid_ids)
if self.debug_mode:
output_items = {
"object_ids": valid_ids,
"descriptions": self.stage_data["descriptions"]
}
self._print_debug_section("Выходные данные этапа stage1_request_descriptions", output_items, blank_lines_before=1, blank_lines_after=1)
self._stage1_create_scene()
self._save_checkpoint("stage1_request_descriptions")
return
else:
self._display_error("⚠️ Нет валидных ID. Создаю сцену по умолчанию.\n")
self._create_default_scene()
self._save_checkpoint("stage1_request_descriptions")
return
else:
self._display_error("⚠️ send_object_info вызван без корректного списка object_ids.\n")
limit = self._get_retry_limit("stage1_request_descriptions")
if retry_count < limit:
self._display_error(loc.tr("messages_stage_retry", func="send_object_info", attempt=retry_count+1, limit=limit))
self._stage1_request_descriptions(retry_count+1)
else:
self._display_system(loc.tr("info_auto_scene"))
self._create_default_scene()
self._save_checkpoint("stage1_request_descriptions")
def _create_default_scene(self):
location_id = None
if self.main_app.current_profile.enabled_locations:
location_id = self.main_app.current_profile.enabled_locations[0]
player_id = None
for cid in self.main_app.current_profile.enabled_characters:
char = self.main_app.characters.get(cid)
if char and char.is_player:
player_id = cid
break
character_ids = []
for cid in self.main_app.current_profile.enabled_characters:
if cid != player_id:
character_ids.append(cid)
if player_id:
character_ids.insert(0, player_id)
item_ids = self.main_app.current_profile.enabled_items[:3]
scenario_ids = self.main_app.current_profile.enabled_scenarios[:self.main_app.max_scenarios_per_scene]
max_events = getattr(self.main_app, 'max_events_per_scene', 10)
event_ids = self.main_app.current_profile.enabled_events[:max_events]
location_id = str(location_id) if location_id else None
character_ids = [str(cid) for cid in character_ids]
item_ids = [str(iid) for iid in item_ids]
scenario_ids = [str(sid) for sid in scenario_ids]
event_ids = [str(eid) for eid in event_ids]
self.stage_data["scene_location_id"] = location_id
self.stage_data["scene_character_ids"] = character_ids
self.stage_data["scene_item_ids"] = item_ids
self.stage_data["scene_scenario_ids"] = scenario_ids
self.stage_data["scene_event_ids"] = event_ids
all_ids = []
if location_id:
all_ids.append(location_id)
all_ids.extend(character_ids)
all_ids.extend(item_ids)
all_ids.extend(scenario_ids)
all_ids.extend(event_ids)
scene_parts = []
if location_id:
loc_obj = self.main_app.locations.get(location_id)
loc_name = loc_obj.name if loc_obj else location_id
scene_parts.append(f"Локация: {loc_name} (ID: {location_id})")
if character_ids:
char_names = []
for cid in character_ids:
char = self.main_app.characters.get(cid)
char_names.append(f"{char.name} (ID: {cid})" if char else cid)
scene_parts.append(f"Персонажи: {', '.join(char_names)}")
if item_ids:
item_names = []
for iid in item_ids:
item = self.main_app.items.get(iid)
item_names.append(f"{item.name} (ID: {iid})" if item else iid)
scene_parts.append(f"Предметы: {', '.join(item_names)}")
if scenario_ids:
scen_names = []
for sid in scenario_ids:
scen = self.main_app.scenarios.get(sid)
scen_names.append(f"{scen.name} (ID: {sid})" if scen else sid)
scene_parts.append(f"Сценарии: {', '.join(scen_names)}")
if event_ids:
event_names = []
for eid in event_ids:
ev = self.main_app.events.get(eid)
event_names.append(f"{ev.name} (ID: {eid})" if ev else eid)
scene_parts.append(f"События: {', '.join(event_names)}")
summary = "\n".join(scene_parts)
self.stage_data["scene_summary"] = summary
self._display_system(loc.tr("messages_auto_scene_created", summary=summary))
if all_ids:
self._fetch_descriptions_sync(all_ids)
self._stage1_truth_check()
def _stage1_create_scene(self, retry_count=0):
if not self.main_app.enabled_stages.get("stage1_create_scene", True):
self._log_debug("STAGE1_CREATE_SCENE_SKIPPED", "Stage1_create_scene disabled")
self._stage1_truth_check()
return
self._log_debug(f"=== STAGE1.2: create_scene (attempt {retry_count+1}) ===")
self._display_system(loc.tr("messages_stage1_2", attempt=retry_count+1))
descriptions_text = "\n".join([f"{oid}: {desc}" for oid, desc in self.stage_data["descriptions"].items() if isinstance(desc, str)])
prompt_template = self.main_app.prompt_manager.get_prompt_content("stage1_create_scene")
if not prompt_template:
raise FileNotFoundError("Prompt 'stage1_create_scene' not found.")
user_data = self._safe_format(
prompt_template,
user_message=self.stage_data['user_message'],
descriptions=descriptions_text
)
extra_context = {
"descriptions": descriptions_text,
"user_message": self.stage_data['user_message']
}
full_context = {**self.stage_data, **extra_context}
debug_inputs = {
"user_message": self.stage_data['user_message'],
"descriptions": descriptions_text
}
self._send_request(
user_data=user_data,
callback=lambda content, extra: self._after_stage1_create_scene(content, extra),
extra={"retry_count": retry_count},
stage_name="stage1_create_scene",
show_in_thinking=True,
context_data=full_context,
debug_inputs=debug_inputs
)
def _after_stage1_create_scene(self, content, extra):
retry_count = extra.get("retry_count", 0)
self._log_full_response("stage1_create_scene", content)
scene_narrative = ""
if content and "confirm_scene(" in content:
parts = content.split("confirm_scene(", 1)
scene_narrative = parts[0].strip()
if scene_narrative:
self.stage_data["scene_narrative"] = scene_narrative
self._display_system(f"🎬 Описание сцены:\n{scene_narrative}\n")
else:
self._display_system("⚠️ Модель не предоставила текстового описания сцены.\n")
tool_calls = self._try_parse_tool_calls_from_text(content, expected_func_names=["confirm_scene"])
if len(tool_calls) > 1:
self._log_debug("WARNING", f"Найдено несколько вызовов confirm_scene ({len(tool_calls)}), беру последний")
confirm_call = tool_calls[-1] if tool_calls else None
if confirm_call:
try:
args = json.loads(confirm_call["function"]["arguments"])
if isinstance(args, list):
self._handle_confirm_scene(args)
if self.debug_mode:
output_items = {
"scene_location_id": self.stage_data["scene_location_id"],
"scene_character_ids": self.stage_data["scene_character_ids"],
"scene_item_ids": self.stage_data["scene_item_ids"],
"scene_scenario_ids": self.stage_data["scene_scenario_ids"],
"scene_narrative": self.stage_data.get("scene_narrative", "")
}
self._print_debug_section("Выходные данные этапа stage1_create_scene", output_items, blank_lines_before=1, blank_lines_after=1)
self._save_checkpoint("stage1_create_scene")
return
except Exception as e:
self._log_debug("ERROR", f"confirm_scene parse error: {e}")
match = re.search(r'\[(l\d+(?:\s*,\s*(?:c\d+|i\d+|s\d+))*)\]', content)
if match:
ids_str = match.group(1)
ids = [id.strip() for id in ids_str.split(',')]
self._display_system("⚠️ Модель не вызвала confirm_scene, но указала ID. Использую их.\n")
self._handle_confirm_scene(ids)
if self.debug_mode:
output_items = {
"scene_location_id": self.stage_data["scene_location_id"],
"scene_character_ids": self.stage_data["scene_character_ids"],
"scene_item_ids": self.stage_data["scene_item_ids"],
"scene_scenario_ids": self.stage_data["scene_scenario_ids"],
"scene_narrative": self.stage_data.get("scene_narrative", "")
}
self._print_debug_section("Выходные данные этапа stage1_create_scene", output_items, blank_lines_before=1, blank_lines_after=1)
self._save_checkpoint("stage1_create_scene")
return
limit = self._get_retry_limit("stage1_create_scene")
if retry_count < limit:
self._display_error(loc.tr("messages_stage_retry", func="confirm_scene", attempt=retry_count+1, limit=limit))
self._stage1_create_scene(retry_count+1)
else:
self._display_system(loc.tr("info_auto_scene"))
self._create_default_scene()
self._save_checkpoint("stage1_create_scene")
def _handle_confirm_scene(self, obj_ids: list):
# Фильтруем только существующие ID
valid_ids = []
for obj_id in obj_ids:
obj_id = str(obj_id)
if self._object_exists(obj_id):
valid_ids.append(obj_id)
else:
self._display_system(f"⚠️ Игнорирую несуществующий ID: {obj_id}")
location_id = None
character_ids = []
item_ids = []
scenario_ids = []
event_ids = []
for obj_id in valid_ids:
if obj_id.startswith('l'):
if location_id is None:
location_id = obj_id
elif obj_id.startswith('c'):
character_ids.append(obj_id)
elif obj_id.startswith('i'):
item_ids.append(obj_id)
elif obj_id.startswith('s'):
scenario_ids.append(obj_id)
elif obj_id.startswith('e'):
event_ids.append(obj_id)
if location_id is None and self.main_app.current_profile.enabled_locations:
location_id = self.main_app.current_profile.enabled_locations[0]
self._display_system(f"⚠️ Локация не указана, беру '{location_id}' по умолчанию.\n")
player_id = None
for cid in self.main_app.current_profile.enabled_characters:
char = self.main_app.characters.get(cid)
if char and char.is_player:
player_id = cid
break
if player_id and player_id not in character_ids:
character_ids.insert(0, player_id)
self._display_system(loc.tr("messages_player_added", player_id=player_id))