-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
2897 lines (2353 loc) · 131 KB
/
Copy pathmain.py
File metadata and controls
2897 lines (2353 loc) · 131 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import argparse
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
from utils.llm_client import create_client
from pipeline.project_outline_processor import ProjectOutlineProcessor
from pipeline.event_processor import EventProcessor
from pipeline.summary_processor import SummaryProcessor
from pipeline.multi_agent_dialogue_processor import MultiAgentDialogueProcessor
from dotenv import load_dotenv
import time
import argparse
import json
from pathlib import Path
from typing import Dict, Any, List, Optional
from tqdm import tqdm
from pypinyin import lazy_pinyin, Style
from datetime import datetime, timedelta
import random
import os
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
base_url = os.getenv('BASE_URL')
# Global variables to store persona and topic data
PERSONA_DATA = None
TOPIC_ATTR_DATA = None
PERSON_GOAL_DATA = None
# Global person-based memory management
# Each person gets their own independent memory space
PERSON_MEMORY_DATA = {} # Format: {person_name: {"memory_points": [], "total_sessions": 0, "last_updated": timestamp}}
# Global person-based ConversationController management
# Each person gets their own ConversationController instance
PERSON_CONVERSATION_CONTROLLERS = {} # Format: {person_name: ConversationController}
def parse_arguments():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description="Project blueprint generator")
parser.add_argument("--names", type=str, default=None,
help="Specify person name to generate dialogue for, e.g.: --names 'Zhang San'")
parser.add_argument("--projects", "-n", type=int, default=3,
help="Number of project blueprints to generate for each person (default: 1)")
# Model parameters
parser.add_argument("--blueprint-model", type=str, default="gemini-2.5-pro",
help="LLM model for project blueprint generation (default: gemini-2.5-pro)")
parser.add_argument("--event-model", type=str, default="gemini-2.5-pro",
help="LLM model for event generation (default: gemini-2.5-pro)")
parser.add_argument("--summary-model", type=str, default="gemini-2.5-pro",
help="LLM model for session summary generation (default: gemini-2.5-pro)")
parser.add_argument("--dialogue-model", type=str, default="gemini-2.5-flash",
help="LLM model for dialogue generation (default: gemini-2.5-flash)")
parser.add_argument("--evaluation-model", type=str, default="gemini-2.5-flash-lite",
help="LLM model for evaluation (default: gemini-2.5-flash-lite)")
parser.add_argument("--memory-model", type=str, default="gemini-2.5-flash",
help="LLM model for memory management (default: gemini-2.5-flash)")
parser.add_argument("--memory-retrieve-model", type=str, default="gemini-2.5-flash",
help="LLM model for memory retrieval (default: gemini-2.5-flash)")
parser.add_argument("--dedup-model", type=str, default="gemini-2.5-flash",
help="LLM model for deduplication (default: gemini-2.5-flash)")
parser.add_argument("--semantic-schedule-model", type=str, default="gemini-2.5-pro",
help="LLM model for semantic schedule processing (default: gpt-4o-mini)")
# Processing parameters
parser.add_argument("--max-turns", type=int, default=24,
help="Maximum dialogue turns (default: 10)")
parser.add_argument("--max-retries", type=int, default=2,
help="Maximum LLM call retry count (default: 2)")
# Output parameters
parser.add_argument("--output", "-o", type=str, default="output",
help="Output directory path (default: output)")
parser.add_argument("--log", action="store_true",
help="Enable verbose logging")
parser.add_argument("--smart-recovery", action="store_true",
help="Enable smart interrupt recovery")
return parser.parse_args()
# Progress check and recovery functions
def validate_blueprint(blueprint_data: Dict[str, Any]) -> bool:
"""Validate blueprint data integrity"""
required_fields = ["_metadata", "project_goal", "project_attributes_schema"]
for field in required_fields:
if field not in blueprint_data:
return False
# Validate metadata integrity
metadata = blueprint_data.get("_metadata", {})
if not metadata.get("person_name") or not metadata.get("total_attributes_used"):
return False
return True
def validate_events(events_data: Dict[str, Any]) -> bool:
"""Validate events data integrity"""
if "events" not in events_data:
return False
events = events_data["events"]
if not isinstance(events, list) or len(events) == 0:
return False
# Validate required fields for each event
for event in events:
if not isinstance(event, dict):
return False
if not event.get("event_name"):
return False
return True
def validate_summaries(summaries_data: Dict[str, Any], events_data: Dict[str, Any] = None) -> bool:
"""Validate session summaries data integrity"""
if "sessions" not in summaries_data:
return False
sessions = summaries_data["sessions"]
if not isinstance(sessions, list) or len(sessions) == 0:
return False
# Validate required fields for each session
for session in sessions:
if not isinstance(session, dict):
return False
if not session.get("session_id") or not session.get("session_summary"):
return False
# If events data provided, check if all events have corresponding session summaries
if events_data:
try:
# fromeventsdataingetalleventID(Translated commentevent_indexandevent_idTranslated commentfieldTranslated comment)
event_ids = set()
if "events" in events_data:
events_list = events_data["events"]
for event in events_list:
if isinstance(event, dict):
# Translated commentuseevent_id,Translated commenthaveTranslated commentuseevent_index
event_id = event.get("event_id") or event.get("event_index")
if event_id:
event_ids.add(event_id)
# fromsummariesdataingetTranslated commenteventID
covered_event_ids = set()
for session in sessions:
if isinstance(session, dict) and session.get("event_id"):
covered_event_ids.add(session["event_id"])
# checkisTranslated commentalleventTranslated commenthaveTranslated commentsession summary
if event_ids != covered_event_ids:
print(f" ⚠️ event: eventID {event_ids} vs {covered_event_ids}")
return False
except Exception as e:
print(f" ⚠️ validationevent: {str(e)}")
return False
return True
def validate_dialogue(dialogue_file: Path) -> bool:
"""Translated docstring"""
try:
with open(dialogue_file, 'r', encoding='utf-8') as f:
dialogue_data = json.load(f)
# checkTranslated commentneedfield
if not dialogue_data.get("session_id"):
return False
# Translated commentdatastructure:Translated commentlayerdialogue_turnsorTranslated commentindialogue_outputin
dialogue_turns = dialogue_data.get("dialogue_turns", [])
# Translated commentlayerTranslated commenthavedialogue_turns,attemptindialogue_outputinTranslated comment
if not dialogue_turns and "dialogue_output" in dialogue_data:
dialogue_output = dialogue_data["dialogue_output"]
dialogue_turns = dialogue_output.get("dialogue_turns", [])
if not isinstance(dialogue_turns, list):
return False
# checkTranslated commenthaveTranslated commentdialogue
if len(dialogue_turns) == 0:
return False
# checkeachTranslated commentdialogueTranslated commentneedfield
for turn in dialogue_turns:
if not isinstance(turn, dict):
return False
if not turn.get("speaker") or not turn.get("content"):
return False
return True
except Exception:
return False
def check_dialogue_sequence_integrity(dialogues_dir: Path, expected_sessions: List[str]) -> Dict[str, Any]:
"""
checkdialoguecolumn,check
Args:
dialogues_dir: dialoguefiledirectory
expected_sessions: session IDlist()
Returns:
{
"is_sequence_complete": bool,
"last_complete_session": str or None,
"sessions_to_regenerate": List[str],
"intact_sessions": List[str]
}
"""
intact_sessions = []
first_problem_index = None
# Translated commentcheckeachitemssession
for i, session_id in enumerate(expected_sessions):
session_file = dialogues_dir / f"{session_id}.json"
if session_file.exists() and validate_dialogue(session_file):
intact_sessions.append(session_id)
else:
if first_problem_index is None:
first_problem_index = i
break # Translated commentitemsTranslated comment,stopcheck
# Translated commentneedwantTranslated commentnewgeneratesessions(fromTranslated commentitemsTranslated commentbeginallafterTranslated commentsessions)
if first_problem_index is not None:
sessions_to_regenerate = expected_sessions[first_problem_index:]
last_complete_session = intact_sessions[-1] if intact_sessions else None
else:
sessions_to_regenerate = []
last_complete_session = intact_sessions[-1] if intact_sessions else None
return {
"is_sequence_complete": len(sessions_to_regenerate) == 0,
"last_complete_session": last_complete_session,
"sessions_to_regenerate": sessions_to_regenerate,
"intact_sessions": intact_sessions,
"first_problem_index": first_problem_index
}
def validate_dialogues_completeness(dialogues_dir: Path, summaries_data: Dict[str, Any]) -> Dict[str, Any]:
"""
validationallsessiondialogueisgenerate,columncheck
Args:
dialogues_dir: dialoguefiledirectory
summaries_data: session summariesdata
Returns:
{
"is_complete": bool,
"expected_sessions": int,
"completed_sessions": int,
"missing_sessions": List[str],
"existing_session_ids": List[str],
"sequence_integrity": Dict # newTranslated commentcolumnTranslated commentinformation
}
"""
if not summaries_data or "sessions" not in summaries_data:
return {
"is_complete": False,
"expected_sessions": 0,
"completed_sessions": 0,
"missing_sessions": [],
"existing_session_ids": [],
"sequence_integrity": {
"is_sequence_complete": False,
"sessions_to_regenerate": [],
"last_complete_session": None,
"intact_sessions": [],
"first_problem_index": None
}
}
sessions = summaries_data["sessions"]
# Translated commentgetsession IDs
expected_sessions = [session.get("session_id") for session in sessions if isinstance(session, dict) and session.get("session_id")]
expected_sessions_count = len(expected_sessions)
# checkdialoguesdirectoryisTranslated commentin
if not dialogues_dir.exists():
return {
"is_complete": False,
"expected_sessions": expected_sessions_count,
"completed_sessions": 0,
"missing_sessions": expected_sessions,
"existing_session_ids": [],
"sequence_integrity": {
"is_sequence_complete": False,
"sessions_to_regenerate": expected_sessions,
"last_complete_session": None,
"intact_sessions": [],
"first_problem_index": 0
}
}
# usenewTranslated commentcolumnTranslated commentcheck
sequence_integrity = check_dialogue_sequence_integrity(dialogues_dir, expected_sessions)
# getallTranslated commentindialoguefile
dialogue_files = list(dialogues_dir.glob("*.json"))
existing_session_ids = set()
# validationeachitemsdialoguefileTranslated comment
valid_dialogue_files = []
for dialogue_file in dialogue_files:
if validate_dialogue(dialogue_file):
try:
with open(dialogue_file, 'r', encoding='utf-8') as f:
dialogue_data = json.load(f)
session_id = dialogue_data.get("session_id")
if session_id:
existing_session_ids.add(session_id)
valid_dialogue_files.append(dialogue_file)
except Exception:
# fileTranslated comment,Translated comment
continue
completed_sessions = len(valid_dialogue_files)
missing_sessions = set(expected_sessions) - existing_session_ids
return {
"is_complete": sequence_integrity["is_sequence_complete"] and completed_sessions == expected_sessions_count,
"expected_sessions": expected_sessions_count,
"completed_sessions": completed_sessions,
"missing_sessions": sorted(list(missing_sessions)),
"existing_session_ids": sorted(list(existing_session_ids)),
"valid_dialogue_files": [f.name for f in sorted(valid_dialogue_files)],
"sequence_integrity": sequence_integrity
}
def get_topic_name_by_id(topic_id: str) -> str:
"""Translated docstring"""
topics = TOPIC_ATTR_DATA.get('topics', [])
for topic in topics:
if topic.get('topic_id') == topic_id:
return topic.get('topic_name', f'topic_{topic_id}')
return f'topic_{topic_id}'
def check_project_progress(safe_person_name: str, project_identifier: str) -> Dict[str, Any]:
"""Translated docstring"""
base_dir = Path(f"output/{safe_person_name}/{project_identifier}")
# 1. checkblueprint
blueprint_file = base_dir / "project_blueprints" / f"{project_identifier}_blueprint.json"
if not blueprint_file.exists():
return {"status": "need_blueprint", "stage": "blueprint", "progress": 0}
try:
with open(blueprint_file, 'r', encoding='utf-8') as f:
blueprint = json.load(f)
# validationblueprintTranslated comment
if not validate_blueprint(blueprint):
return {"status": "blueprint_incomplete", "stage": "blueprint", "progress": 0}
except Exception as e:
return {"status": "blueprint_corrupted", "stage": "blueprint", "progress": 0, "error": str(e)}
# 2. checkevents
events_file = base_dir / "project_events" / f"{project_identifier}_events.json"
if not events_file.exists():
return {"status": "need_events", "stage": "events", "progress": 25}
try:
with open(events_file, 'r', encoding='utf-8') as f:
events_data = json.load(f)
if not validate_events(events_data):
return {"status": "events_incomplete", "stage": "events", "progress": 25}
except Exception as e:
return {"status": "events_corrupted", "stage": "events", "progress": 25, "error": str(e)}
# 3. checksession summaries
summaries_file = base_dir / "session_summaries" / f"{project_identifier}_summary.json"
if not summaries_file.exists():
return {"status": "need_summaries", "stage": "summaries", "progress": 50}
try:
with open(summaries_file, 'r', encoding='utf-8') as f:
summaries_data = json.load(f)
if not validate_summaries(summaries_data, events_data):
return {"status": "summaries_incomplete", "stage": "summaries", "progress": 50}
except Exception as e:
return {"status": "summaries_corrupted", "stage": "summaries", "progress": 50, "error": str(e)}
# 4. checkdialogues(Translated commentcolumnTranslated commentcheck)
dialogues_dir = base_dir / "dialogues"
# usenewdialogueTranslated commentvalidationfunction
dialogue_completeness = validate_dialogues_completeness(dialogues_dir, summaries_data)
if dialogue_completeness["expected_sessions"] == 0:
return {
"status": "need_summaries",
"stage": "summaries",
"progress": 50,
"error": "No sessions found in summaries data"
}
# useTranslated commentcolumnTranslated commentcheckresult
sequence_integrity = dialogue_completeness["sequence_integrity"]
if not sequence_integrity["is_sequence_complete"]:
sessions_to_regenerate = sequence_integrity["sessions_to_regenerate"]
last_complete_session = sequence_integrity["last_complete_session"]
first_session_to_regenerate = sessions_to_regenerate[0] if sessions_to_regenerate else None
return {
"status": "dialogues_incomplete",
"stage": "dialogues",
"progress": 75,
"start_from_session": first_session_to_regenerate,
"sessions_to_regenerate": sessions_to_regenerate,
"last_complete_session": last_complete_session,
"total_sessions": dialogue_completeness["expected_sessions"],
"intact_sessions": sequence_integrity["intact_sessions"],
"existing_session_ids": dialogue_completeness["existing_session_ids"],
"regeneration_reason": f"Sequence broken at {first_session_to_regenerate}"
}
# Translated commentcolumnTranslated comment(Translated commentonTranslated commentwillTranslated comment,Translated commentforTranslated commentcolumnTranslated comment)
if not dialogue_completeness["is_complete"]:
return {
"status": "dialogue_corrupted",
"stage": "dialogues",
"progress": 75,
"valid_files": dialogue_completeness["valid_dialogue_files"],
"expected_files_count": dialogue_completeness["expected_sessions"]
}
# 5. checkproject memory
project_memory_file = base_dir / "project_memories" / f"{project_identifier}_memory.json"
if not project_memory_file.exists():
return {"status": "need_project_memory", "stage": "memory", "progress": 95}
# projectcomplete
return {
"status": "completed",
"stage": "completed",
"progress": 100,
"total_sessions": dialogue_completeness["expected_sessions"],
"sequence_integrity": sequence_integrity
}
def convert_to_safe_filename(text: str) -> str:
"""
willtextforfileformat
infor,forunder
Args:
text: originaltext
Returns:
filestring
"""
if not text:
return "unknown"
# willinTranslated commentforTranslated comment,Translated commenthaveTranslated comment
pinyin_list = lazy_pinyin(text, style=Style.NORMAL, neutral_tone_with_five=True)
pinyin_text = "".join(pinyin_list)
# Translated commentnon-Translated comment,Translated commentforunderTranslated comment
safe_name = "".join([c if c.isalnum() else "_" for c in pinyin_text])
# removeTranslated commentunderTranslated comment
while "__" in safe_name:
safe_name = safe_name.replace("__", "_")
# removeTranslated commentunderTranslated comment
safe_name = safe_name.strip("_")
return safe_name or "unknown"
def read_persona_topic_files(persona_file="dataset/all_persona_topic/persona_all.json",
topic_attr_file="dataset/all_persona_topic/topic&goal&attr.json",
person_goal_file="dataset/all_persona_topic/person&goal.json"):
"""Read and properly parse the persona and topic/goal/attribute JSON files."""
global PERSONA_DATA, TOPIC_ATTR_DATA, PERSON_GOAL_DATA
# If data already loaded, return cached values
if PERSONA_DATA is not None and TOPIC_ATTR_DATA is not None and PERSON_GOAL_DATA is not None:
return
try:
# Read and parse persona data (array of persona objects)
with open(persona_file, 'r', encoding='utf-8') as f:
PERSONA_DATA = json.load(f)
# Read and parse topic/goal/attribute data (contains topics array)
with open(topic_attr_file, 'r', encoding='utf-8') as f:
TOPIC_ATTR_DATA = json.load(f)
# Read and parse person/goal data (contains person array)
with open(person_goal_file, 'r', encoding='utf-8') as f:
PERSON_GOAL_DATA = json.load(f)
# Validate structure
if not isinstance(PERSONA_DATA, list):
raise ValueError("persona file should contain an array of persona objects")
if not isinstance(TOPIC_ATTR_DATA, dict) or "topics" not in TOPIC_ATTR_DATA:
raise ValueError("topic&attr file should contain a 'topics' key")
if not isinstance(PERSON_GOAL_DATA, list):
raise ValueError("person&goal file should contain an array of person/goal pairs")
print(f"✅ Loaded {len(PERSONA_DATA)} personas")
print(f"✅ Loaded {len(TOPIC_ATTR_DATA['topics'])} topics")
print(f"✅ Loaded {len(PERSON_GOAL_DATA)} person/goal pairs")
except FileNotFoundError as e:
print(f"❌ Error: File not found - {e}")
except json.JSONDecodeError as e:
print(f"❌ Error: Invalid JSON format - {e}")
except ValueError as e:
print(f"❌ Error: Invalid data structure - {e}")
return
def get_person_memory(person_name: str) -> Dict[str, Any]:
"""Translated docstring"""
global PERSON_MEMORY_DATA
if person_name not in PERSON_MEMORY_DATA:
# attemptfromnewpathloadTranslated commenthavememoryfile
safe_person_name = convert_to_safe_filename(person_name)
memory_file_path = Path(f"output/{safe_person_name}/{safe_person_name}_memory.json")
if memory_file_path.exists():
try:
with open(memory_file_path, 'r', encoding='utf-8') as f:
loaded_memory = json.load(f)
PERSON_MEMORY_DATA[person_name] = loaded_memory
print(f"✅ Loaded existing memory for {person_name}: {memory_file_path}")
except Exception as e:
print(f"⚠️ Failed to load memory file {memory_file_path}: {str(e)}")
# initializenewpersonmemoryTranslated commentbetween
PERSON_MEMORY_DATA[person_name] = {
"memory_points": [],
"total_sessions": 0,
"last_updated": time.time(),
"metadata": {
"person_name": person_name,
"created_at": time.time(),
"last_session_id": None
}
}
else:
# initializenewpersonmemoryTranslated commentbetween
PERSON_MEMORY_DATA[person_name] = {
"memory_points": [],
"total_sessions": 0,
"last_updated": time.time(),
"metadata": {
"person_name": person_name,
"created_at": time.time(),
"last_session_id": None
}
}
return PERSON_MEMORY_DATA[person_name]
def save_project_memory(person_name: str, project_identifier: str, memory_data: Dict[str, Any]) -> str:
"""
saveprojectmemorydatatofile
Args:
person_name: personname
project_identifier: projectID
memory_data: memorydata
Returns:
savefilepath
"""
safe_person_name = convert_to_safe_filename(person_name)
# createprojectmemorydirectory
project_memory_dir = Path(f"output/{safe_person_name}/{project_identifier}/project_memories")
project_memory_dir.mkdir(parents=True, exist_ok=True)
# generateprojectmemoryfile
filename = f"{project_identifier}_memory.json"
filepath = project_memory_dir / filename
# saveprojectmemorydata
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(memory_data, f, ensure_ascii=False, indent=2)
print(f"💾 Saved project memory for {project_identifier}: {filepath}")
return str(filepath)
def save_person_memory(person_name: str, output_dir: str = None) -> str:
"""
savepersonmemorydatatofile
Args:
person_name: personname
output_dir: outputdirectory
Returns:
savefilepath
"""
global PERSON_MEMORY_DATA
if person_name not in PERSON_MEMORY_DATA:
return None
# Translated commenthaveTranslated commentoutputdirectory,usenewTranslated commentstructure
if output_dir is None:
safe_person_name = convert_to_safe_filename(person_name)
output_dir = f"output/{safe_person_name}"
# createoutputdirectory
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# generatefileTranslated comment
safe_person_name = convert_to_safe_filename(person_name)
filename = f"{safe_person_name}_memory.json"
filepath = output_path / filename
# savememorydata
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(PERSON_MEMORY_DATA[person_name], f, ensure_ascii=False, indent=2)
print(f"💾 Saved memory for {person_name}: {filepath}")
return str(filepath)
def get_person_schedule(person_name: str, project_identifier: str = None) -> Dict[str, Any]:
"""Translated docstring"""
safe_person_name = convert_to_safe_filename(person_name)
schedule_file_path = Path(f"output/{safe_person_name}/schedule.json")
# Translated commentdirectoryTranslated commentin
schedule_file_path.parent.mkdir(parents=True, exist_ok=True)
if schedule_file_path.exists():
try:
with open(schedule_file_path, 'r', encoding='utf-8') as f:
schedule_data = json.load(f)
print(f"✅ Loaded existing schedule for {person_name}/{project_identifier}: {schedule_file_path}")
return schedule_data
except Exception as e:
print(f"⚠️ Failed to load schedule file {schedule_file_path}: {str(e)}")
# returnTranslated commentstructure
return {
"plan_items": [], # Translated commentprojectlist
"current_date": "", # currentdate
"metadata": {
"created_time": time.time(),
"person_name": person_name,
"max_plan_id": 0 # Translated commentIDfor0
}
}
def extract_plan_items_content(schedule_data: Dict[str, Any]) -> List[str]:
"""
fromscheduledatainprojectcontentlist
Args:
schedule_data: includesprojectdata
Returns:
projectcontentstringlist
"""
plan_items = schedule_data.get("plan_items", [])
if not plan_items:
return []
# Translated commentisstringlist,Translated commentreturn
if isinstance(plan_items[0], str):
return plan_items
# Translated commentisobjectlist,Translated commentcontentfield
if isinstance(plan_items[0], dict):
return [item.get("content", "") for item in plan_items if item.get("content")]
return []
def get_plan_items_full(schedule_data: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
fromscheduledataingetprojectobjectlist
Args:
schedule_data: includesprojectdata
Returns:
projectobjectlist
"""
plan_items = schedule_data.get("plan_items", [])
if not plan_items:
return []
# Translated commentisstringlist,needwantTranslated commentforTranslated commentstructure(Translated commentafterTranslated comment)
if isinstance(plan_items[0], str):
return [{"content": content} for content in plan_items]
# Translated commentisobjectlist,Translated commentreturn
if isinstance(plan_items[0], dict):
return plan_items
return []
def process_plan_items_with_metadata(plan_items: List[Dict[str, Any]], project_identifier: str, session_id: str, existing_schedule_data: Dict[str, Any] = None) -> Tuple[List[Dict[str, Any]], int]:
"""
forprojectaddsessionandidfield
Args:
plan_items: projectlist
project_identifier: projectID
session_id: sessionID
existing_schedule_data: havedata,getID
Returns:
tuple: (includesmetadataprojectlist, newID)
"""
if not plan_items:
return [], 0
# getTranslated commenthaveTranslated commentID:Translated commentfrommetadatainget,itstimesfromTranslated commenthaveprojectincalculate
max_id = 0
if existing_schedule_data:
# Translated commentattemptfrommetadataingetrecordTranslated commentID
metadata = existing_schedule_data.get("metadata", {})
if "max_plan_id" in metadata:
try:
max_id = int(metadata["max_plan_id"])
except (ValueError, TypeError):
pass
else:
# Translated commentmetadatainTranslated commenthave,Translated commentfromTranslated commenthaveprojectincalculate
if "plan_items" in existing_schedule_data:
existing_items = existing_schedule_data["plan_items"]
if existing_items and isinstance(existing_items[0], dict):
for item in existing_items:
if isinstance(item, dict) and "id" in item:
try:
max_id = max(max_id, int(item["id"]))
except (ValueError, TypeError):
pass
processed_items = []
for item in plan_items:
if isinstance(item, dict):
# Translated commentisTranslated commentstructure,checkisTranslated commentneedwantaddfield
if "id" not in item:
max_id += 1
item["id"] = str(max_id)
item["session"] = f"{project_identifier}:{session_id}"
item["created_time"] = time.time()
else:
# Translated commenthaveid,updatemax_id
try:
max_id = max(max_id, int(item["id"]))
except (ValueError, TypeError):
pass
processed_items.append(item)
else:
# Translated commentisstring,createTranslated commentstructure
max_id += 1
processed_items.append({
"id": str(max_id),
"content": item,
"session": f"{project_identifier}:{session_id}",
"created_time": time.time()
})
return processed_items, max_id
def save_person_schedule(person_name: str, schedule_data: Dict[str, Any], project_identifier: str = None, session_id: str = None) -> str:
"""Translated docstring"""
safe_person_name = convert_to_safe_filename(person_name)
schedule_file_path = Path(f"output/{safe_person_name}/schedule.json")
# Translated commentdirectoryTranslated commentin
schedule_file_path.parent.mkdir(parents=True, exist_ok=True)
# initializevariable
new_max_id = None
# processTranslated commentproject,addmetadata
if "plan_items" in schedule_data and project_identifier and session_id:
# readTranslated commenthavedataTranslated commentgetTranslated commentID
existing_schedule_data = {}
if schedule_file_path.exists():
try:
with open(schedule_file_path, 'r', encoding='utf-8') as f:
existing_schedule_data = json.load(f)
except Exception:
pass
# Translated commentprojectforstructureTranslated commentformat,getnewTranslated commentID
plan_items = schedule_data["plan_items"]
processed_items, new_max_id = process_plan_items_with_metadata(
plan_items, project_identifier, session_id, existing_schedule_data
)
schedule_data["plan_items"] = processed_items
# updateTranslated commentdata,includingTranslated commentID
if "metadata" not in schedule_data:
schedule_data["metadata"] = {}
metadata_updates = {
"updated_time": time.time(),
"person_name": person_name
}
# savenewTranslated commentIDtometadatain
if new_max_id is not None:
metadata_updates["max_plan_id"] = new_max_id
schedule_data["metadata"].update(metadata_updates)
try:
with open(schedule_file_path, 'w', encoding='utf-8') as f:
json.dump(schedule_data, f, ensure_ascii=False, indent=2)
print(f"💾 Schedule saved: {schedule_file_path}")
return str(schedule_file_path)
except Exception as e:
print(f"❌ Failed to save schedule file {schedule_file_path}: {str(e)}")
return ""
def generate_project_blueprint(person_data: Dict[str, Any], project_attributes: List[str], project_goal: str = None, model: str = None, topic_name: str = None, selected_task_id: str = None) -> Optional[Dict[str, Any]]:
"""
Generate project blueprint for a specific person using ProjectOutlineProcessor
Args:
person_data: Persona data object
project_attributes: List of project attributes from the selected topic
project_goal: Specific goal/task description (optional)
model: LLM model name
topic_name: Selected topic name (optional)
selected_task_id: Selected task ID (optional)
Returns:
Project blueprint data or None if failed
"""
person_name = person_data.get('name', 'unknown_person')
try:
# Use provided model or default
if model is None:
model = "gemini-2.5-pro-thinking-*"
# Initialize LLM client
llm_client = create_client(api_key=api_key, base_url=base_url, model=model)
print("✅ LLM client initialized")
# Initialize ProjectOutlineProcessor
processor = ProjectOutlineProcessor(
llm_client=llm_client,
checkpoint_dir="output/checkpoints/project_outline"
)
print("✅ ProjectOutlineProcessor initialized")
# Prepare input data for processor
processor_input = {
"persona": person_data,
"project_attributes": project_attributes
}
# Add project_goal if provided
if project_goal:
processor_input["primary_goal"] = project_goal
# Process the person data
result = processor.process(
data=processor_input,
use_checkpoint=False
)
if result.success:
print("✅ Project blueprint generated successfully!")
# Add metadata to the result
blueprint = result.data
blueprint["_metadata"] = {
"person_name": person_name,
"persona_role": person_data.get('role', 'Unknown'),
"total_attributes_used": len(project_attributes)
}
# Add topic and task metadata if provided
if topic_name:
blueprint["selected_topic"] = topic_name
if project_goal:
blueprint["selected_goal"] = project_goal
if selected_task_id:
blueprint["selected_task_id"] = selected_task_id
# addproject_attributes_schemafield - Translated commentvalidationfailedTranslated comment
if project_attributes:
blueprint["project_attributes_schema"] = project_attributes
# Generate project identifier for directory structure
safe_topic_name = convert_to_safe_filename(topic_name) if topic_name else "unknown_topic"
safe_person_name = convert_to_safe_filename(person_name)
# Debug: checkparametervalue
print(f" Debug generate_project_blueprint:")
print(f" topic_name: '{topic_name}'")
print(f" selected_task_id: '{selected_task_id}' (type: {type(selected_task_id)})")
print(f" safe_topic_name: '{safe_topic_name}'")
project_identifier = f"{safe_topic_name}_{selected_task_id or 'unknown'}"
print(f" project_identifier: '{project_identifier}'")
# Save blueprint to new directory structure
output_dir = Path(f"output/{safe_person_name}/{project_identifier}/project_blueprints")
output_dir.mkdir(parents=True, exist_ok=True)
filename = f"{project_identifier}_blueprint.json"
filepath = output_dir / filename
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(blueprint, f, ensure_ascii=False, indent=2)
print(f"✅ Blueprint saved to: {filepath}")
return blueprint
else:
print(f"❌ Failed to generate project blueprint: {result.error_message}")
return None
except Exception as e:
print(f"❌ Error generating project blueprint: {str(e)}")
return None
def generate_session_summaries(person_data: Dict[str, Any], blueprint: Dict[str, Any], events_data: Dict[str, Any], model: str = None) -> Optional[Dict[str, Any]]:
"""
forprojecteventGenerate session summaries
Args:
person_data: roledata
blueprint: projectblueprint
events_data: eventdata
model: LLMname
Returns:
summarydataorNone
"""
person_name = person_data.get('name', 'unknown_person')
# eventdatacancaninTranslated commentfieldin
if 'events' in events_data:
events_list = events_data['events']
elif 'output_data' in events_data:
if isinstance(events_data['output_data'], list):
events_list = events_data['output_data']
elif isinstance(events_data['output_data'], dict):
events_list = events_data['output_data'].get('events', [])
else:
events_list = []
else:
events_list = []
if len(events_list) == 0:
print(f" ⚠️ havetoeventdata,summarygenerate")
return None
try:
# Use provided model or default
if model is None:
model = "gemini-2.5-pro-thinking-*"
# initializeLLMTranslated comment
llm_client = create_client(api_key=api_key, base_url=base_url, model=model)
print(" ✅ Summary LLM client initialized")
# initializeSummaryProcessor
summary_processor = SummaryProcessor(
llm_client=llm_client,
checkpoint_dir="output/checkpoints/summaries"
)
print(" ✅ SummaryProcessor initialized")
all_summaries = []
# foreacheventgeneratesummary