
    Oj                         d Z ddlZddlZddlmZmZmZmZ ddlm	Z	  ej                  e      Z G d d      Z G d dee	      Z G d	 d
ee	      Z G d dee	      Zy)u`   요약 Phase StepRunner — episode_summary, visual_world_rules, scene_summary, project_summary.    N)AnyDictListOptional)
StepRunnerc                   :    e Zd ZdefdZdefdZdedee   fdZy)_SummaryStepMixinreturnc                 L   ddl m} ddlm} | j                  j                  |      j                   ||j                              j                  |j                  | j                  k(        j                         }|r|j                  sddlm}  |ddd      |j                  S )	Nr   Episode)undeferAppErrorzstep.no_fulltextu'   시나리오 텍스트가 없습니다.  codemessagestatus_code)app.models.projectr   sqlalchemy.ormr   dbqueryoptionsfulltextfilterid
episode_idfirstapp.core.errorsr   )selfr   r   epr   s        R/Users/manta/Documents/Projects/TheRoad-I1/backend/app/core/steps/summary_steps.py_load_fulltextz _SummaryStepMixin._load_fulltext   s    .*WW]]7#++GG4D4D,EFMMJJ$//)

%' 	 0 2<esvww{{    c                     | j                  d      }|r)|j                  di       j                  d      r|d   d   S | j                         S )u:   text_cleanup 결과가 있으면 사용, 없으면 원본.text_cleanupdatacleaned_text)_load_prev_checkpointgetr$   )r!   cps     r#   _load_cleaned_textz$_SummaryStepMixin._load_cleaned_text   sK    ''7"&&$((8f:n--""$$r%   step_idc                     ddl m} ddlm}  ||j                        | j
                  z  dz  dz  | j                  z  |z  dz  }|j                         r%t        j                  |j                  d            S y )	Nr   )Pathsettingscheckpointsepisodeszmanifest.jsonzutf-8)encoding)pathlibr0   app.core.configr2   projects_dir
project_idr   existsjsonloads	read_text)r!   r.   r0   r2   r,   s        r#   r*   z'_SummaryStepMixin._load_prev_checkpoint   sp     ,(''(4??:]JZWZ^ZiZiilss  wF  F99;::bllGl<==r%   N)	__name__
__module____qualname__strr$   r-   r   r   r*    r%   r#   r	   r	      s1    	 	%C %S Xd^ r%   r	   c                   (    e Zd ZdZddeeef   fdZy)EpisodeSummaryStepu%   Step 3: 에피소드 요약 (500자).r
   c                    | j                         }ddlm} ddlm}  |||j
                  | j                  | j                               }ddlm	} | j                  j                  |      j                  |j                  | j                  k(        j                         }|r1|j!                  dd      |_        | j                  j%                          ddd|d	S )
Nr   r1   )summarize_episode)r   
max_lengthproject_configopik_metadatar   summary    completed_countapplicable_countfailed_countr(   )r-   r7   r2   'app.modules.pipeline.episode_summarizerrF   max_episode_summary_lengthrH   build_opik_metadatar   r   r   r   r   r   r   r   r+   rJ   commit)r!   moder   r2   rF   resultr   r"   s           r#   _executezEpisodeSummaryStep._execute+   s    **,,M"::..224	
 	/WW]]7#**7::+HIOOQIr2BJGGNN  ! !	
 	
r%   Nresume)r>   r?   r@   __doc__r   rA   r   rW   rB   r%   r#   rD   rD   (   s    /
c3h 
r%   rD   c                   ,    e Zd ZdZddedeeef   fdZy)VisualWorldRulesStepu3  Step 4: 시각적 세계관 규칙 추출.

    입력:
        - text_cleanup 체크포인트 (정리된 텍스트)
        - episode_summary 체크포인트 (에피소드 요약)

    출력:
        - rules: 시각적 규칙 목록
        - era: 시대 배경
        - region: 지역/국가 배경
    rU   r
   c                    | j                         }d}| j                  d      }|r)|j                  di       j                  d      r|d   d   }ddlm}  || j
                  | j                  | j                        }|j                  dd      |j                  d	d
      z   |j                  dd      z   }ddl	m
}  ||||z   | j                  | j                  dg            }	ddlm}
  |
|	| j                        }	t        |	j                  dg             }|	j                  dd      }|	j                  dd      }t         j#                  d||||j$                         ddd|	dS )NrK   episode_summaryr(   rJ   r   )get_planning_contextworld_settingu   ## 기획서: 세계관	tone_moodu   ## 기획서: 톤/분위기visual_conceptsu   ## 기획서: 비주얼 컨셉)extract_visual_rulesvisual_world_rules
extra_tags)r   r^   rH   rI   )apply_declared_coordinatesruleseraregionzBVisualWorldRulesStep: %d rules, era=%s, region=%s, planning_doc=%srL   rM   )r-   r*   r+   app.core.planning_doc_contextr_   r9   r   r   inject_if_available'app.modules.pipeline.visual_world_rulesrc   rH   rS   *app.modules.pipeline.grounding_coordinatesrg   lenloggerinfohas_planning_doc)r!   rU   r   r^   ep_cpr_   pctxplanning_supplementrc   rV   rg   rules_countri   rj   s                 r#   rW   zVisualWorldRulesStep._executeT   ss   **, **+<=UYYvr*..y9#FmI6O 	G#DOOT__dggN$$_6OP&&{4QRS&&'8:Z[\ 	 	Q%+.AA..22?S>T2U	
 	Z+FD4G4GH&**Wb12jj#Hb)Pfd&;&;	
  ! !	
 	
r%   NrX   r>   r?   r@   rZ   rA   r   r   rW   rB   r%   r#   r\   r\   G   s"    
2
S 2
S#X 2
r%   r\   c                   ,    e Zd ZdZddedeeef   fdZy)SceneSummaryStepuu  Step 7: 씬별 요약 (병렬 ThreadPool).

    입력:
        - scene_save 체크포인트 (segments)
        - text_cleanup 체크포인트 (정리된 텍스트)
        - episode_summary 체크포인트 (에피소드 요약)
        - visual_world_rules 체크포인트 (시각적 규칙)

    출력:
        - scene_summaries: [{scene_index, scene_summary}, ...]
    rU   r
   c           	         | j                  d      }|r!|j                  di       j                  d      sddlm}  |ddd	      |d   d   }d
}| j                  d      }|r)|j                  di       j                  d      r|d   d   }d
}| j                  d      }|r@|j                  d      r/|d   j                  dg       }	|	rdj	                  d |	D              }ddlm}
  |
|||| j                  | j                  dg            }t        d |D              }t        |      }||z
  }t        j                  d|||       |||d|idS )N
scene_saver(   segmentsr   r   zstep.no_inputu<   씬 저장 결과 없음 (scene_save 체크포인트 필요)r   r   rK   r^   rJ   rd   rh   
c              3   l   K   | ],  }d |j                  dd       d|j                  dd        . yw)z- [	rule_typerK   z] descriptionNr+   ).0rs     r#   	<genexpr>z,SceneSummaryStep._execute.<locals>.<genexpr>   s=      )' !%%R01AEE-4L3MN's   24)summarize_scenesscene_summaryre   )r|   r^   visual_rulesrH   rI   c              3   D   K   | ]  }|j                  d       sd  yw)r   rL   Nr   )r   ss     r#   r   z,SceneSummaryStep._execute.<locals>.<genexpr>   s     M?aaeeO6L?s     z5SceneSummaryStep: %d/%d scenes summarized (%d failed)	summariesrM   )r*   r+   r    r   join%app.modules.pipeline.scene_summarizerr   rH   rS   sumro   rp   rq   )r!   rU   scene_cpr   r|   r^   rs   r   vw_cp
rules_listr   scene_summaries	completedtotalfaileds                  r#   rW   zSceneSummaryStep._execute   s   --l;x||FB7;;JG0$V 
  (/
; **+<=UYYvr*..y9#FmI6O **+?@UYYv&v**7B7J#yy )')   	K*+%..22>O2P
 M?MM	H"Cuf	
  ) %" /2	
 	
r%   NrX   rw   rB   r%   r#   ry   ry      s"    
6
S 6
S#X 6
r%   ry   )rZ   r;   loggingtypingr   r   r   r   app.core.step_runnerr   	getLoggerr>   rp   r	   rD   r\   ry   rB   r%   r#   <module>r      sc    f   , , +			8	$ 8
*J 
>?
,j ?
DC
(* C
r%   