-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombined_code.txt
2583 lines (2189 loc) · 97.2 KB
/
combined_code.txt
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
----- File: ./entity_registry.py -----
# entity_registry.py
from typing import Dict, Optional, List, Any, Tuple
import logging
import re
import pydantic
from thefuzz import fuzz
from entity_normalizer import EntityNormalizer
logger = logging.getLogger(__name__)
class EntityRegistry:
"""Maintains consistent entity tracking across scenes."""
def __init__(self):
self.agents = {}
self.objects = {}
self.locations = {}
self.organizations = {}
self._debug_matches = {}
self.normalizer = EntityNormalizer() # Add this line
def normalize_name(self, name: str) -> str:
"""Enhanced name normalization."""
return self.normalizer.normalize_name(name)
def determine_primary_entity_type(self, entity_name: str, extracted_types: Dict[str, Dict]) -> Optional[Tuple[str, str]]:
"""
Enhanced to prioritize organizations over locations and handle cases where an entity is extracted as both.
"""
normalized_name = self.normalize_name(entity_name)
# Find all matching entities across types
found_types = {}
for type_name, entities in extracted_types.items():
for uuid, data in entities.items():
if self.normalize_name(data.get('name', '')) == normalized_name:
found_types[type_name] = {
'uuid': uuid,
'data': data
}
if not found_types:
return None
# Prioritize organizations over locations
if 'organizations' in found_types and 'locations' in found_types:
logger.warning(f"Entity '{entity_name}' is both an organization and a location. Prioritizing organization.")
return ('organizations', found_types['organizations']['uuid'])
# Base type hierarchy with organizations prioritized over locations
type_scores = {
'agents': 10,
'organizations': 9,
'locations': 6,
'objects': 4
}
# Calculate final scores with context-based adjustments
final_scores = {}
for type_name, type_data in found_types.items():
score = type_scores[type_name]
entity_data = type_data['data']
# Context-based score adjustments
if self._has_type_specific_traits(type_name, normalized_name, entity_data):
score += 2
# Special case: known agent references should strongly favor agent type
if type_name == 'agents' and self._is_known_agent_reference(normalized_name):
score += 5
final_scores[type_name] = score
# Get type with highest score
if not final_scores:
return None
primary_type = max(final_scores.items(), key=lambda x: x[1])[0]
uuid = found_types[primary_type]['uuid']
logger.debug(f"Resolved entity '{entity_name}' to primary type '{primary_type}' with uuid '{uuid}'")
return (primary_type, uuid)
def _has_type_specific_traits(self, type_name: str, name: str, entity_data: Dict) -> bool:
"""Helper method to check for type-specific characteristics."""
name_lower = name.lower()
description = entity_data.get('description', '').lower() if entity_data.get('description') else ''
# Group/collective terms should be organizations
collective_terms = {
'workers', 'group', 'team', 'unit', 'force', 'corps',
'committee', 'staff', 'personnel', 'service'
}
# Known locations/spaces
location_terms = {
'room', 'office', 'building', 'hall', 'wing', 'venue',
'house', 'center', 'centre', 'area', 'chamber', 'situation room'
}
if type_name == 'locations':
return any(term in name_lower for term in location_terms)
elif type_name == 'organizations':
return (
any(term in name_lower for term in collective_terms) or
any(term in description for term in collective_terms)
)
elif type_name == 'agents':
# Enhanced check for human names
has_full_name = bool(re.search(r'^[A-Z][a-z]+ (?:[A-Z][a-z]+ )*[A-Z][a-z]+$', name))
# If it's a person name or title
agent_indicators = {
'president', 'senator', 'secretary', 'ambassador',
'director', 'chief', 'minister', 'advisor', 'doctor'
}
title = entity_data.get('title', '').lower() if entity_data.get('title') else ''
# Person detection
person_indicators = {'grandmother', 'brother', 'sister', 'father', 'mother', 'aunt', 'uncle'}
# Check for various person indicators
return (
has_full_name or
any(indicator in description for indicator in person_indicators) or
any(term in name_lower for term in agent_indicators) or
any(term in title for term in agent_indicators) or
bool(re.match(r'^[A-Z][a-z]+$', name)) # single-word proper name
)
return False
def _is_known_agent_reference(self, normalized_name: str) -> bool:
"""Helper method to check if this matches any known agent patterns."""
# Check against existing agents
for agent in self.agents.values():
if normalized_name == self.normalize_name(agent['name']):
return True
if 'agent_id' in agent and normalized_name == agent['agent_id']:
return True
return False
def find_best_match(self, name: str, registry: Dict[str, Dict[str, Any]]) -> Optional[str]:
"""Find best matching entity using fuzzy matching with enhanced type checking."""
logger.debug(f"Finding best match for: {name} (type: {type(name)}) in registry")
if not name or not isinstance(name, str):
logger.warning(f"Invalid name parameter: {name} (type: {type(name)})")
return None
# Direct UUID match
if name in registry:
self._debug_matches[name] = ('direct_uuid', name)
return name
normalized = self.normalize_name(name)
# Direct normalized name match
for uuid, details in registry.items():
# Ensure we're working with string names
entity_name = details.get('name', '')
if isinstance(entity_name, (dict, pydantic.BaseModel)):
logger.warning(f"Found non-string name in registry: {entity_name}")
continue
if self.normalize_name(str(entity_name)) == normalized:
self._debug_matches[name] = ('direct', normalized)
return uuid
# Fuzzy matching with type safety
best_match = None
best_ratio = 0
for uuid, details in registry.items():
try:
entity_name = str(details.get('name', ''))
ratio = fuzz.ratio(normalized, self.normalize_name(entity_name))
if ratio > 85 and ratio > best_ratio:
best_match = uuid
best_ratio = ratio
self._debug_matches[name] = ('fuzzy', entity_name, ratio)
except Exception as e:
logger.error(f"Error during fuzzy matching: {e}")
continue
return best_match
def register_entity(self, entity_type: str, entity: Dict) -> Optional[str]:
"""Register an entity with enhanced type checking and organization resolution."""
if not entity or not entity.get('name'):
logger.warning(f"Attempting to register invalid entity: {entity}")
return None
# Convert any Pydantic models to dictionaries
if isinstance(entity, pydantic.BaseModel):
entity = entity.model_dump()
# Ensure name is a string
if not isinstance(entity['name'], str):
try:
entity['name'] = str(entity['name'])
except Exception as e:
logger.error(f"Could not convert entity name to string: {e}")
return None
# Clean references before registration
entity = self._clean_entity_references(entity)
normalized_name = self.normalize_name(entity['name'])
# Check across all registries
current_entities = {
'agents': self.agents,
'objects': self.objects,
'locations': self.locations,
'organizations': self.organizations
}
resolution = self.determine_primary_entity_type(normalized_name, current_entities)
if resolution:
primary_type, existing_uuid = resolution
if primary_type != entity_type:
logger.warning(
f"Skipping registration of {entity_type} '{entity['name']}' "
f"as it exists as {primary_type} {existing_uuid}"
)
return None
# Update existing entity with any new information
existing_entity = getattr(self, primary_type)[existing_uuid]
self._merge_entity_data(existing_entity, entity)
return existing_uuid
# New entity registration
if 'uuid' not in entity:
entity['uuid'] = f"{entity_type[:-1]}-{normalized_name}"
# Special handling for agent's affiliated_org
if entity_type == 'agents' and 'affiliated_org' in entity:
org_ref = entity['affiliated_org']
if isinstance(org_ref, str):
# Resolve the organization reference
org_uuid = self.resolve_organization_reference(org_ref)
if org_uuid:
entity['affiliated_org'] = org_uuid
else:
# If still not resolved, remove the reference
del entity['affiliated_org']
logger.warning(f"Removed unresolved affiliated_org for agent {entity['name']}")
else:
# Remove the affiliated_org if it's not a string
del entity['affiliated_org']
logger.warning(f"Removed invalid affiliated_org for agent {entity['name']}")
registry = getattr(self, entity_type)
registry[entity['uuid']] = entity
return entity['uuid']
def _clean_entity_references(self, entity: Dict) -> Dict:
"""Clean entity references to ensure they're stored as strings."""
cleaned = entity.copy()
# Clean original_owner references
if 'original_owner' in cleaned:
if isinstance(cleaned['original_owner'], pydantic.BaseModel):
cleaned['original_owner'] = cleaned['original_owner'].uuid
elif isinstance(cleaned['original_owner'], dict):
cleaned['original_owner'] = cleaned['original_owner'].get('uuid')
# Clean location references
if 'location' in cleaned:
if isinstance(cleaned['location'], pydantic.BaseModel):
cleaned['location'] = cleaned['location'].uuid
elif isinstance(cleaned['location'], dict):
cleaned['location'] = cleaned['location'].get('uuid')
# Clean affiliated_org references
if 'affiliated_org' in cleaned:
if isinstance(cleaned['affiliated_org'], pydantic.BaseModel):
cleaned['affiliated_org'] = cleaned['affiliated_org'].uuid
elif isinstance(cleaned['affiliated_org'], dict):
cleaned['affiliated_org'] = cleaned['affiliated_org'].get('uuid')
return cleaned
def _merge_entity_data(self, existing: Dict, new: Dict) -> None:
"""Helper method to merge new entity data into existing entity."""
# Update non-null fields
for key, value in new.items():
if value is not None and key != 'uuid':
if isinstance(value, list):
# Merge lists without duplicates
existing[key] = list(set(existing.get(key, []) + value))
elif isinstance(value, str) and key in existing:
# Take longer string values, handling None
existing_value = existing[key]
if existing_value is None or (len(value) > len(existing_value)):
existing[key] = value
else:
existing[key] = value
def resolve_reference(self, entity_type: str, reference: str) -> Optional[str]:
"""Resolve an entity reference to its UUID."""
if not reference:
return None
# Try finding in specified type first
registry = getattr(self, entity_type)
if uuid := self.find_best_match(reference, registry):
return uuid
# Special handling for organizations when resolving agent affiliations
if entity_type == 'agents' and 'affiliated_org' in reference:
org_name = reference.split('affiliated_org:')[-1].strip()
if org_uuid := self.resolve_organization_reference(org_name):
return org_uuid
# Check other types
normalized_ref = self.normalize_name(reference)
for type_name in ['agents', 'objects', 'locations', 'organizations']:
if type_name == entity_type:
continue
registry = getattr(self, type_name)
if uuid := self.find_best_match(normalized_ref, registry):
logger.warning(
f"Attempted to reference {entity_type} '{reference}' "
f"but it exists as {type_name} {uuid}"
)
return None
return None
def resolve_organization_reference(self, org_name: str) -> Optional[str]:
"""Specifically resolve an organization reference, creating it if not found."""
logger.debug(f"Resolving organization reference: '{org_name}'")
if not org_name:
logger.debug("Organization reference is None or empty, returning None")
return None
normalized_name = self.normalize_name(org_name)
# Check if it exists
for org_uuid, org_data in self.organizations.items():
if self.normalize_name(org_data['name']) == normalized_name:
logger.debug(f"Found existing organization: {org_uuid}")
return org_uuid
# Create if it doesn't exist
logger.info(f"Creating missing organization: {org_name}")
new_org_uuid = f"org-{normalized_name}"
self.organizations[new_org_uuid] = {
'uuid': new_org_uuid,
'name': org_name,
'description': 'Automatically created from agent affiliation',
'members': [] # Initialize with an empty member list
}
return new_org_uuid
def get_entity_details(self, entity_type: str, uuid: str) -> Optional[Dict]:
"""Retrieve entity details by UUID."""
logger.debug(f"Getting details for {entity_type} with UUID: {uuid}")
if not uuid: # Early return for null/empty UUIDs
return None
registry = getattr(self, entity_type)
details = registry.get(uuid)
if details:
logger.debug(f"Found details for {entity_type} with UUID: {uuid}")
return details
else:
logger.debug(f"No details found for {entity_type} with UUID: {uuid}")
return None
def get_entity_by_name(self, entity_type: str, name: str) -> Optional[Dict]:
"""Retrieve entity details by normalized name."""
registry = getattr(self, entity_type)
if uuid := self.find_best_match(name, registry):
return registry[uuid]
return None
def merge_entities(self, entity_type: str, uuid1: str, uuid2: str) -> Optional[str]:
"""Merges two entities of the same type, returning the UUID of the merged entity."""
registry = getattr(self, entity_type)
if uuid1 not in registry or uuid2 not in registry:
logger.warning(f"Cannot merge: One or both entities not found in {entity_type}: {uuid1}, {uuid2}")
return None
if uuid1 == uuid2:
logger.info(f"No merge needed: Entities are the same: {uuid1}")
return uuid1
# For now, we'll just keep the first entity and discard the second
# In the future, implement more sophisticated merging logic here
logger.info(f"Merging {entity_type} {uuid2} into {uuid1}. Currently, this just keeps {uuid1} and discards {uuid2}.")
del registry[uuid2]
return uuid1
def debug_registry(self):
"""Print current registry state for debugging."""
for entity_type in ['agents', 'objects', 'locations', 'organizations']:
registry = getattr(self, entity_type)
logger.debug(f"\n{entity_type.upper()}:")
for uuid, details in registry.items():
logger.debug(f" UUID: {uuid}, Name: {details['name']}, Agent ID: {details.get('agent_id')}")
----- File: ./scene_processor.py -----
# scene_processor.py
from typing import Dict, Optional, List, Any
import logging
from baml_client import b
from baml_client.type_builder import TypeBuilder
from entity_registry import EntityRegistry
from entity_extractors import (
extract_and_register_entities,
infer_object_owners
)
logger = logging.getLogger(__name__)
async def process_scene(
scene_data: Dict,
story_context: str,
scene_number: int,
*,
next_scene_uuid: Optional[str]=None,
entity_registry: Optional[EntityRegistry]=None,
tb: Optional[TypeBuilder] = None,
known_agent_uuids: Optional[List[str]] = None,
known_object_uuids: Optional[List[str]] = None
) -> Dict:
"""Process a single scene, extracting all relevant information."""
try:
if entity_registry is None:
entity_registry = EntityRegistry()
# Generate scene UUID
scene_uuid = f"scene-{scene_number:03}"
scene_title = scene_data.get("Scene", "Untitled Scene")
logger.info(f"Processing scene: {scene_title} (UUID: {scene_uuid})")
# Format scene text for processing, now passing scene_location
scene_text = format_dialogue(scene_data.get("Dialogue", []), scene_number, scene_data.get("Scene"))
# First extract entities to ensure proper typing
await extract_and_register_entities(
scene_data,
scene_text,
story_context,
entity_registry,
tb
)
# Get current UUIDs after entity registration
current_agent_uuids = known_agent_uuids or list(entity_registry.agents.keys())
current_object_uuids = known_object_uuids or list(entity_registry.objects.keys())
# Extract metadata (now using existing entity UUIDs)
metadata = await b.ExtractSceneMetadata(
scene_text=scene_text,
story_context=story_context,
baml_options={"tb": tb}
)
if metadata:
metadata_dict = metadata.model_dump()
# Directly use the location from ExtractSceneMetadata if it's a valid UUID
if metadata_dict.get('location') and not entity_registry.normalizer.validate_reference(metadata_dict['location']):
# Only resolve if it's not already a valid UUID
location_uuid = entity_registry.resolve_reference('locations', metadata_dict['location'])
metadata_dict['location'] = location_uuid
metadata_dict['uuid'] = scene_uuid
metadata_dict['scene_number'] = scene_number
metadata_dict['next_scene'] = next_scene_uuid
else:
metadata_dict = {
'uuid': scene_uuid,
'scene_number': scene_number,
'next_scene': next_scene_uuid,
'title': scene_title,
'description': ''
}
# Extract events using known entity UUIDs
events = await b.ExtractEvents(
scene_text=scene_text,
story_context=story_context,
scene_number=scene_number,
known_agents=current_agent_uuids,
known_objects=current_object_uuids,
baml_options={"tb": tb}
)
events_list = []
for event in events:
event_dict = event.model_dump()
# Ensure all agent/object references are valid UUIDs
if 'agent_participations' in event_dict:
event_dict['agent_participations'] = [
uuid for uuid in event_dict['agent_participations']
if entity_registry.get_entity_details('agents', uuid)
]
if 'object_involvements' in event_dict:
event_dict['object_involvements'] = [
uuid for uuid in event_dict['object_involvements']
if entity_registry.get_entity_details('objects', uuid)
]
events_list.append(event_dict)
# Extract participations and involvements
agent_participations = await b.ExtractAgentParticipations(
scene_text=scene_text,
story_context=story_context,
events=events_list,
agents=current_agent_uuids,
baml_options={"tb": tb}
)
participations_list = []
for ap in agent_participations:
ap_dict = ap.model_dump()
agent_uuid = entity_registry.resolve_reference('agents', ap_dict['agent'])
if agent_uuid and ap_dict.get('event'):
ap_dict['agent'] = agent_uuid
ap_dict['uuid'] = f"participation-{agent_uuid}-{ap_dict['event']}"
participations_list.append(ap_dict)
object_involvements = await b.ExtractObjectInvolvements(
scene_text=scene_text,
story_context=story_context,
events=events_list,
objects=current_object_uuids,
baml_options={"tb": tb}
)
involvements_list = []
for oi in object_involvements:
oi_dict = oi.model_dump()
object_uuid = entity_registry.resolve_reference('objects', oi_dict['object'])
if object_uuid and oi_dict.get('event'):
oi_dict['object'] = object_uuid
oi_dict['uuid'] = f"involvement-{object_uuid}-{oi_dict['event']}"
involvements_list.append(oi_dict)
return {
"scene_uuid": scene_uuid,
"original_scene_data": scene_data,
"extracted_data": {
"metadata": metadata_dict,
"events": events_list,
"agent_participations": participations_list,
"object_involvements": involvements_list
}
}
except Exception as e:
logger.error(f"Error processing scene {scene_title}: {str(e)}")
return {
"scene_uuid": scene_uuid,
"original_scene_data": scene_data,
"error": str(e)
}
async def extract_scene_metadata(
scene_text: str,
story_context: str,
scene_uuid: str,
scene_number: int,
next_scene_uuid: Optional[str],
entity_registry: EntityRegistry,
tb: TypeBuilder
) -> Dict:
"""Extract and process scene metadata."""
metadata_extracted = await b.ExtractSceneMetadata(
scene_text=scene_text,
story_context=story_context,
baml_options={"tb": tb}
)
metadata = metadata_extracted.model_dump()
metadata["uuid"] = scene_uuid
metadata["scene_number"] = scene_number
metadata["next_scene"] = next_scene_uuid
# Extract and assign primary location
locations = await b.ExtractLocations(
scene_text=scene_text,
story_context=story_context,
baml_options={"tb": tb}
)
if locations:
primary_location = locations[0].model_dump()
location_uuid = entity_registry.register_entity('locations', primary_location)
metadata["location"] = location_uuid
return metadata
async def extract_scene_events(
scene_text: str,
story_context: str,
scene_number: int,
known_agent_uuids: List[str],
known_object_uuids: List[str],
tb: TypeBuilder
) -> List[Dict]:
"""Extract events from a scene."""
events_extracted = await b.ExtractEvents(
scene_text=scene_text,
story_context=story_context,
scene_number=scene_number,
known_agents=known_agent_uuids,
known_objects=known_object_uuids,
baml_options={"tb": tb}
)
events = [ev.model_dump() for ev in events_extracted]
for event in events:
event['uuid'] = f"event-{scene_number}-{event['sequence_within_scene']}"
return events
async def extract_agent_participations(
scene_text: str,
story_context: str,
events: List[Dict],
entity_registry: EntityRegistry,
tb: TypeBuilder
) -> List[Dict]:
"""Extract agent participations for events."""
registry_agents = [v for v in entity_registry.agents.values()]
agent_parts_extracted = await b.ExtractAgentParticipations(
scene_text=scene_text,
story_context=story_context,
events=events,
agents=registry_agents,
baml_options={"tb": tb}
)
agent_participations = []
for p in agent_parts_extracted:
d = p.model_dump()
agent_uuid = entity_registry.resolve_reference('agents', d['agent'])
if agent_uuid:
d['agent'] = agent_uuid
d['uuid'] = f"participation-{agent_uuid}-{d['event']}"
agent_participations.append(d)
else:
logger.warning(f"Skipping invalid agent participation for '{d['agent']}'")
return agent_participations
async def extract_object_involvements(
scene_text: str,
story_context: str,
events: List[Dict],
entity_registry: EntityRegistry,
tb: TypeBuilder
) -> List[Dict]:
"""Extract object involvements for events."""
registry_objects = [v for v in entity_registry.objects.values()]
obj_invs_extracted = await b.ExtractObjectInvolvements(
scene_text=scene_text,
story_context=story_context,
events=events,
objects=registry_objects,
baml_options={"tb": tb}
)
object_involvements = []
for oi in obj_invs_extracted:
d = oi.model_dump()
obj_uuid = entity_registry.resolve_reference('objects', d['object'])
if obj_uuid:
d['object'] = obj_uuid
d['uuid'] = f"involvement-{obj_uuid}-{d['event']}"
object_involvements.append(d)
else:
logger.warning(f"Skipping invalid object involvement for '{d['object']}'")
return object_involvements
def build_scene_output(
metadata: Dict,
events: List[Dict],
agent_participations: List[Dict],
object_involvements: List[Dict],
entity_registry: EntityRegistry
) -> Dict:
"""Build the final scene output structure."""
used_agent_uuids = set()
used_object_uuids = set()
used_location_uuids = set()
used_org_uuids = set()
# Primary location from metadata
if metadata.get("location"):
used_location_uuids.add(metadata["location"])
# Collect references from events
for e in events:
used_agent_uuids.update(e.get('agent_participations', []))
used_object_uuids.update(e.get('object_involvements', []))
if e.get('location'):
used_location_uuids.add(e['location'])
# Collect references from agent_participations
for ap in agent_participations:
used_agent_uuids.add(ap['agent'])
agent_details = entity_registry.get_entity_details('agents', ap['agent'])
if agent_details and agent_details.get('affiliated_org'):
org_uuid = entity_registry.resolve_reference(
'organizations',
agent_details['affiliated_org']
)
if org_uuid:
used_org_uuids.add(org_uuid)
# Collect references from object_involvements
for oi in object_involvements:
used_object_uuids.add(oi['object'])
obj_details = entity_registry.get_entity_details('objects', oi['object'])
if obj_details and obj_details.get('original_owner'):
owner_uuid = entity_registry.resolve_reference(
'agents',
obj_details['original_owner']
)
if owner_uuid:
used_agent_uuids.add(owner_uuid)
return {
"metadata": metadata,
"events": events,
"agents": [
entity_registry.get_entity_details('agents', au)
for au in used_agent_uuids
if entity_registry.get_entity_details('agents', au)
],
"objects": [
entity_registry.get_entity_details('objects', ou)
for ou in used_object_uuids
if entity_registry.get_entity_details('objects', ou)
],
"locations": [
entity_registry.get_entity_details('locations', lu)
for lu in used_location_uuids
if entity_registry.get_entity_details('locations', lu)
],
"organizations": [
entity_registry.get_entity_details('organizations', ou)
for ou in used_org_uuids
if entity_registry.get_entity_details('organizations', ou)
],
"agent_participations": agent_participations,
"object_involvements": object_involvements,
}
def format_dialogue(
dialogues: List[Dict[str, str]],
scene_number: int,
scene_location: Optional[str] = None
) -> str:
formatted_lines = [f"(Scene Number: {scene_number})"]
if scene_location:
formatted_lines.append(f"Location: {scene_location}")
for dialogue in dialogues:
if "Stage Direction" in dialogue:
formatted_lines.append(f"[{dialogue['Stage Direction']}]")
elif "Character" in dialogue and "Line" in dialogue:
formatted_lines.append(f"{dialogue['Character']}: {dialogue['Line']}")
return "\n".join(formatted_lines)
----- File: ./main.py -----
# main.py
import asyncio
import logging
from pathlib import Path
from typing import Dict, List, Optional, Set, Union
from baml_client.type_builder import TypeBuilder
from baml_client import b
from thefuzz import fuzz
from entity_registry import EntityRegistry
from entity_normalizer import EntityNormalizer
from entity_extractors import extract_and_register_entities
from scene_processor import process_scene, format_dialogue
from utils import (
load_json,
save_json,
load_and_concatenate_context,
setup_logging,
validate_file_paths,
create_backup,
Timer
)
from post_processor import (
clean_entity_references,
clean_scene_references,
update_event_involvements
)
from entity_cleaners import (
clean_agent_data,
clean_object_data,
clean_location_data,
clean_organization_data,
clean_event_data
)
# Constants
INPUT_JSON_PATH = Path("source_docs/ai_fanfic/doctor_who/quantum_archive_transcript.json")
CONTEXT_FILES = [
Path("ssource_docs/ai_fanfic/doctor_who/quantum_archive_novelization.txt")
]
OUTPUT_JSON_PATH = Path("output/pre_processed/quantum_archive_graph.json")
# INPUT_JSON_PATH = Path("source_docs/ai_fanfic/west_wing/fault_lines_transcript.json")
# CONTEXT_FILES = [
# Path("source_docs/ai_fanfic/west_wing/fault_lines_novelization.txt")
# ]
# OUTPUT_JSON_PATH = Path("output/pre_processed/fault_lines_graph.json")
# INPUT_JSON_PATH = Path("source_docs/ai_fanfic/peep_show/networking_event_transcript.json")
# CONTEXT_FILES = [
# Path("source_docs/ai_fanfic/peep_show/networking_event_treatment.txt")
# ]
# OUTPUT_JSON_PATH = Path("output/pre_processed/networking_event_graph.json")
# INPUT_JSON_PATH = Path("source_docs/ai_fanfic/star_trek_tng/echoes_of_the_past_transcript.json")
# CONTEXT_FILES = [
# Path("source_docs/ai_fanfic/star_trek_tng/echoes_of_the_past_treatment.txt")
# ]
# OUTPUT_JSON_PATH = Path("output/pre_processed/echoes_of_the_pastA.json")
# INPUT_JSON_PATH = Path("source_docs/doctor_who/doctor10/json/blink_transcript.json")
# CONTEXT_FILES = [
# Path("source_docs/doctor_who/doctor10/resource/txt/blink_summary.txt")
# ]
# OUTPUT_JSON_PATH = Path("output/pre_processed/blink_extracted.json")
# INPUT_JSON_PATH = Path("source_docs/doctor_who/doctor1/json/mission_to_the_unknown_transcript.json")
# CONTEXT_FILES = [
# Path("source_docs/doctor_who/doctor1/resource/novel/mission_to_the_unknown_novel.txt")
# ]
# OUTPUT_JSON_PATH = Path("output/pre_processed/mission_to_the_unknown_graph.json")
LOG_DIR = Path("logs")
logger = logging.getLogger(__name__)
async def process_episode(
episode_data: Dict,
story_context: str,
entity_registry: EntityRegistry,
tb: TypeBuilder,
known_agent_uuids: List[str],
known_object_uuids: List[str]
) -> Dict:
"""Process a single episode."""
logger.info(f"Processing episode: {episode_data.get('Episode', 'Unknown Episode')}")
scenes = episode_data.get("Scenes", [])
processed_scenes = []
for i, scene in enumerate(scenes):
scene_number = i + 1
next_scene_uuid = f"scene-{scene_number+1:03}" if scene_number < len(scenes) else None
# Extract scene location here
scene_location = scene.get("Scene", "Unknown Location")
processed_scene = await process_scene(
scene,
story_context,
scene_number,
next_scene_uuid=next_scene_uuid,
entity_registry=entity_registry,
tb=tb,
known_agent_uuids=known_agent_uuids,
known_object_uuids=known_object_uuids
)
processed_scenes.append(processed_scene)
return {
"episode_title": episode_data.get("Episode"),
"scenes": processed_scenes
}
async def first_pass_extraction(
story_json: Dict,
story_context: str,
entity_registry: EntityRegistry,
tb: TypeBuilder
) -> None:
"""First pass: extract all entities across all scenes."""
scene_number = 1 # Initialize to 1
for episode in story_json.get("Episodes", []):
for scene in episode.get("Scenes", []):
logger.info(f"First pass processing scene {scene_number}")
scene_text = format_dialogue(
scene.get("Dialogue", []),
scene_number,
scene.get("Scene", "Unknown Location")
)
await extract_and_register_entities(
scene,
scene_text,
story_context,
entity_registry,
tb
)
scene_number += 1
entity_registry.debug_registry()
async def second_pass_processing(
story_json: Dict,
story_context: str,
entity_registry: EntityRegistry,
tb: TypeBuilder
) -> List[Dict]:
"""Second pass: process episodes in detail."""
logger.info("Second pass: processing episodes in detail")
processed_episodes = []
for ep in story_json.get("Episodes", []):
# Extract agent and object UUIDs
known_agent_uuids = [agent["uuid"] for agent in entity_registry.agents.values()]
known_object_uuids = [object["uuid"] for object in entity_registry.objects.values()]
processed_episodes.append(
await process_episode(
ep,
story_context,
entity_registry,
tb,
known_agent_uuids=known_agent_uuids,
known_object_uuids=known_object_uuids
)
)
return processed_episodes
def build_final_output(
story_json: Dict,
processed_episodes: List[Dict],
entity_registry: EntityRegistry
) -> Dict:
"""Build the final output structure."""
return {
"serial": story_json.get("Story", "Untitled Serial"),
"episodes": processed_episodes,
"entity_registry": {
"agents": entity_registry.agents,
"objects": entity_registry.objects,
"locations": entity_registry.locations,
"organizations": entity_registry.organizations,
}
}
async def process_story(story_json: Dict, story_context: str) -> Dict:
"""Process entire story, managing the two-pass approach with enhanced entity handling."""
logger.info(f"Processing story: {story_json.get('Story', 'Untitled Serial')}")
entity_registry = EntityRegistry()
tb = TypeBuilder()
# First pass: gather entities
logger.info("First pass: extracting & registering global entities")
await first_pass_extraction(story_json, story_context, entity_registry, tb)
# Post first-pass processing
logger.info("Processing entities after first pass")
merge_duplicate_entities(entity_registry) # This merges agents, objects, locations
# Second pass: process episodes in detail
logger.info("Second pass: processing episodes in detail")
processed_episodes = await second_pass_processing(
story_json,
story_context,
entity_registry,
tb