
    i                     .   U d Z ddlZddlmZmZmZmZ ddhdhdhddhdZeeee	   f   e
d<   d	ed
ededee	ee	   f   fdZd	edee	ee	   f   deee	      fdZdeee	ef      dee	ee	ef   f   deeee   f   fdZdedeeee   f   deee      fdZy)u  엔티티/씬 이미지 생성 순서 결정 — 시각적 의존성 기반.

Visual dependency graph를 구축하여 엔티티 참조 이미지를
올바른 순서로 생성하고, 독립적인 엔티티는 병렬로 처리한다.

씬 이미지도 동일한 토폴로지 정렬을 사용하여 같은 배경을
공유하는 씬은 순차 처리, 독립 씬은 병렬 처리한다.
    N)AnyDictListSetidentitytransformation
possession))	characterr
   )r
   prop)r   r
   )locationr   VISUAL_REFERENCE_RULESentities	relationsparticipantsreturnc                 P   | D ci c]  }|d   |d    }}| D ci c]  }|d   t                }}i }|D ]&  }|j                  |d   g       j                  |       ( |D ]  }|j                  |d   g       }	t	        |	      dk  r'|d   }
t        |	      D ]  \  }}|	|dz   d D ]o  }|d   |d   }}||vs||vr||   ||   }}||f}||f}t        j                  |      xs t        j                  |      }|sW|
|v s\||   j                  |       q   |S c c}w c c}w )	au  Build dependency graph based on visual reference rules only.

    Args:
        entities: list of dicts with at least {"id", "entity_type"}.
        relations: list of dicts with {"id", "relation_family"}.
        participants: list of dicts with {"relation_id", "canon_id"}.

    Returns:
        {entity_id: set of entity_ids it depends on (must be generated first)}
    identity_typerelation_id   relation_family   Ncanon_id)set
setdefaultappendgetlen	enumerater   add)r   r   r   eentity_typesdeps	rel_partsprelpartsfamilyip1p2id1id2type1type2	type_pairtype_pair_revalloweds                        S/Users/manta/Documents/Projects/TheRoad-I1/backend/app/modules/entity_dependency.pybuild_visual_dependency_graphr4      sw    HP#Px!AdGQ}-=$=xL#P9A BA4#%D B "$IQ}-r299!<  c$i,u:>&'u%EArAEGnj>2j>Sl*c.E+C0,s2Cu"EN	!&044 ?+//>  v0 IMM#&! % & 4 KE $Q Bs
   DD#r#   c                    | D ch c]  }|d   	 }}t               }g }|rg }t        |      D ]?  }|j                  |t                     }|j                  |      s/|j	                  |       A |s|j	                  t        |             	 |S |j	                  |       |j                  |       |t        |      z  }|r|S c c}w )a\  Topological sort into batches (each batch can run in parallel).

    Args:
        entities: list of dicts with at least {"id"}.
        deps: dependency graph from build_visual_dependency_graph().

    Returns:
        List of batches.  Each batch is a list of entity IDs whose
        dependencies have all been completed in earlier batches.
    r   )r   sortedr   issubsetr   update)	r   r#   r!   	remaining	completedbatchesreadyeidentity_depss	            r3   topological_sort_entitiesr?   Q   s     -55Hq1T7HI5%I!G
)$C((3.K##I.S! %
 NN6),- N	 	uSZ	 " N+ 6s   Cstillsentity_lookupc                 .   t        t        |             D ci c]  }|t                }}i }t        |       D ]2  \  }}	 t	        j
                  |j                  dd            }g }|D ]  }t        |t              r&|j                  d      xs |j                  dd      }	nt        |t              r|}	nM|j                  |	      }
|
sa|
j                  d      dk(  sv|j                  |	        |D ]"  }||v r||   j                  ||          |||<   $ |j                  d      }|st        |       D ]0  \  }}|j                  d      |k(  s||   j                  |        2 5 |S c c}w # t        j                  t        f$ r g }Y .w xY w)	a  Build scene dependency graph based on shared background locations.

    Scenes sharing the same location must be generated sequentially
    (for visual continuity from previous scene reference). Scenes at
    independent locations can be generated in parallel.

    Args:
        stills: list of still dicts (ordered by still_index).
            Each must have "visible_entities_json".
        entity_lookup: entity_id -> entity dict (with "entity_type").

    Returns:
        {scene_index: set of scene_indices it depends on}
    visible_entities_jsonz[]r   	entity_id r   r   dependent_scene_id)ranger   r   r   jsonloadsr   JSONDecodeError	TypeError
isinstancedictstrr   r    )r@   rA   sir#   location_to_latest_scene
still_datavisible_idslocation_idsvr=   entityloc_iddep_scene_idsjothers                  r3   build_scene_dependency_graphrZ   z   s   $ 6;3v;5G H5GrSU5GD H/1#F+J	**Z^^4KT%RSK #%A!T"eeDk;QUU;%;As#"&&s+F&**]3zA##C(  #F11R5f=>/1$V, # "~~&:;&v.	E99T?l2HLL$ /; ,D KK !I $$i0 	K	s   E0 %E55FFscene_countc                    t        t        |             }t               }g }|rg }t        |      D ]?  }|j                  |t                     }|j	                  |      s/|j                  |       A |s|j                  t        |             	 |S |j                  |       |j                  |       |t        |      z  }|r|S )a[  Topological sort scene indices into batches for concurrent generation.

    Args:
        scene_count: total number of scenes.
        deps: dependency graph from build_scene_dependency_graph().

    Returns:
        List of batches. Each batch is a list of scene indices whose
        dependencies have all been completed in earlier batches.
    )r   rG   r6   r   r7   r   r8   )r[   r#   r9   r:   r;   r<   rO   
scene_depss           r3   topological_sort_scenesr^      s     eK01I%I!G
#B"ce,J""9-R  $
 NN6),- N	 	uSZ	   N    )__doc__rH   typingr   r   r   r   r   tuplerN   __annotations__listr4   r?   intrZ   r^    r_   r3   <module>rg      s:    ' ' ",-= >(>(>/<1 UCH_- 111 1 
#s3x-	1h##
sCH}
# 
$s)_#R7c3h 7T#s(^+,7 
#s3x-7t""
sCH}
" 
$s)_"r_   