mgbam commited on
Commit
a4d9a11
·
verified ·
1 Parent(s): 2d90be5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +442 -314
app.py CHANGED
@@ -1,340 +1,468 @@
1
- # app.py
2
- import streamlit as st
 
 
 
3
  import os
 
 
 
 
 
4
  import logging
5
 
6
- # --- Streamlit PermissionError Mitigation Attempts ---
7
- if "STREAMLIT_CLIENT_GATHER_USAGE_STATS" not in os.environ:
8
- os.environ["STREAMLIT_CLIENT_GATHER_USAGE_STATS"] = "false"
9
- if "STREAMLIT_BROWSER_GATHERUSAGESTATS" not in os.environ: # For newer versions
10
- os.environ["STREAMLIT_BROWSER_GATHERUSAGESTATS"] = "false"
11
- streamlit_home_path_app = "/app/.streamlit_cai_config_v3"
12
- if "STREAMLIT_HOME" not in os.environ and os.getcwd().startswith("/app"):
13
- os.environ["STREAMLIT_HOME"] = streamlit_home_path_app
14
- try: os.makedirs(streamlit_home_path_app, exist_ok=True)
15
- except Exception: pass
16
 
17
- from core.gemini_handler import GeminiHandler
18
- from core.visual_engine import VisualEngine
19
- from core.prompt_engineering import (
20
- create_cinematic_treatment_prompt, construct_dalle_prompt,
21
- construct_text_to_video_prompt_for_gen4, create_narration_script_prompt_enhanced,
22
- create_scene_regeneration_prompt, create_visual_regeneration_prompt
23
- )
 
24
 
25
- st.set_page_config(page_title="CineGen AI Ultra+", layout="wide", initial_sidebar_state="expanded")
26
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s [%(levelname)s] - %(message)s (%(module)s.%(funcName)s:%(lineno)d)')
27
  logger = logging.getLogger(__name__)
 
28
 
29
- SHOT_TYPES_OPTIONS = [ "Director's Choice", "Establishing Shot", "Long Shot", "Full Shot", "Medium Long Shot (Cowboy)", "Medium Shot", "Medium Close-up", "Close-up", "Extreme Close-up", "Point of View (POV)", "Over the Shoulder", "Tracking Shot", "Dolly Zoom", "Crane Shot", "Aerial Shot", "Static Shot", "Dutch Angle", "Whip Pan"]
30
- DEFAULT_SCENE_DURATION_SECS = 5; DEFAULT_SHOT_TYPE = "Director's Choice"; ASSET_TYPE_OPTIONS = ["Auto (Director's Choice)", "Image", "Video Clip"]
 
 
 
 
 
31
 
32
- def load_api_key(key_name_st, key_name_e, service_n):
33
- key_val = None; secrets_avail = hasattr(st, 'secrets')
34
- try:
35
- if secrets_avail and key_name_st in st.secrets: key_val = st.secrets.get(key_name_st);
36
- if key_val: logger.info(f"API Key for {service_n} found in Streamlit secrets.")
37
- except Exception as e: logger.warning(f"No st.secrets for {key_name_st} ({service_n}): {e}")
38
- if not key_val and key_name_e in os.environ: key_val = os.environ.get(key_name_e);
39
- if key_val: logger.info(f"API Key for {service_n} found in env var '{key_name_e}'.")
40
- if not key_val: logger.warning(f"API Key for {service_n} (Key: {key_name_st}/{key_name_e}) NOT FOUND.")
41
- return key_val
42
 
43
- if 'services_initialized_flag' not in st.session_state:
44
- logger.info("APP_INIT: Initializing services and API keys...")
45
- st.session_state.API_KEY_GEMINI = load_api_key("GEMINI_API_KEY", "GEMINI_API_KEY", "Gemini")
46
- st.session_state.API_KEY_OPENAI = load_api_key("OPENAI_API_KEY", "OPENAI_API_KEY", "OpenAI/DALL-E")
47
- st.session_state.API_KEY_ELEVENLABS = load_api_key("ELEVENLABS_API_KEY", "ELEVENLABS_API_KEY", "ElevenLabs")
48
- st.session_state.API_KEY_PEXELS = load_api_key("PEXELS_API_KEY", "PEXELS_API_KEY", "Pexels")
49
- st.session_state.CONFIG_ELEVENLABS_VOICE_ID = load_api_key("ELEVENLABS_VOICE_ID", "ELEVENLABS_VOICE_ID", "ElevenLabs Voice ID")
50
- st.session_state.API_KEY_RUNWAYML = load_api_key("RUNWAY_API_KEY", "RUNWAY_API_KEY", "RunwayML")
51
- if not st.session_state.API_KEY_GEMINI: st.error("CRITICAL: Gemini API Key missing!"); logger.critical("Gemini API Key missing."); st.stop()
52
- try: st.session_state.gemini_service_handler = GeminiHandler(api_key=st.session_state.API_KEY_GEMINI); logger.info("GeminiHandler initialized.")
53
- except Exception as e: st.error(f"CRITICAL: GeminiHandler init fail: {e}"); logger.critical(f"GeminiHandler init fail: {e}", exc_info=True); st.stop()
54
- try:
55
- el_def_voice = "Rachel"; el_res_voice_id = st.session_state.CONFIG_ELEVENLABS_VOICE_ID or el_def_voice
56
- st.session_state.visual_content_engine = VisualEngine(output_dir="temp_cinegen_media", default_elevenlabs_voice_id=el_res_voice_id)
57
- st.session_state.visual_content_engine.set_openai_api_key(st.session_state.API_KEY_OPENAI)
58
- st.session_state.visual_content_engine.set_elevenlabs_api_key(st.session_state.API_KEY_ELEVENLABS, voice_id_from_secret=st.session_state.CONFIG_ELEVENLABS_VOICE_ID)
59
- st.session_state.visual_content_engine.set_pexels_api_key(st.session_state.API_KEY_PEXELS)
60
- st.session_state.visual_content_engine.set_runway_api_key(st.session_state.API_KEY_RUNWAYML)
61
- logger.info("VisualEngine initialized and keys set.")
62
- except Exception as e: st.error(f"CRITICAL: VisualEngine init fail: {e}"); logger.critical(f"VisualEngine init fail: {e}", exc_info=True); st.warning("VisualEngine critical setup issue."); st.stop()
63
- st.session_state.services_initialized_flag = True; logger.info("APP_INIT: Service initialization complete.")
64
 
65
- PROJECT_SS_DEFAULTS = {'project_story_treatment_scenes_list':[],'project_scene_generation_prompts_list':[],'project_generated_assets_info_list':[],'project_final_video_path':None,'project_character_definitions_map':{},'project_global_style_keywords_str':"",'project_overall_narration_audio_path':None,'project_narration_script_text':""}
66
- for k_ss, def_v_ss in PROJECT_SS_DEFAULTS.items():
67
- if k_ss not in st.session_state: st.session_state[k_ss] = def_v_ss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- def initialize_new_project_data_in_session():
70
- st.session_state.project_story_treatment_scenes_list = []; st.session_state.project_scene_generation_prompts_list = []; st.session_state.project_generated_assets_info_list = []
71
- st.session_state.project_final_video_path = None; st.session_state.project_overall_narration_audio_path = None; st.session_state.project_narration_script_text = ""
72
- logger.info("PROJECT_DATA: New project data re-initialized.")
 
73
 
74
- def generate_asset_for_scene_in_app(sc_idx, sc_data_dict, asset_v=1, user_asset_type_ui="Auto (Director's Choice)"):
75
- logger.debug(f"APP: generate_asset_for_scene_in_app for S_idx {sc_idx}, ver {asset_v}, user_type: {user_asset_type_ui}")
76
- gen_as_vid_final = False; gemini_sugg_type = sc_data_dict.get('suggested_asset_type_감독', 'image').lower()
77
- if user_asset_type_ui=="Image": gen_as_vid_final=False
78
- elif user_asset_type_ui=="Video Clip": gen_as_vid_final=True
79
- elif user_asset_type_ui=="Auto (Director's Choice)": gen_as_vid_final=(gemini_sugg_type=="video_clip")
80
- logger.debug(f"APP: Final asset type: {'Video' if gen_as_vid_final else 'Image'}")
81
- prompt_base_img = construct_dalle_prompt(sc_data_dict,st.session_state.project_character_definitions_map,st.session_state.project_global_style_keywords_str)
82
- prompt_motion_vid = ""
83
- if gen_as_vid_final: prompt_motion_vid=construct_text_to_video_prompt_for_gen4(sc_data_dict,st.session_state.project_global_style_keywords_str) or sc_data_dict.get('video_clip_motion_description_감독',"subtle motion")
84
- if not prompt_base_img: logger.error(f"Base image prompt construction failed for S{sc_data_dict.get('scene_number',sc_idx+1)}"); return False
85
- while len(st.session_state.project_scene_generation_prompts_list)<=sc_idx:st.session_state.project_scene_generation_prompts_list.append("")
86
- while len(st.session_state.project_generated_assets_info_list)<=sc_idx:st.session_state.project_generated_assets_info_list.append(None)
87
- st.session_state.project_scene_generation_prompts_list[sc_idx]=prompt_motion_vid if gen_as_vid_final else prompt_base_img
88
- fn_base_asset=f"scene_{sc_data_dict.get('scene_number',sc_idx+1)}_asset_v{asset_v}"
89
- rwy_dur=sc_data_dict.get('video_clip_duration_estimate_secs_감독',sc_data_dict.get('user_scene_duration_secs',DEFAULT_SCENE_DURATION_SECS));rwy_dur=max(1,rwy_dur)
90
- asset_res_dict=st.session_state.visual_content_engine.generate_scene_asset(image_generation_prompt_text=prompt_base_img,motion_prompt_text_for_video=prompt_motion_vid,scene_data_dict=sc_data_dict,scene_identifier_fn_base=fn_base_asset,generate_as_video_clip_flag=gen_as_vid_final,runway_target_dur_val=rwy_dur)
91
- st.session_state.project_generated_assets_info_list[sc_idx]=asset_res_dict
92
- if asset_res_dict and asset_res_dict.get('prompt_used')and st.session_state.project_scene_generation_prompts_list[sc_idx]!=asset_res_dict['prompt_used']:st.session_state.project_scene_generation_prompts_list[sc_idx]=asset_res_dict['prompt_used']
93
- if asset_res_dict and not asset_res_dict['error']and asset_res_dict.get('path')and os.path.exists(asset_res_dict['path']):logger.info(f"APP: Asset ({asset_res_dict.get('type')}) OK S{sc_data_dict.get('scene_number',sc_idx+1)}:{os.path.basename(asset_res_dict['path'])}");return True
94
- else:err_msg=asset_res_dict.get('error_message','Unk err')if asset_res_dict else 'Asset res None';logger.warning(f"APP: Asset gen FAIL S{sc_data_dict.get('scene_number',sc_idx+1)}. Type:{'Vid'if gen_as_vid_final else 'Img'}. Err:{err_msg}");curr_p=st.session_state.project_scene_generation_prompts_list[sc_idx];st.session_state.project_generated_assets_info_list[sc_idx]={'path':None,'type':'none','error':True,'error_message':err_msg,'prompt_used':curr_p};return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- with st.sidebar:
97
- if os.path.exists("assets/logo.png"): st.image("assets/logo.png", width=150)
98
- else: st.sidebar.markdown("## 🎬 CineGen AI Ultra+"); logger.warning("assets/logo.png not found.")
99
- st.markdown("### Creative Seed")
100
- sb_user_idea = st.text_area("Core Idea:", "Lone wanderer, mythical oasis...", height=100, key="sb_user_idea_u")
 
 
 
 
 
 
101
 
102
- # <<< EXPANDED GENRE AND MOOD LISTS >>>
103
- genres_list = [
104
- "Sci-Fi (General)", "Cyberpunk", "Space Opera", "Post-Apocalyptic", "Dystopian", "Biopunk", "Steampunk",
105
- "Fantasy (General)", "High Fantasy", "Urban Fantasy", "Dark Fantasy", "Mythological", "Sword and Sorcery",
106
- "Horror (General)", "Supernatural Horror", "Psychological Horror", "Cosmic Horror", "Slasher", "Found Footage", "Body Horror", "Folk Horror",
107
- "Thriller (General)", "Psychological Thriller", "Crime Thriller", "Mystery", "Noir", "Techno-thriller",
108
- "Action (General)", "Adventure", "Spy Fiction", "Martial Arts", "Heist", "Disaster",
109
- "Drama (General)", "Historical Drama", "Biographical", "Coming-of-Age", "Family Drama", "Legal Drama", "Medical Drama", "Political Drama",
110
- "Romance (General)", "Romantic Comedy", "Historical Romance",
111
- "Comedy (General)", "Satire", "Dark Comedy", "Slapstick", "Mockumentary", "Parody",
112
- "Western (General)", "Revisionist Western", "Spaghetti Western",
113
- "Animation (Specify Style)", "Experimental", "Surreal", "Documentary Style", "Musical"
114
- ]
115
- default_genre_index = genres_list.index("Post-Apocalyptic") if "Post-Apocalyptic" in genres_list else 0
116
- sb_genre = st.selectbox("Genre:", genres_list, index=default_genre_index, key="sb_genre_u")
117
 
118
- moods_list = [
119
- "Hopeful yet Desperate", "Mysterious & Eerie", "Gritty & Tense", "Dark & Brooding", "Bleak & Nihilistic",
120
- "Epic & Awe-Inspiring", "Melancholy & Reflective", "Whimsical & Lighthearted", "Playful & Energetic",
121
- "Suspenseful & Unsettling", "Romantic & Passionate", "Tragic & Somber", "Heartwarming & Sentimental",
122
- "Action-Packed & Exciting", "Comedic & Absurdist", "Satirical & Ironic", "Cynical",
123
- "Nostalgic & Bittersweet", "Surreal & Dreamlike", "Inspiring & Uplifting", "Triumphant",
124
- "Quiet & Contemplative", "Ominous & Foreboding", "Chaotic & Frenetic", "Peaceful & Serene"
125
- ]
126
- default_mood_index = moods_list.index("Hopeful yet Desperate") if "Hopeful yet Desperate" in moods_list else 0
127
- sb_mood = st.selectbox("Mood:", moods_list, index=default_mood_index, key="sb_mood_u")
128
- # <<< END EXPANDED LISTS >>>
129
 
130
- sb_num_scenes = st.slider("Key Scenes:", 1, 10, 1, key="sb_num_scenes_u")
131
- sb_guidance_opts = {"Standard": "standard", "Artistic": "more_artistic", "Experimental": "experimental_narrative"}
132
- sb_guidance_key = st.selectbox("AI Director Style:", list(sb_guidance_opts.keys()), key="sb_guidance_u")
133
- sb_actual_guidance = sb_guidance_opts[sb_guidance_key]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
- if st.button("🌌 Generate Cinematic Treatment", type="primary", key="sb_btn_gen_treat_u", use_container_width=True):
136
- initialize_new_project_data_in_session()
137
- if not sb_user_idea.strip(): st.warning("Please provide a story idea.")
138
- else:
139
- with st.status("AI Director is envisioning your masterpiece...", expanded=True) as main_status_op:
140
- try:
141
- main_status_op.write("P1: Crafting treatment... 📜"); logger.info("APP: P1 - Treatment Gen.")
142
- prompt_treat = create_cinematic_treatment_prompt(sb_user_idea, sb_genre, sb_mood, sb_num_scenes, sb_actual_guidance)
143
- raw_treat_list = st.session_state.gemini_service_handler.generate_story_breakdown(prompt_treat)
144
- if not isinstance(raw_treat_list, list) or not raw_treat_list: raise ValueError("Gemini invalid scene list.")
145
- init_scenes = []
146
- for scene_g in raw_treat_list:
147
- gem_dur = scene_g.get('video_clip_duration_estimate_secs_감독', 0); scene_g['user_scene_duration_secs'] = gem_dur if gem_dur > 0 else DEFAULT_SCENE_DURATION_SECS
148
- scene_g['user_shot_type'] = scene_g.get('PROACTIVE_camera_work_감독', DEFAULT_SHOT_TYPE); scene_g['user_selected_asset_type'] = "Auto (Director's Choice)"; init_scenes.append(scene_g)
149
- st.session_state.project_story_treatment_scenes_list = init_scenes
150
- num_gen_sc = len(init_scenes); st.session_state.project_scene_generation_prompts_list = [""]*num_gen_sc; st.session_state.project_generated_assets_info_list = [None]*num_gen_sc
151
- logger.info(f"APP: P1 done. {num_gen_sc} scenes."); main_status_op.update(label="Treatment OK! ✅ Assets...", state="running")
152
- main_status_op.write("P2: Creating assets..."); logger.info("APP: P2 - Asset Gen.")
153
- success_assets = 0
154
- for i, scene_item in enumerate(st.session_state.project_story_treatment_scenes_list):
155
- sc_n_log = scene_item.get('scene_number', i+1); main_status_op.write(f" Asset S{sc_n_log}..."); logger.info(f" APP: Asset S{sc_n_log}.")
156
- if generate_asset_for_scene_in_app(i, scene_item, asset_v=1): success_assets += 1
157
- lbl_p2="Assets OK! "; nxt_st="running"
158
- if success_assets==0 and num_gen_sc>0: logger.error("APP:Asset FAIL all.");lbl_p2="Asset FAIL all.";nxt_st="error";main_status_op.update(label=lbl_p2,state=nxt_st,expanded=True);st.stop()
159
- elif success_assets<num_gen_sc: logger.warning(f"APP:Assets partial({success_assets}/{num_gen_sc}).");lbl_p2=f"Assets partial({success_assets}/{num_gen_sc}). "
160
- main_status_op.update(label=f"{lbl_p2}Narration...", state=nxt_st);
161
- if nxt_st=="error":st.stop()
162
- main_status_op.write("P3: Narration script..."); logger.info("APP: P3 - Narr Script.")
163
- v_style=st.session_state.get("selected_voice_style_for_generation","cinematic_trailer");p_narr=create_narration_script_prompt_enhanced(st.session_state.project_story_treatment_scenes_list,sb_mood,sb_genre,v_style)
164
- st.session_state.project_narration_script_text=st.session_state.gemini_service_handler.generate_image_prompt(p_narr)
165
- logger.info("APP: Narr script OK."); main_status_op.update(label="Narr ready! Voice synth...", state="running")
166
- main_status_op.write("P4: Voice synth..."); logger.info("APP: P4 - Voice Synth.")
167
- st.session_state.project_overall_narration_audio_path=st.session_state.visual_content_engine.generate_narration_audio(st.session_state.project_narration_script_text)
168
- fin_lbl="All ready! Review storyboard.🚀";fin_st="complete"
169
- if not st.session_state.project_overall_narration_audio_path: fin_lbl=f"{lbl_p2}Storyboard (Voice fail).";logger.warning("APP:Narr audio fail.")
170
- else:logger.info("APP:Narr audio OK.")
171
- main_status_op.update(label=fin_lbl,state=fin_st,expanded=False)
172
- except ValueError as e_val_main: logger.error(f"APP:ValueError:{e_val_main}",exc_info=True); main_status_op.update(label=f"Data/Resp Err:{e_val_main}",state="error",expanded=True);
173
- except TypeError as e_type_main: logger.error(f"APP:TypeError:{e_type_main}",exc_info=True); main_status_op.update(label=f"Type Err:{e_type_main}",state="error",expanded=True);
174
- except Exception as e_unhandled_main_flow: logger.error(f"APP_MAIN_FLOW: Unhandled Exception: {e_unhandled_main_flow}", exc_info=True); main_status_op.update(label=f"Unexpected Error: {e_unhandled_main_flow}", state="error", expanded=True);
175
-
176
- with st.expander("Define Characters", expanded=False):
177
- sb_char_name = st.text_input("Character Name", key="sb_char_name_unique_char_main"); sb_char_desc = st.text_area("Visual Description", key="sb_char_desc_unique_char_main", height=100)
178
- if st.button("Save Character", key="sb_add_char_unique_char_main"):
179
- if sb_char_name and sb_char_desc: st.session_state.project_character_definitions_map[sb_char_name.strip().lower()] = sb_char_desc.strip(); st.success(f"Char '{sb_char_name.strip()}' saved.")
180
- else: st.warning("Name and description needed.")
181
- if st.session_state.project_character_definitions_map: st.caption("Defined Characters:"); [st.markdown(f"**{k.title()}:** _{v}_") for k,v in st.session_state.project_character_definitions_map.items()]
182
- with st.expander("Global Style Overrides", expanded=False):
183
- sb_style_presets = { "Default": "", "Noir": "gritty neo-noir...", "Fantasy": "epic fantasy...", "Sci-Fi": "analog sci-fi..."}
184
- sb_selected_preset = st.selectbox("Base Style Preset:", list(sb_style_presets.keys()), key="sb_style_preset_unique_global_main")
185
- sb_custom_keywords = st.text_area("Additional Custom Keywords:", key="sb_custom_style_unique_global_main", height=80)
186
- sb_curr_global_style = st.session_state.project_global_style_keywords_str
187
- if st.button("Apply Global Styles", key="sb_apply_styles_unique_global_main"):
188
- final_style = sb_style_presets[sb_selected_preset];
189
- if sb_custom_keywords.strip(): final_style = f"{final_style}, {sb_custom_keywords.strip()}" if final_style else sb_custom_keywords.strip()
190
- st.session_state.project_global_style_keywords_str = final_style.strip(); sb_curr_global_style = final_style.strip()
191
- if sb_curr_global_style: st.success("Global styles applied!")
192
- else: st.info("Global styles cleared.")
193
- if sb_curr_global_style: st.caption(f"Active: \"{sb_curr_global_style}\"")
194
- with st.expander("Voice & Narration Style", expanded=False):
195
- sb_engine_default_voice = "Rachel"
196
- if hasattr(st.session_state, 'visual_content_engine'): sb_engine_default_voice = st.session_state.visual_content_engine.elevenlabs_voice_id
197
- sb_user_voice_id = st.text_input("11L Voice ID (override):", value=sb_engine_default_voice, key="sb_el_voice_id_override_unique_global_main")
198
- sb_narration_styles = {"Cinematic Trailer": "cinematic_trailer", "Neutral Documentary": "documentary_neutral", "Character Introspection": "introspective_character"}
199
- sb_selected_narr_style = st.selectbox("Narration Script Style:", list(sb_narration_styles.keys()), key="sb_narr_style_sel_unique_global_main", index=0)
200
- if st.button("Set Narrator Voice & Style", key="sb_set_voice_btn_unique_global_main"):
201
- final_el_voice_id = sb_user_voice_id.strip() or st.session_state.get("CONFIG_ELEVENLABS_VOICE_ID", "Rachel")
202
- if hasattr(st.session_state, 'visual_content_engine'): st.session_state.visual_content_engine.elevenlabs_voice_id = final_el_voice_id
203
- st.session_state.selected_voice_style_for_generation = sb_narration_styles[sb_selected_narr_style]
204
- st.success(f"Narrator Voice: {final_el_voice_id}. Script Style: {sb_selected_narr_style}")
205
- logger.info(f"User updated 11L Voice ID: {final_el_voice_id}, Narr Style: {sb_selected_narr_style}")
206
 
207
- st.header("🎬 Cinematic Storyboard & Treatment")
208
- if st.session_state.project_narration_script_text:
209
- with st.expander("📜 View Full Narration Script", expanded=False): st.markdown(f"> _{st.session_state.project_narration_script_text}_")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
 
211
- if not st.session_state.project_story_treatment_scenes_list: st.info("Use the sidebar to generate your cinematic treatment.")
212
- else:
213
- for i_main_display, scene_content_item_display in enumerate(st.session_state.project_story_treatment_scenes_list):
214
- scene_num_for_display = scene_content_item_display.get('scene_number', i_main_display + 1)
215
- scene_title_for_display_main = scene_content_item_display.get('scene_title', 'Untitled Scene')
216
- key_base_main_area_widgets = f"s{scene_num_for_display}_main_widgets_loop_v3_{i_main_display}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
- if "director_note" in scene_content_item_display and scene_content_item_display['director_note']: st.info(f"🎬 Director Note S{scene_num_for_display}: {scene_content_item_display['director_note']}")
219
- st.subheader(f"SCENE {scene_num_for_display}: {scene_title_for_display_main.upper()}");
220
- treatment_display_col, visual_display_col = st.columns([0.45, 0.55])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
- with treatment_display_col:
223
- with st.expander("📝 Scene Treatment & Controls", expanded=True):
224
- st.markdown(f"**Beat:** {scene_content_item_display.get('emotional_beat', 'N/A')}"); st.markdown(f"**Setting:** {scene_content_item_display.get('setting_description', 'N/A')}"); st.markdown(f"**Chars:** {', '.join(scene_content_item_display.get('characters_involved', ['N/A']))}"); st.markdown(f"**Focus Moment:** _{scene_content_item_display.get('character_focus_moment', 'N/A')}_"); st.markdown(f"**Plot Beat:** {scene_content_item_display.get('key_plot_beat', 'N/A')}"); st.markdown(f"**Dialogue Hook:** `\"{scene_content_item_display.get('suggested_dialogue_hook', '...')}\"`"); st.markdown("---"); st.markdown(f"**Dir. Visual Style:** _{scene_content_item_display.get('PROACTIVE_visual_style_감독', 'N/A')}_"); st.markdown(f"**Dir. Camera:** _{scene_content_item_display.get('PROACTIVE_camera_work_감독', 'N/A')}_"); st.markdown(f"**Dir. Sound:** _{scene_content_item_display.get('PROACTIVE_sound_design_감독', 'N/A')}_"); st.markdown("---")
225
- st.markdown("##### Shot, Pacing & Asset Controls")
226
- ui_shot_type = st.session_state.project_story_treatment_scenes_list[i_main_display].get('user_shot_type', DEFAULT_SHOT_TYPE)
227
- try: ui_shot_idx = SHOT_TYPES_OPTIONS.index(ui_shot_type)
228
- except ValueError: ui_shot_idx = SHOT_TYPES_OPTIONS.index(DEFAULT_SHOT_TYPE)
229
- new_ui_shot = st.selectbox("Dominant Shot Type:", SHOT_TYPES_OPTIONS, index=ui_shot_idx, key=f"shot_type_{key_base_main_area_widgets}")
230
- if new_ui_shot != ui_shot_type: st.session_state.project_story_treatment_scenes_list[i_main_display]['user_shot_type'] = new_ui_shot
231
- ui_dur = st.session_state.project_story_treatment_scenes_list[i_main_display].get('user_scene_duration_secs', DEFAULT_SCENE_DURATION_SECS)
232
- new_ui_dur = st.number_input("Scene Duration (s):", 1, 300, ui_dur, 1, key=f"duration_{key_base_main_area_widgets}")
233
- if new_ui_dur != ui_dur: st.session_state.project_story_treatment_scenes_list[i_main_display]['user_scene_duration_secs'] = new_ui_dur
234
- ui_asset_type = st.session_state.project_story_treatment_scenes_list[i_main_display].get('user_selected_asset_type', "Auto (Director's Choice)")
235
- try: ui_asset_idx = ASSET_TYPE_OPTIONS.index(ui_asset_type)
236
- except ValueError: ui_asset_idx = 0
237
- new_ui_asset = st.selectbox("Asset Type Override:", ASSET_TYPE_OPTIONS, index=ui_asset_idx, key=f"asset_type_{key_base_main_area_widgets}")
238
- if new_ui_asset != ui_asset_type: st.session_state.project_story_treatment_scenes_list[i_main_display]['user_selected_asset_type'] = new_ui_asset
239
- st.markdown("---")
240
- prompt_asset_disp_main = st.session_state.project_scene_generation_prompts_list[i_main_display] if i_main_display < len(st.session_state.project_scene_generation_prompts_list) else None
241
- if prompt_asset_disp_main:
242
- with st.popover("👁️ View Asset Gen Prompt"): st.markdown(f"**Prompt used:**"); st.code(prompt_asset_disp_main, language='text')
243
- px_q_disp_main = scene_content_item_display.get('pexels_search_query_감독', None)
244
- if px_q_disp_main: st.caption(f"Pexels Fallback: `{px_q_disp_main}`")
245
 
246
- with visual_display_col:
247
- asset_info_main_disp = st.session_state.project_generated_assets_info_list[i_main_display] if i_main_display < len(st.session_state.project_generated_assets_info_list) else None
248
- if asset_info_main_disp and not asset_info_main_disp.get('error') and asset_info_main_disp.get('path') and os.path.exists(asset_info_main_disp['path']):
249
- path_asset_main = asset_info_main_disp['path']; type_asset_main = asset_info_main_disp.get('type','image')
250
- if type_asset_main == 'image': st.image(path_asset_main, caption=f"S{scene_num_for_display} ({type_asset_main}): {scene_title_for_display_main}")
251
- elif type_asset_main == 'video':
252
- try:
253
- with open(path_asset_main,'rb') as vid_f_main: vid_b_main = vid_f_main.read()
254
- st.video(vid_b_main, format="video/mp4", start_time=0); st.caption(f"S{scene_num_for_display} ({type_asset_main}): {scene_title_for_display_main}")
255
- except Exception as e_vid_disp_main_area: st.error(f"Error displaying video {path_asset_main}: {e_vid_disp_main_area}"); logger.error(f"Display video error: {e_vid_disp_main_area}", exc_info=True)
256
- else: st.warning(f"Unknown asset type '{type_asset_main}' S{scene_num_for_display}.")
257
- else:
258
- if st.session_state.project_story_treatment_scenes_list:
259
- err_msg_disp_main_area = asset_info_main_disp.get('error_message', 'Visual pending or failed.') if asset_info_main_disp else 'Visual pending or failed.'
260
- st.caption(err_msg_disp_main_area)
261
-
262
- with st.popover(f"✏️ Edit S{scene_num_for_display} Treatment"):
263
- feedback_treat_regen_in = st.text_area("Changes to treatment:", key=f"treat_fb_pop_main_{key_base_main_area_widgets}", height=150)
264
- if st.button(f"🔄 Update S{scene_num_for_display} Treatment", key=f"regen_treat_btn_pop_main_{key_base_main_area_widgets}"):
265
- if feedback_treat_regen_in:
266
- with st.status(f"Updating S{scene_num_for_display} Treatment & Asset...", expanded=True) as status_treat_upd_pop_main:
267
- user_shot_pref = st.session_state.project_story_treatment_scenes_list[i_main_display]['user_shot_type']
268
- user_dur_pref = st.session_state.project_story_treatment_scenes_list[i_main_display]['user_scene_duration_secs']
269
- user_asset_pref = st.session_state.project_story_treatment_scenes_list[i_main_display]['user_selected_asset_type']
270
- prompt_gemini_regen = create_scene_regeneration_prompt(scene_content_item_display, feedback_treat_regen_in, st.session_state.project_story_treatment_scenes_list)
271
- try:
272
- updated_scene_gemini = st.session_state.gemini_service_handler.regenerate_scene_script_details(prompt_gemini_regen)
273
- final_updated_scene = {**updated_scene_gemini}
274
- final_updated_scene['user_shot_type']=user_shot_pref; final_updated_scene['user_scene_duration_secs']=user_dur_pref; final_updated_scene['user_selected_asset_type']=user_asset_pref
275
- st.session_state.project_story_treatment_scenes_list[i_main_display] = final_updated_scene
276
- status_treat_upd_pop_main.update(label="Treatment updated! Regenerating asset...", state="running")
277
- ver_asset_regen = 1
278
- if asset_info_main_disp and asset_info_main_disp.get('path') and os.path.exists(asset_info_main_disp['path']):
279
- try: base_fn_regen,_=os.path.splitext(os.path.basename(asset_info_main_disp['path'])); ver_asset_regen = int(base_fn_regen.split('_v')[-1])+1 if '_v' in base_fn_regen else 2
280
- except: ver_asset_regen = 2
281
- if generate_asset_for_scene_in_app(i_main_display, final_updated_scene, asset_v=ver_asset_regen, user_asset_type_ui=user_asset_pref): status_treat_upd_pop_main.update(label="Treatment & Asset Updated! 🎉", state="complete", expanded=False)
282
- else: status_treat_upd_pop_main.update(label="Treatment updated, asset regen failed.", state="complete", expanded=False)
283
- st.rerun()
284
- except Exception as e_treat_regen_main_loop_pop: status_treat_upd_pop_main.update(label=f"Error: {e_treat_regen_main_loop_pop}", state="error"); logger.error(f"Scene treatment regen error: {e_treat_regen_main_loop_pop}", exc_info=True)
285
- else: st.warning("Please provide feedback for treatment.")
286
 
287
- with st.popover(f"🎨 Edit S{scene_num_for_display} Visual Prompt/Asset"):
288
- prompt_edit_disp_visual_pop = st.session_state.project_scene_generation_prompts_list[i_main_display] if i_main_display < len(st.session_state.project_scene_generation_prompts_list) else "No prompt."
289
- st.caption("Current Asset Generation Prompt:"); st.code(prompt_edit_disp_visual_pop, language='text')
290
- feedback_vis_asset_regen_input_pop = st.text_area("Describe changes for visual asset:", key=f"visual_fb_input_pop_main_{key_base_main_area_widgets}", height=150)
291
- if st.button(f"🔄 Update S{scene_num_for_display} Asset", key=f"regen_visual_btn_pop_main_{key_base_main_area_widgets}"):
292
- if feedback_vis_asset_regen_input_pop:
293
- with st.status(f"Refining prompt & asset for S{scene_num_for_display}...", expanded=True) as status_vis_asset_regen_op_pop_main:
294
- user_asset_type_choice_pop_viz = st.session_state.project_story_treatment_scenes_list[i_main_display]['user_selected_asset_type']
295
- is_video_for_regen_pop_viz = (user_asset_type_choice_pop_viz == "Video Clip") or (user_asset_type_choice_pop_viz == "Auto (Director's Choice)" and scene_content_item_display.get('suggested_asset_type_감독') == 'video_clip')
296
- newly_constructed_asset_prompt_regen_pop_viz = ""
297
- if not is_video_for_regen_pop_viz:
298
- gemini_refinement_prompt_viz_pop_final = create_visual_regeneration_prompt(prompt_edit_disp_visual_pop, feedback_vis_asset_regen_input_pop, scene_content_item_display, st.session_state.project_character_definitions_map, st.session_state.project_global_style_keywords_str)
299
- try: newly_constructed_asset_prompt_regen_pop_viz = st.session_state.gemini_service_handler.refine_image_prompt_from_feedback(gemini_refinement_prompt_viz_pop_final); st.session_state.project_scene_generation_prompts_list[i_main_display] = newly_constructed_asset_prompt_regen_pop_viz; status_vis_asset_regen_op_pop_main.update(label="Image prompt refined! Regenerating asset...", state="running")
300
- except Exception as e_gem_refine_pop_main: status_vis_asset_regen_op_pop_main.update(label=f"Error refining prompt: {e_gem_refine_pop_main}", state="error"); logger.error(f"Visual prompt refinement error: {e_gem_refine_pop_main}", exc_info=True); continue
301
- else:
302
- newly_constructed_asset_prompt_regen_pop_viz = construct_text_to_video_prompt_for_gen4(scene_content_item_display, st.session_state.project_global_style_keywords_str); st.session_state.project_scene_generation_prompts_list[i_main_display] = newly_constructed_asset_prompt_regen_pop_viz; status_vis_asset_regen_op_pop_main.update(label="Video prompt reconstructed! Regenerating asset...", state="running")
303
- if not newly_constructed_asset_prompt_regen_pop_viz: status_vis_asset_regen_op_pop_main.update(label="Prompt construction failed.", state="error"); continue
304
- ver_vis_asset_regen_pop_main = 1
305
- if asset_info_main_disp and asset_info_main_disp.get('path') and os.path.exists(asset_info_main_disp['path']):
306
- try: base_fn_viz_pop_main,_=os.path.splitext(os.path.basename(asset_info_main_disp['path'])); ver_vis_asset_regen_pop_main = int(base_fn_viz_pop_main.split('_v')[-1])+1 if '_v' in base_fn_viz_pop_main else 2
307
- except: ver_vis_asset_regen_pop_main = 2
308
- if generate_asset_for_scene_in_app(i_main_display, st.session_state.project_story_treatment_scenes_list[i_main_display], asset_ver_num=ver_vis_asset_regen_pop_main, user_asset_type_ui=user_asset_type_choice_pop_viz): status_vis_asset_regen_op_pop_main.update(label="Asset Updated! 🎉", state="complete", expanded=False)
309
- else: status_vis_asset_regen_op_pop_main.update(label="Prompt updated, asset regen failed.", state="complete", expanded=False)
310
- st.rerun()
311
- else: st.warning("Please provide feedback for visual asset regeneration.")
312
- st.markdown("---")
313
-
314
- if st.session_state.project_story_treatment_scenes_list and any(asset_info_item_vid and not asset_info_item_vid.get('error') and asset_info_item_vid.get('path') for asset_info_item_vid in st.session_state.project_generated_assets_info_list if asset_info_item_vid is not None):
315
- if st.button("🎬 Assemble Narrated Cinematic Animatic", key="assemble_video_main_area_btn_final_unique_4", type="primary", use_container_width=True):
316
- with st.status("Assembling Ultra Animatic...", expanded=True) as status_video_assembly_final_op_main:
317
- assets_for_final_vid_assembly_list = []
318
- for i_vid_assembly_main_loop, scene_data_for_vid_assembly_main in enumerate(st.session_state.project_story_treatment_scenes_list):
319
- asset_info_current_scene_for_vid_main = st.session_state.project_generated_assets_info_list[i_vid_assembly_main_loop] if i_vid_assembly_main_loop < len(st.session_state.project_generated_assets_info_list) else None
320
- if asset_info_current_scene_for_vid_main and not asset_info_current_scene_for_vid_main.get('error') and asset_info_current_scene_for_vid_main.get('path') and os.path.exists(asset_info_current_scene_for_vid_main['path']):
321
- assets_for_final_vid_assembly_list.append({'path': asset_info_current_scene_for_vid_main['path'], 'type': asset_info_current_scene_for_vid_main.get('type', 'image'), 'scene_num': scene_data_for_vid_assembly_main.get('scene_number', i_vid_assembly_main_loop + 1), 'key_action': scene_data_for_vid_assembly_main.get('key_plot_beat', ''), 'duration': scene_data_for_vid_assembly_main.get('user_scene_duration_secs', DEFAULT_SCENE_DURATION_SECS)})
322
- status_video_assembly_final_op_main.write(f"Adding S{scene_data_for_vid_assembly_main.get('scene_number', i_vid_assembly_main_loop + 1)} ({asset_info_current_scene_for_vid_main.get('type')}).")
323
- else: logger.warning(f"Skipping S{scene_data_for_vid_assembly_main.get('scene_number', i_vid_assembly_main_loop+1)} for video: No valid asset.")
324
- if assets_for_final_vid_assembly_list:
325
- status_video_assembly_final_op_main.write("Calling video engine..."); logger.info("APP: Calling visual_engine.assemble_animatic_from_assets")
326
- st.session_state.project_final_video_path = st.session_state.visual_content_engine.assemble_animatic_from_assets(asset_data_list=assets_for_final_vid_assembly_list, overall_narration_path=st.session_state.project_overall_narration_audio_path, output_filename="cinegen_ultra_animatic.mp4", fps=24)
327
- if st.session_state.project_final_video_path and os.path.exists(st.session_state.project_final_video_path): status_video_assembly_final_op_main.update(label="Ultra animatic assembled! 🎉", state="complete", expanded=False); st.balloons()
328
- else: status_video_assembly_final_op_main.update(label="Video assembly failed. Check logs.", state="error", expanded=True); logger.error("APP: Video assembly returned None or file does not exist.")
329
- else: status_video_assembly_final_op_main.update(label="No valid assets for video assembly.", state="error", expanded=True); logger.warning("APP: No valid assets found for video assembly.")
330
- elif st.session_state.project_story_treatment_scenes_list: st.info("Generate visual assets for your scenes before attempting to assemble the animatic.")
331
 
332
- if st.session_state.project_final_video_path and os.path.exists(st.session_state.project_final_video_path):
333
- st.header("🎬 Generated Cinematic Animatic");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  try:
335
- with open(st.session_state.project_final_video_path, 'rb') as final_video_file_obj_display_main: final_video_bytes_for_display_main = final_video_file_obj_display_main.read()
336
- st.video(final_video_bytes_for_display_main, format="video/mp4")
337
- st.download_button(label="Download Ultra Animatic", data=final_video_bytes_for_display_main, file_name=os.path.basename(st.session_state.project_final_video_path), mime="video/mp4", use_container_width=True, key="download_video_main_area_btn_final_unique_4" )
338
- except Exception as e_final_video_display_op_main_area: st.error(f"Error displaying final animatic video: {e_final_video_display_op_main_area}"); logger.error(f"Error displaying final animatic video: {e_final_video_display_op_main_area}", exc_info=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
- st.sidebar.markdown("---"); st.sidebar.caption("CineGen AI Ultra+ | Visionary Cinematic Pre-Production")
 
 
 
 
 
 
1
+ # core/visual_engine.py
2
+ from PIL import Image, ImageDraw, ImageFont, ImageOps
3
+ import base64
4
+ import mimetypes
5
+ import numpy as np
6
  import os
7
+ import openai
8
+ import requests
9
+ import io
10
+ import time
11
+ import random
12
  import logging
13
 
14
+ from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
15
+ CompositeVideoClip, AudioFileClip)
16
+ import moviepy.video.fx.all as vfx
 
 
 
 
 
 
 
17
 
18
+ try:
19
+ if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'):
20
+ if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
21
+ elif hasattr(Image, 'LANCZOS'):
22
+ if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
23
+ elif not hasattr(Image, 'ANTIALIAS'):
24
+ print("WARNING: Pillow version lacks common Resampling or ANTIALIAS. MoviePy effects might fail.")
25
+ except Exception as e_mp: print(f"WARNING: ANTIALIAS monkey-patch error: {e_mp}")
26
 
 
 
27
  logger = logging.getLogger(__name__)
28
+ # logger.setLevel(logging.DEBUG)
29
 
30
+ ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
31
+ try:
32
+ from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
33
+ from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
34
+ ElevenLabsAPIClient = ImportedElevenLabsClient; Voice = ImportedVoice; VoiceSettings = ImportedVoiceSettings
35
+ ELEVENLABS_CLIENT_IMPORTED = True; logger.info("ElevenLabs client components imported.")
36
+ except Exception as e_11l_imp: logger.warning(f"ElevenLabs client import failed: {e_11l_imp}. Audio disabled.")
37
 
38
+ RUNWAYML_SDK_IMPORTED = False; RunwayMLAPIClientClass = None
39
+ try:
40
+ from runwayml import RunwayML as ImportedRunwayMLAPIClientClass
41
+ RunwayMLAPIClientClass = ImportedRunwayMLAPIClientClass; RUNWAYML_SDK_IMPORTED = True
42
+ logger.info("RunwayML SDK imported.")
43
+ except Exception as e_rwy_imp: logger.warning(f"RunwayML SDK import failed: {e_rwy_imp}. RunwayML disabled.")
 
 
 
 
44
 
45
+ class VisualEngine:
46
+ DEFAULT_FONT_SIZE_PIL = 10; PREFERRED_FONT_SIZE_PIL = 20
47
+ VIDEO_OVERLAY_FONT_SIZE = 30; VIDEO_OVERLAY_FONT_COLOR = 'white'
48
+ DEFAULT_MOVIEPY_FONT = 'DejaVu-Sans-Bold'; PREFERRED_MOVIEPY_FONT = 'Liberation-Sans-Bold'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
51
+ self.output_dir = output_dir
52
+ try: os.makedirs(self.output_dir, exist_ok=True); logger.info(f"VE output dir: {os.path.abspath(self.output_dir)}")
53
+ # Test writability immediately (optional, but good for early failure detection)
54
+ # test_file_path = os.path.join(self.output_dir, ".ve_write_test.txt")
55
+ # with open(test_file_path, "w") as f_test: f_test.write("VE write test OK")
56
+ # os.remove(test_file_path); logger.info(f"Write test to '{self.output_dir}' OK.")
57
+ except Exception as e_mkdir: logger.critical(f"CRITICAL: Failed to create output dir '{os.path.abspath(self.output_dir)}': {e_mkdir}", exc_info=True); raise OSError(f"VE failed to init output dir '{self.output_dir}'.") from e_mkdir
58
+ self.font_filename_pil_preference = "DejaVuSans-Bold.ttf"
59
+ font_paths = [ self.font_filename_pil_preference, f"/usr/share/fonts/truetype/dejavu/{self.font_filename_pil_preference}", f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", f"/System/Library/Fonts/Supplemental/Arial.ttf", f"C:/Windows/Fonts/arial.ttf", f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf"]
60
+ self.resolved_font_path_pil = next((p for p in font_paths if os.path.exists(p)), None)
61
+ self.active_font_pil = ImageFont.load_default(); self.active_font_size_pil = self.DEFAULT_FONT_SIZE_PIL; self.active_moviepy_font_name = self.DEFAULT_MOVIEPY_FONT
62
+ if self.resolved_font_path_pil:
63
+ try: self.active_font_pil = ImageFont.truetype(self.resolved_font_path_pil, self.PREFERRED_FONT_SIZE_PIL); self.active_font_size_pil = self.PREFERRED_FONT_SIZE_PIL; logger.info(f"Pillow font: {self.resolved_font_path_pil} sz {self.active_font_size_pil}."); self.active_moviepy_font_name = 'DejaVu-Sans-Bold' if "dejavu" in self.resolved_font_path_pil.lower() else ('Liberation-Sans-Bold' if "liberation" in self.resolved_font_path_pil.lower() else self.DEFAULT_MOVIEPY_FONT)
64
+ except IOError as e_font: logger.error(f"Pillow font IOError '{self.resolved_font_path_pil}': {e_font}. Default.")
65
+ else: logger.warning("Preferred Pillow font not found. Default.")
66
+ self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False; self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
67
+ self.video_frame_size = (1280, 720)
68
+ self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client_instance = None
69
+ self.elevenlabs_voice_id = default_elevenlabs_voice_id # Set initial voice ID
70
+ logger.info(f"VE __init__: 11L Voice ID initially set to: {self.elevenlabs_voice_id}")
71
+ if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED: self.elevenlabs_voice_settings_obj = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
72
+ else: self.elevenlabs_voice_settings_obj = None
73
+ self.pexels_api_key = None; self.USE_PEXELS = False
74
+ self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None
75
+ if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass and os.getenv("RUNWAYML_API_SECRET"):
76
+ try: self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init from env var at startup.")
77
+ except Exception as e_rwy_init: logger.error(f"Initial RunwayML client init failed: {e_rwy_init}"); self.USE_RUNWAYML = False
78
+ logger.info("VisualEngine __init__ sequence complete.")
79
 
80
+ def set_openai_api_key(self, api_key_value): self.openai_api_key = api_key_value; self.USE_AI_IMAGE_GENERATION = bool(api_key_value); logger.info(f"DALL-E status: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}")
81
+
82
+ # <<< CORRECTED METHOD SIGNATURE AND LOGIC >>>
83
+ def set_elevenlabs_api_key(self, api_key_value, voice_id_from_secret=None):
84
+ self.elevenlabs_api_key = api_key_value
85
 
86
+ if voice_id_from_secret:
87
+ self.elevenlabs_voice_id = voice_id_from_secret
88
+ logger.info(f"ElevenLabs Voice ID explicitly set/updated to: {self.elevenlabs_voice_id} via set_elevenlabs_api_key.")
89
+ # If voice_id_from_secret is None, self.elevenlabs_voice_id (set in __init__ or by user via UI) remains.
90
+
91
+ if api_key_value and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
92
+ try:
93
+ self.elevenlabs_client_instance = ElevenLabsAPIClient(api_key=api_key_value)
94
+ self.USE_ELEVENLABS = bool(self.elevenlabs_client_instance)
95
+ logger.info(f"ElevenLabs Client service status: {'Ready' if self.USE_ELEVENLABS else 'Failed Initialization'} (Using Voice ID: {self.elevenlabs_voice_id})")
96
+ except Exception as e_11l_setkey_init:
97
+ logger.error(f"ElevenLabs client initialization error during set_elevenlabs_api_key: {e_11l_setkey_init}. Service Disabled.", exc_info=True)
98
+ self.USE_ELEVENLABS = False
99
+ self.elevenlabs_client_instance = None
100
+ else:
101
+ self.USE_ELEVENLABS = False
102
+ self.elevenlabs_client_instance = None
103
+ if not api_key_value: logger.info(f"ElevenLabs Service Disabled (API key not provided to set_elevenlabs_api_key).")
104
+ elif not (ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient): logger.info(f"ElevenLabs Service Disabled (SDK issue).")
105
+
106
+ def set_pexels_api_key(self, api_key_value): self.pexels_api_key = api_key_value; self.USE_PEXELS = bool(api_key_value); logger.info(f"Pexels status: {'Ready' if self.USE_PEXELS else 'Disabled'}")
107
+
108
+ def set_runway_api_key(self, api_key_value):
109
+ self.runway_api_key = api_key_value
110
+ if api_key_value:
111
+ if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
112
+ if not self.runway_ml_sdk_client_instance:
113
+ try:
114
+ original_env_secret_val = os.getenv("RUNWAYML_API_SECRET")
115
+ if not original_env_secret_val: os.environ["RUNWAYML_API_SECRET"] = api_key_value; logger.info("Temp set RUNWAYML_API_SECRET for SDK.")
116
+ self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init via set_key.")
117
+ if not original_env_secret_val: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared temp RUNWAYML_API_SECRET.")
118
+ except Exception as e_runway_setkey_init_local: logger.error(f"RunwayML Client init in set_key fail: {e_runway_setkey_init_local}", exc_info=True); self.USE_RUNWAYML=False;self.runway_ml_sdk_client_instance=None
119
+ else: self.USE_RUNWAYML = True; logger.info("RunwayML Client already init.")
120
+ else: logger.warning("RunwayML SDK not imported. Disabled."); self.USE_RUNWAYML = False
121
+ else: self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None; logger.info("RunwayML Disabled (no key).")
122
 
123
+ # --- Helper Methods (_image_to_data_uri, _map_resolution_to_runway_ratio, etc. - Ensure these are fully corrected from previous iterations) ---
124
+ def _image_to_data_uri(self, image_path_in):
125
+ try:
126
+ mime_type_val, _ = mimetypes.guess_type(image_path_in)
127
+ if not mime_type_val: ext = os.path.splitext(image_path_in)[1].lower(); mime_map = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}; mime_type_val = mime_map.get(ext, "application/octet-stream");
128
+ if mime_type_val == "application/octet-stream": logger.warning(f"Unknown MIME for {image_path_in}, using {mime_type_val}.")
129
+ with open(image_path_in, "rb") as img_file_handle: img_binary_data = img_file_handle.read()
130
+ encoded_b64_str = base64.b64encode(img_binary_data).decode('utf-8')
131
+ final_data_uri = f"data:{mime_type_val};base64,{encoded_b64_str}"; logger.debug(f"Data URI for {os.path.basename(image_path_in)} (MIME:{mime_type_val}): {final_data_uri[:100]}..."); return final_data_uri
132
+ except FileNotFoundError: logger.error(f"Img not found {image_path_in} for data URI."); return None
133
+ except Exception as e_to_data_uri: logger.error(f"Error converting {image_path_in} to data URI:{e_to_data_uri}", exc_info=True); return None
134
 
135
+ def _map_resolution_to_runway_ratio(self, width_in, height_in):
136
+ ratio_string = f"{width_in}:{height_in}"; supported_ratios = ["1280:720","720:1280","1104:832","832:1104","960:960","1584:672"];
137
+ if ratio_string in supported_ratios: return ratio_string
138
+ logger.warning(f"Res {ratio_string} not in Gen-4 list. Default 1280:720 for Runway.");return "1280:720"
 
 
 
 
 
 
 
 
 
 
 
139
 
140
+ def _get_text_dimensions(self, text_str, font_pil_obj):
141
+ def_h = getattr(font_pil_obj, 'size', self.active_font_size_pil);
142
+ if not text_str: return 0, def_h
143
+ try:
144
+ if hasattr(font_pil_obj,'getbbox'): box = font_pil_obj.getbbox(text_str); w_val=box[2]-box[0]; h_val=box[3]-box[1]; return w_val, h_val if h_val > 0 else def_h
145
+ elif hasattr(font_pil_obj,'getsize'): w_val,h_val=font_pil_obj.getsize(text_str); return w_val, h_val if h_val > 0 else def_h
146
+ else: return int(len(text_str)*def_h*0.6), int(def_h*1.2)
147
+ except Exception as e_get_dim: logger.warning(f"Error in _get_text_dimensions: {e_get_dim}"); return int(len(text_str)*self.active_font_size_pil*0.6),int(self.active_font_size_pil*1.2)
 
 
 
148
 
149
+ def _create_placeholder_image_content(self,text_desc_val, filename_val, size_val=None):
150
+ if size_val is None: size_val = self.video_frame_size
151
+ placeholder_img = Image.new('RGB', size_val, color=(20, 20, 40)); placeholder_draw = ImageDraw.Draw(placeholder_img); ph_padding = 25
152
+ ph_max_w = size_val[0] - (2 * ph_padding); ph_lines = []
153
+ if not text_desc_val: text_desc_val = "(Placeholder Image)"
154
+ ph_words = text_desc_val.split(); ph_current_line = ""
155
+ for ph_word_idx, ph_word in enumerate(ph_words):
156
+ ph_prosp_add = ph_word + (" " if ph_word_idx < len(ph_words) - 1 else "")
157
+ ph_test_line = ph_current_line + ph_prosp_add
158
+ ph_curr_w, _ = self._get_text_dimensions(ph_test_line, self.active_font_pil)
159
+ if ph_curr_w == 0 and ph_test_line.strip(): ph_curr_w = len(ph_test_line) * (self.active_font_size_pil * 0.6)
160
+ if ph_curr_w <= ph_max_w: ph_current_line = ph_test_line
161
+ else:
162
+ if ph_current_line.strip(): ph_lines.append(ph_current_line.strip())
163
+ ph_current_line = ph_prosp_add
164
+ if ph_current_line.strip(): ph_lines.append(ph_current_line.strip())
165
+ if not ph_lines and text_desc_val:
166
+ ph_avg_char_w, _ = self._get_text_dimensions("W", self.active_font_pil); ph_avg_char_w = ph_avg_char_w or (self.active_font_size_pil * 0.6)
167
+ ph_chars_line = int(ph_max_w / ph_avg_char_w) if ph_avg_char_w > 0 else 20
168
+ ph_lines.append(text_desc_val[:ph_chars_line] + ("..." if len(text_desc_val) > ph_chars_line else ""))
169
+ elif not ph_lines: ph_lines.append("(Placeholder Error)")
170
+ _, ph_single_h = self._get_text_dimensions("Ay", self.active_font_pil); ph_single_h = ph_single_h if ph_single_h > 0 else self.active_font_size_pil + 2
171
+ ph_max_l = min(len(ph_lines), (size_val[1] - (2 * ph_padding)) // (ph_single_h + 2)) if ph_single_h > 0 else 1; ph_max_l = max(1, ph_max_l)
172
+ ph_y_pos = ph_padding + (size_val[1] - (2 * ph_padding) - ph_max_l * (ph_single_h + 2)) / 2.0
173
+ for ph_i_line in range(ph_max_l):
174
+ ph_line_txt = ph_lines[ph_i_line]; ph_line_w, _ = self._get_text_dimensions(ph_line_txt, self.active_font_pil)
175
+ if ph_line_w == 0 and ph_line_txt.strip(): ph_line_w = len(ph_line_txt) * (self.active_font_size_pil * 0.6)
176
+ ph_x_pos = (size_val[0] - ph_line_w) / 2.0
177
+ try: placeholder_draw.text((ph_x_pos, ph_y_pos), ph_line_txt, font=self.active_font_pil, fill=(200, 200, 180))
178
+ except Exception as e_ph_draw: logger.error(f"Pillow d.text error: {e_ph_draw} for '{ph_line_txt}'")
179
+ ph_y_pos += ph_single_h + 2
180
+ if ph_i_line == 6 and ph_max_l > 7:
181
+ try: placeholder_draw.text((ph_x_pos, ph_y_pos), "...", font=self.active_font_pil, fill=(200, 200, 180))
182
+ except Exception as e_ph_elip: logger.error(f"Pillow d.text ellipsis error: {e_ph_elip}"); break
183
+ ph_filepath = os.path.join(self.output_dir, filename_val)
184
+ try: placeholder_img.save(ph_filepath); return ph_filepath
185
+ except Exception as e_ph_save: logger.error(f"Saving placeholder image '{ph_filepath}' error: {e_ph_save}", exc_info=True); return None
186
 
187
+ def _search_pexels_image(self, query_str_px, output_fn_base_px):
188
+ if not self.USE_PEXELS or not self.pexels_api_key: return None
189
+ http_headers_px = {"Authorization": self.pexels_api_key}
190
+ http_params_px = {"query": query_str_px, "per_page": 1, "orientation": "landscape", "size": "large2x"}
191
+ base_name_for_pexels_img, _ = os.path.splitext(output_fn_base_px)
192
+ pexels_filename_output = base_name_for_pexels_img + f"_pexels_{random.randint(1000,9999)}.jpg"
193
+ filepath_for_pexels_img = os.path.join(self.output_dir, pexels_filename_output)
194
+ try:
195
+ logger.info(f"Pexels: Searching for '{query_str_px}'")
196
+ effective_query_for_pexels = " ".join(query_str_px.split()[:5])
197
+ http_params_px["query"] = effective_query_for_pexels
198
+ response_from_pexels = requests.get("https://api.pexels.com/v1/search", headers=http_headers_px, params=http_params_px, timeout=20)
199
+ response_from_pexels.raise_for_status()
200
+ data_from_pexels = response_from_pexels.json()
201
+ if data_from_pexels.get("photos") and len(data_from_pexels["photos"]) > 0:
202
+ photo_details_item_px = data_from_pexels["photos"][0]
203
+ photo_url_item_px = photo_details_item_px.get("src", {}).get("large2x")
204
+ if not photo_url_item_px: logger.warning(f"Pexels: 'large2x' URL missing for '{effective_query_for_pexels}'. Details: {photo_details_item_px}"); return None
205
+ image_response_get_px = requests.get(photo_url_item_px, timeout=60); image_response_get_px.raise_for_status()
206
+ img_pil_data_from_pexels = Image.open(io.BytesIO(image_response_get_px.content))
207
+ if img_pil_data_from_pexels.mode != 'RGB': img_pil_data_from_pexels = img_pil_data_from_pexels.convert('RGB')
208
+ img_pil_data_from_pexels.save(filepath_for_pexels_img); logger.info(f"Pexels: Image saved to {filepath_for_pexels_img}"); return filepath_for_pexels_img
209
+ else: logger.info(f"Pexels: No photos for '{effective_query_for_pexels}'."); return None
210
+ except requests.exceptions.RequestException as e_req_px_loop: logger.error(f"Pexels: RequestException for '{query_str_px}': {e_req_px_loop}", exc_info=False); return None
211
+ except Exception as e_px_gen_loop: logger.error(f"Pexels: General error for '{query_str_px}': {e_px_gen_loop}", exc_info=True); return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
+ def _generate_video_clip_with_runwayml(self, motion_prompt_rwy, input_img_path_rwy, scene_id_base_fn_rwy, duration_s_rwy=5):
214
+ if not self.USE_RUNWAYML or not self.runway_ml_sdk_client_instance: logger.warning("RunwayML skip: Not enabled/client not init."); return None
215
+ if not input_img_path_rwy or not os.path.exists(input_img_path_rwy): logger.error(f"Runway Gen-4 needs input img. Invalid: {input_img_path_rwy}"); return None
216
+ img_data_uri_rwy = self._image_to_data_uri(input_img_path_rwy)
217
+ if not img_data_uri_rwy: return None
218
+ rwy_actual_dur = 10 if duration_s_rwy >= 8 else 5; rwy_actual_ratio = self._map_resolution_to_runway_ratio(self.video_frame_size[0],self.video_frame_size[1])
219
+ rwy_fn_base, _ = os.path.splitext(scene_id_base_fn_rwy); rwy_output_fn = rwy_fn_base + f"_runway_gen4_d{rwy_actual_dur}s.mp4"; rwy_output_fp = os.path.join(self.output_dir,rwy_output_fn)
220
+ logger.info(f"Runway Gen-4 task: motion='{motion_prompt_rwy[:70]}...', img='{os.path.basename(input_img_path_rwy)}', dur={rwy_actual_dur}s, ratio='{rwy_actual_ratio}'")
221
+ try:
222
+ rwy_submitted_task = self.runway_ml_sdk_client_instance.image_to_video.create(model='gen4_turbo',prompt_image=img_data_uri_rwy,prompt_text=motion_prompt_rwy,duration=rwy_actual_dur,ratio=rwy_actual_ratio)
223
+ rwy_task_id_val = rwy_submitted_task.id; logger.info(f"Runway task ID: {rwy_task_id_val}. Polling...")
224
+ poll_interval_val=10;max_poll_attempts=36;poll_start_timestamp=time.time()
225
+ while time.time()-poll_start_timestamp < max_poll_attempts*poll_interval_val:
226
+ time.sleep(poll_interval_val);rwy_task_details_obj=self.runway_ml_sdk_client_instance.tasks.retrieve(id=rwy_task_id_val)
227
+ logger.info(f"Runway task {rwy_task_id_val} status: {rwy_task_details_obj.status}")
228
+ if rwy_task_details_obj.status=='SUCCEEDED':
229
+ rwy_video_output_url=getattr(getattr(rwy_task_details_obj,'output',None),'url',None) or (getattr(rwy_task_details_obj,'artifacts',None)and rwy_task_details_obj.artifacts and hasattr(rwy_task_details_obj.artifacts[0],'url')and rwy_task_details_obj.artifacts[0].url) or (getattr(rwy_task_details_obj,'artifacts',None)and rwy_task_details_obj.artifacts and hasattr(rwy_task_details_obj.artifacts[0],'download_url')and rwy_task_details_obj.artifacts[0].download_url)
230
+ if not rwy_video_output_url:logger.error(f"Runway task {rwy_task_id_val} SUCCEEDED, no output URL. Details:{vars(rwy_task_details_obj)if hasattr(rwy_task_details_obj,'__dict__')else rwy_task_details_obj}");return None
231
+ logger.info(f"Runway task {rwy_task_id_val} SUCCEEDED. Downloading: {rwy_video_output_url}")
232
+ runway_video_response=requests.get(rwy_video_output_url,stream=True,timeout=300);runway_video_response.raise_for_status()
233
+ with open(rwy_output_fp,'wb')as f_out_vid:
234
+ for data_chunk_vid in runway_video_response.iter_content(chunk_size=8192): f_out_vid.write(data_chunk_vid)
235
+ logger.info(f"Runway Gen-4 video saved: {rwy_output_fp}");return rwy_output_fp
236
+ elif rwy_task_details_obj.status in['FAILED','ABORTED','ERROR']:
237
+ runway_error_detail=getattr(rwy_task_details_obj,'error_message',None)or getattr(getattr(rwy_task_details_obj,'output',None),'error',"Unknown Runway error.")
238
+ logger.error(f"Runway task {rwy_task_id_val} status:{rwy_task_details_obj.status}. Error:{runway_error_detail}");return None
239
+ logger.warning(f"Runway task {rwy_task_id_val} timed out.");return None
240
+ except AttributeError as e_rwy_sdk_attr: logger.error(f"RunwayML SDK AttrError:{e_rwy_sdk_attr}. SDK methods changed?",exc_info=True);return None
241
+ except Exception as e_rwy_general: logger.error(f"Runway Gen-4 API error:{e_rwy_general}",exc_info=True);return None
242
 
243
+ def _create_placeholder_video_content(self, text_desc_ph_vid, filename_ph_vid, duration_ph_vid=4, size_ph_vid=None):
244
+ if size_ph_vid is None: size_ph_vid = self.video_frame_size
245
+ filepath_ph_vid_out = os.path.join(self.output_dir, filename_ph_vid)
246
+ text_clip_object_ph = None
247
+ try:
248
+ text_clip_object_ph = TextClip(text_desc_ph_vid, fontsize=50, color='white', font=self.video_overlay_font,
249
+ bg_color='black', size=size_ph_vid, method='caption').set_duration(duration_ph_vid)
250
+ text_clip_object_ph.write_videofile(filepath_ph_vid_out, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
251
+ logger.info(f"Generic placeholder video created: {filepath_ph_vid_out}")
252
+ return filepath_ph_vid_out
253
+ except Exception as e_placeholder_video_creation:
254
+ logger.error(f"Failed to create generic placeholder video '{filepath_ph_vid_out}': {e_placeholder_video_creation}", exc_info=True)
255
+ return None
256
+ finally:
257
+ if text_clip_object_ph and hasattr(text_clip_object_ph, 'close'):
258
+ try: text_clip_object_ph.close()
259
+ except Exception as e_close_placeholder_clip: logger.warning(f"Ignoring error closing placeholder TextClip: {e_close_placeholder_clip}")
260
+
261
+ def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
262
+ scene_data_dictionary, scene_identifier_fn_base,
263
+ generate_as_video_clip_flag=False, runway_target_duration_val=5):
264
+ base_name_current_asset, _ = os.path.splitext(scene_identifier_fn_base)
265
+ asset_info_return_obj = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_generation_prompt_text, 'error_message': 'Asset generation init failed'}
266
+ path_to_input_image_for_runway = None
267
+ filename_for_base_image_output = base_name_current_asset + ("_base_for_video.png" if generate_as_video_clip_flag else ".png")
268
+ filepath_for_base_image_output = os.path.join(self.output_dir, filename_for_base_image_output)
269
+ if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
270
+ max_retries_dalle, current_attempt_dalle = 2,0;
271
+ for idx_dalle_attempt in range(max_retries_dalle):
272
+ current_attempt_dalle = idx_dalle_attempt + 1
273
+ try:
274
+ logger.info(f"Att {current_attempt_dalle} DALL-E (base img): {image_generation_prompt_text[:70]}..."); oai_client = openai.OpenAI(api_key=self.openai_api_key,timeout=90.0); oai_response = oai_client.images.generate(model=self.dalle_model,prompt=image_generation_prompt_text,n=1,size=self.image_size_dalle3,quality="hd",response_format="url",style="vivid"); oai_image_url = oai_response.data[0].url; oai_revised_prompt = getattr(oai_response.data[0],'revised_prompt',None);
275
+ if oai_revised_prompt: logger.info(f"DALL-E revised: {oai_revised_prompt[:70]}...")
276
+ oai_image_get_response = requests.get(oai_image_url,timeout=120); oai_image_get_response.raise_for_status(); oai_pil_image = Image.open(io.BytesIO(oai_image_get_response.content));
277
+ if oai_pil_image.mode!='RGB': oai_pil_image=oai_pil_image.convert('RGB')
278
+ oai_pil_image.save(filepath_for_base_image_output); logger.info(f"DALL-E base img saved: {filepath_for_base_image_output}"); path_to_input_image_for_runway=filepath_for_base_image_output; asset_info_return_obj={'path':filepath_for_base_image_output,'type':'image','error':False,'prompt_used':image_generation_prompt_text,'revised_prompt':oai_revised_prompt}; break
279
+ except openai.RateLimitError as e_dalle_rl: logger.warning(f"OpenAI RateLimit Att {current_attempt_dalle}:{e_dalle_rl}.Retry...");time.sleep(5*current_attempt_dalle);asset_info_return_obj['error_message']=str(e_dalle_rl)
280
+ except openai.APIError as e_dalle_api: logger.error(f"OpenAI APIError Att {current_attempt_dalle}:{e_dalle_api}");asset_info_return_obj['error_message']=str(e_dalle_api);break
281
+ except requests.exceptions.RequestException as e_dalle_req: logger.error(f"Requests Err DALL-E Att {current_attempt_dalle}:{e_dalle_req}");asset_info_return_obj['error_message']=str(e_dalle_req);break
282
+ except Exception as e_dalle_gen: logger.error(f"General DALL-E Err Att {current_attempt_dalle}:{e_dalle_gen}",exc_info=True);asset_info_return_obj['error_message']=str(e_dalle_gen);break
283
+ if asset_info_return_obj['error']: logger.warning(f"DALL-E failed after {current_attempt_dalle} attempts for base img.")
284
+ if asset_info_return_obj['error'] and self.USE_PEXELS:
285
+ logger.info("Trying Pexels for base img.");pexels_query_text_val = scene_data_dictionary.get('pexels_search_query_감독',f"{scene_data_dictionary.get('emotional_beat','')} {scene_data_dictionary.get('setting_description','')}");pexels_path_result = self._search_pexels_image(pexels_query_text_val, filename_for_base_image_output);
286
+ if pexels_path_result:path_to_input_image_for_runway=pexels_path_result;asset_info_return_obj={'path':pexels_path_result,'type':'image','error':False,'prompt_used':f"Pexels:{pexels_query_text_val}"}
287
+ else:current_error_msg_pexels=asset_info_return_obj.get('error_message',"");asset_info_return_obj['error_message']=(current_error_msg_pexels+" Pexels failed for base.").strip()
288
+ if asset_info_return_obj['error']:
289
+ logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");placeholder_prompt_text_val =asset_info_return_obj.get('prompt_used',image_generation_prompt_text);placeholder_path_result=self._create_placeholder_image_content(f"[Base Placeholder]{placeholder_prompt_text_val[:70]}...",filename_for_base_image_output);
290
+ if placeholder_path_result:path_to_input_image_for_runway=placeholder_path_result;asset_info_return_obj={'path':placeholder_path_result,'type':'image','error':False,'prompt_used':placeholder_prompt_text_val}
291
+ else:current_error_msg_ph=asset_info_return_obj.get('error_message',"");asset_info_return_obj['error_message']=(current_error_msg_ph+" Base placeholder failed.").strip()
292
+ if generate_as_video_clip_flag:
293
+ if not path_to_input_image_for_runway:logger.error("RunwayML video: base img failed.");asset_info_return_obj['error']=True;asset_info_return_obj['error_message']=(asset_info_return_obj.get('error_message',"")+" Base img miss, Runway abort.").strip();asset_info_return_obj['type']='none';return asset_info_return_obj
294
+ if self.USE_RUNWAYML:
295
+ runway_generated_video_path=self._generate_video_clip_with_runwayml(motion_prompt_text_for_video,path_to_input_image_for_runway,base_name_current_asset,runway_target_duration_val)
296
+ if runway_generated_video_path and os.path.exists(runway_generated_video_path):asset_info_return_obj={'path':runway_generated_video_path,'type':'video','error':False,'prompt_used':motion_prompt_text_for_video,'base_image_path':path_to_input_image_for_runway}
297
+ else:logger.warning(f"RunwayML video failed for {base_name_current_asset}. Fallback to base img.");asset_info_return_obj['error']=True;asset_info_return_obj['error_message']=(asset_info_return_obj.get('error_message',"Base img ok.")+" RunwayML video fail; use base img.").strip();asset_info_return_obj['path']=path_to_input_image_for_runway;asset_info_return_obj['type']='image';asset_info_return_obj['prompt_used']=image_generation_prompt_text
298
+ else:logger.warning("RunwayML selected but disabled. Use base img.");asset_info_return_obj['error']=True;asset_info_return_obj['error_message']=(asset_info_return_obj.get('error_message',"Base img ok.")+" RunwayML disabled; use base img.").strip();asset_info_return_obj['path']=path_to_input_image_for_runway;asset_info_return_obj['type']='image';asset_info_return_obj['prompt_used']=image_generation_prompt_text
299
+ return asset_info_return_obj
300
 
301
+ def generate_narration_audio(self, narration_text, output_fn="narration_overall.mp3"):
302
+ if not self.USE_ELEVENLABS or not self.elevenlabs_client_instance or not narration_text: logger.info("11L conditions not met. Skip audio."); return None
303
+ narration_fp = os.path.join(self.output_dir, output_fn)
304
+ try:
305
+ logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): \"{narration_text[:70]}...\"")
306
+ stream_method = None
307
+ if hasattr(self.elevenlabs_client_instance,'text_to_speech') and hasattr(self.elevenlabs_client_instance.text_to_speech,'stream'): stream_method=self.elevenlabs_client_instance.text_to_speech.stream; logger.info("Using 11L .text_to_speech.stream()")
308
+ elif hasattr(self.elevenlabs_client_instance,'generate_stream'): stream_method=self.elevenlabs_client_instance.generate_stream; logger.info("Using 11L .generate_stream()")
309
+ elif hasattr(self.elevenlabs_client_instance,'generate'):
310
+ logger.info("Using 11L .generate() (non-streaming).")
311
+ voice_p = Voice(voice_id=str(self.elevenlabs_voice_id),settings=self.elevenlabs_voice_settings_obj) if Voice and self.elevenlabs_voice_settings_obj else str(self.elevenlabs_voice_id)
312
+ audio_b = self.elevenlabs_client_instance.generate(text=narration_text,voice=voice_p,model="eleven_multilingual_v2")
313
+ with open(narration_fp,"wb") as f_audio: f_audio.write(audio_b); logger.info(f"11L audio (non-stream): {narration_fp}"); return narration_fp
314
+ else: logger.error("No recognized 11L audio method."); return None # This path should ideally not be reached if client initialized
315
+
316
+ # This block only executes if a streaming method was found
317
+ if stream_method:
318
+ voice_stream_params={"voice_id":str(self.elevenlabs_voice_id)}
319
+ if self.elevenlabs_voice_settings_obj:
320
+ if hasattr(self.elevenlabs_voice_settings_obj,'model_dump'): voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj.model_dump()
321
+ elif hasattr(self.elevenlabs_voice_settings_obj,'dict'): voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj.dict()
322
+ else: voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj
323
+ audio_iter = stream_method(text=narration_text,model_id="eleven_multilingual_v2",**voice_stream_params)
324
+ with open(narration_fp,"wb") as f_audio_stream:
325
+ for chunk_item in audio_iter:
326
+ if chunk_item: f_audio_stream.write(chunk_item)
327
+ logger.info(f"11L audio (stream): {narration_fp}"); return narration_fp
328
+ else: # Should be caught by the first check, but as a safeguard
329
+ logger.error("Logical error: No streaming method assigned but non-streaming path not taken."); return None
330
+ except AttributeError as e_11l_attr: logger.error(f"11L SDK AttrError: {e_11l_attr}. SDK/methods changed?", exc_info=True); return None
331
+ except Exception as e_11l_gen: logger.error(f"11L audio gen error: {e_11l_gen}", exc_info=True); return None
332
 
333
+ def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
334
+ if not asset_data_list: logger.warning("No assets for animatic."); return None
335
+ processed_moviepy_clips_list = []; narration_audio_clip_mvpy = None; final_video_output_clip = None
336
+ logger.info(f"Assembling from {len(asset_data_list)} assets. Target Frame: {self.video_frame_size}.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
+ for i_asset, asset_info_item_loop in enumerate(asset_data_list):
339
+ path_of_asset, type_of_asset, duration_for_scene = asset_info_item_loop.get('path'), asset_info_item_loop.get('type'), asset_info_item_loop.get('duration', 4.5)
340
+ num_of_scene, action_in_key = asset_info_item_loop.get('scene_num', i_asset + 1), asset_info_item_loop.get('key_action', '')
341
+ logger.info(f"S{num_of_scene}: Path='{path_of_asset}', Type='{type_of_asset}', Dur='{duration_for_scene}'s")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
 
343
+ if not (path_of_asset and os.path.exists(path_of_asset)): logger.warning(f"S{num_of_scene}: Not found '{path_of_asset}'. Skip."); continue
344
+ if duration_for_scene <= 0: logger.warning(f"S{num_of_scene}: Invalid duration ({duration_for_scene}s). Skip."); continue
345
+
346
+ active_scene_clip = None
347
+ try:
348
+ if type_of_asset == 'image':
349
+ pil_img_original = Image.open(path_of_asset); logger.debug(f"S{num_of_scene} (0-Load): Original. Mode:{pil_img_original.mode}, Size:{pil_img_original.size}"); pil_img_original.save(os.path.join(self.output_dir,f"debug_0_ORIGINAL_S{num_of_scene}.png"))
350
+ img_rgba_intermediate = pil_img_original.convert('RGBA') if pil_img_original.mode != 'RGBA' else pil_img_original.copy().convert('RGBA'); logger.debug(f"S{num_of_scene} (1-ToRGBA): Mode:{img_rgba_intermediate.mode}, Size:{img_rgba_intermediate.size}"); img_rgba_intermediate.save(os.path.join(self.output_dir,f"debug_1_AS_RGBA_S{num_of_scene}.png"))
351
+ thumbnailed_img_rgba = img_rgba_intermediate.copy(); resample_filter_pil = Image.Resampling.LANCZOS if hasattr(Image.Resampling,'LANCZOS') else Image.BILINEAR; thumbnailed_img_rgba.thumbnail(self.video_frame_size, resample_filter_pil); logger.debug(f"S{num_of_scene} (2-Thumbnail): Mode:{thumbnailed_img_rgba.mode}, Size:{thumbnailed_img_rgba.size}"); thumbnailed_img_rgba.save(os.path.join(self.output_dir,f"debug_2_THUMBNAIL_RGBA_S{num_of_scene}.png"))
352
+ canvas_for_compositing_rgba = Image.new('RGBA', self.video_frame_size, (0,0,0,0)); pos_x_paste = (self.video_frame_size[0] - thumbnailed_img_rgba.width) // 2; pos_y_paste = (self.video_frame_size[1] - thumbnailed_img_rgba.height) // 2; canvas_for_compositing_rgba.paste(thumbnailed_img_rgba, (pos_x_paste, pos_y_paste), thumbnailed_img_rgba); logger.debug(f"S{num_of_scene} (3-PasteOnRGBA): Mode:{canvas_for_compositing_rgba.mode}, Size:{canvas_for_compositing_rgba.size}"); canvas_for_compositing_rgba.save(os.path.join(self.output_dir,f"debug_3_COMPOSITED_RGBA_S{num_of_scene}.png"))
353
+ final_rgb_image_for_pil = Image.new("RGB", self.video_frame_size, (0, 0, 0));
354
+ if canvas_for_compositing_rgba.mode == 'RGBA': final_rgb_image_for_pil.paste(canvas_for_compositing_rgba, mask=canvas_for_compositing_rgba.split()[3])
355
+ else: final_rgb_image_for_pil.paste(canvas_for_compositing_rgba)
356
+ logger.debug(f"S{num_of_scene} (4-ToRGB): Final RGB. Mode:{final_rgb_image_for_pil.mode}, Size:{final_rgb_image_for_pil.size}")
357
+ debug_path_img_pre_numpy = os.path.join(self.output_dir,f"debug_4_PRE_NUMPY_RGB_S{num_of_scene}.png"); final_rgb_image_for_pil.save(debug_path_img_pre_numpy); logger.info(f"CRITICAL DEBUG: Saved PRE_NUMPY_RGB_S{num_of_scene} to {debug_path_img_pre_numpy}")
358
+
359
+ numpy_frame_arr = np.array(final_rgb_image_for_pil, dtype=np.uint8)
360
+ if not numpy_frame_arr.flags['C_CONTIGUOUS']: numpy_frame_arr = np.ascontiguousarray(numpy_frame_arr, dtype=np.uint8)
361
+ logger.debug(f"S{num_of_scene} (5-NumPy): Final NumPy. Shape:{numpy_frame_arr.shape}, DType:{numpy_frame_arr.dtype}, Flags:{numpy_frame_arr.flags}")
362
+ if numpy_frame_arr.size == 0 or numpy_frame_arr.ndim != 3 or numpy_frame_arr.shape[2] != 3: logger.error(f"S{num_of_scene}: Invalid NumPy shape/size ({numpy_frame_arr.shape}). Skipping."); continue
363
+
364
+ base_image_clip_mvpy = ImageClip(numpy_frame_arr, transparent=False, ismask=False).set_duration(duration_for_scene)
365
+ logger.debug(f"S{num_of_scene} (6-ImageClip): Base ImageClip. Duration: {base_image_clip_mvpy.duration}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
 
367
+ debug_path_moviepy_frame = os.path.join(self.output_dir,f"debug_7_MOVIEPY_FRAME_S{num_of_scene}.png")
368
+ try: # Corrected try-except for save_frame
369
+ save_frame_time = min(0.1, base_image_clip_mvpy.duration / 2 if base_image_clip_mvpy.duration > 0 else 0.1)
370
+ base_image_clip_mvpy.save_frame(debug_path_moviepy_frame, t=save_frame_time)
371
+ logger.info(f"CRITICAL DEBUG: Saved frame FROM MOVIEPY ImageClip S{num_of_scene} to {debug_path_moviepy_frame}")
372
+ except Exception as e_save_mvpy_frame:
373
+ logger.error(f"DEBUG: Error saving frame FROM MOVIEPY ImageClip S{num_of_scene}: {e_save_mvpy_frame}", exc_info=True)
374
+
375
+ fx_image_clip_mvpy = base_image_clip_mvpy
376
+ try: # Ken Burns try block
377
+ scale_end_kb_val = random.uniform(1.03, 1.08)
378
+ if duration_for_scene > 0: fx_image_clip_mvpy = base_image_clip_mvpy.fx(vfx.resize, lambda t_val: 1 + (scale_end_kb_val - 1) * (t_val / duration_for_scene)).set_position('center'); logger.debug(f"S{num_of_scene} (8-KenBurns): Ken Burns applied.")
379
+ else: logger.warning(f"S{num_of_scene}: Duration zero, skipping Ken Burns.")
380
+ except Exception as e_kb_fx_loop: # Except for Ken Burns
381
+ logger.error(f"S{num_of_scene} Ken Burns error: {e_kb_fx_loop}", exc_info=False)
382
+ active_scene_clip = fx_image_clip_mvpy
383
+ elif type_of_asset == 'video':
384
+ source_video_clip_obj=None
385
+ try:
386
+ logger.debug(f"S{num_of_scene}: Loading VIDEO asset: {path_of_asset}")
387
+ source_video_clip_obj=VideoFileClip(path_of_asset,target_resolution=(self.video_frame_size[1],self.video_frame_size[0])if self.video_frame_size else None, audio=False)
388
+ temp_video_clip_obj_loop=source_video_clip_obj
389
+ if source_video_clip_obj.duration!=duration_for_scene:
390
+ if source_video_clip_obj.duration>duration_for_scene:temp_video_clip_obj_loop=source_video_clip_obj.subclip(0,duration_for_scene)
391
+ else:
392
+ if duration_for_scene/source_video_clip_obj.duration > 1.5 and source_video_clip_obj.duration>0.1:temp_video_clip_obj_loop=source_video_clip_obj.loop(duration=duration_for_scene)
393
+ else:temp_video_clip_obj_loop=source_video_clip_obj.set_duration(source_video_clip_obj.duration);logger.info(f"S{num_of_scene} Video clip ({source_video_clip_obj.duration:.2f}s) shorter than target ({duration_for_scene:.2f}s).")
394
+ active_scene_clip=temp_video_clip_obj_loop.set_duration(duration_for_scene)
395
+ if active_scene_clip.size!=list(self.video_frame_size):active_scene_clip=active_scene_clip.resize(self.video_frame_size)
396
+ logger.debug(f"S{num_of_scene}: Video asset processed. Final duration: {active_scene_clip.duration:.2f}s")
397
+ except Exception as e_vid_load_loop:logger.error(f"S{num_of_scene} Video load error '{path_of_asset}':{e_vid_load_loop}",exc_info=True);continue
398
+ finally:
399
+ if source_video_clip_obj and source_video_clip_obj is not active_scene_clip and hasattr(source_video_clip_obj,'close'):
400
+ try: source_video_clip_obj.close()
401
+ except Exception as e_close_src_vid: logger.warning(f"S{num_of_scene}: Error closing source VideoFileClip: {e_close_src_vid}")
402
+ else: logger.warning(f"S{num_of_scene} Unknown asset type '{type_of_asset}'. Skipping."); continue
403
+
404
+ if active_scene_clip and action_in_key: # Text Overlay
405
+ try:
406
+ dur_text_overlay_val=min(active_scene_clip.duration-0.5,active_scene_clip.duration*0.8)if active_scene_clip.duration>0.5 else (active_scene_clip.duration if active_scene_clip.duration > 0 else 0)
407
+ start_text_overlay_val=0.25 if active_scene_clip.duration > 0.5 else 0
408
+ if dur_text_overlay_val > 0:
409
+ text_clip_for_overlay_obj=TextClip(f"Scene {num_of_scene}\n{action_in_key}",fontsize=self.VIDEO_OVERLAY_FONT_SIZE,color=self.VIDEO_OVERLAY_FONT_COLOR,font=self.active_moviepy_font_name,bg_color='rgba(10,10,20,0.7)',method='caption',align='West',size=(self.video_frame_size[0]*0.9,None),kerning=-1,stroke_color='black',stroke_width=1.5).set_duration(dur_text_overlay_val).set_start(start_text_overlay_val).set_position(('center',0.92),relative=True)
410
+ active_scene_clip=CompositeVideoClip([active_scene_clip,text_clip_for_overlay_obj],size=self.video_frame_size,use_bgclip=True)
411
+ logger.debug(f"S{num_of_scene}: Text overlay composited.")
412
+ else: logger.warning(f"S{num_of_scene}: Text overlay duration zero or negative ({dur_text_overlay_val}). Skipping text overlay.")
413
+ except Exception as e_txt_comp_loop:logger.error(f"S{num_of_scene} TextClip compositing error:{e_txt_comp_loop}. Proceeding without text for this scene.",exc_info=True)
414
+
415
+ if active_scene_clip: processed_moviepy_clips_list.append(active_scene_clip); logger.info(f"S{num_of_scene}: Asset successfully processed. Clip duration: {active_scene_clip.duration:.2f}s. Added to final list.")
416
+ except Exception as e_asset_loop_main_exc: logger.error(f"MAJOR UNHANDLED ERROR processing asset for S{num_of_scene} (Path: {path_of_asset}): {e_asset_loop_main_exc}", exc_info=True)
417
+ finally:
418
+ if active_scene_clip and active_scene_clip not in processed_moviepy_clips_list and hasattr(active_scene_clip,'close'): # Only close if not added to list
419
+ try: active_scene_clip.close(); logger.debug(f"S{num_of_scene}: Closed active_scene_clip in asset loop finally block because it wasn't added.")
420
+ except Exception as e_close_active_err: logger.warning(f"S{num_of_scene}: Error closing active_scene_clip in error handler: {e_close_active_err}")
421
+
422
+ if not processed_moviepy_clips_list: logger.warning("No MoviePy clips were successfully processed. Aborting animatic assembly before concatenation."); return None
423
+ transition_duration_val=0.75
424
  try:
425
+ logger.info(f"Concatenating {len(processed_moviepy_clips_list)} processed clips for final animatic.");
426
+ if len(processed_moviepy_clips_list)>1: final_video_output_clip=concatenate_videoclips(processed_moviepy_clips_list, padding=-transition_duration_val if transition_duration_val > 0 else 0, method="compose")
427
+ elif processed_moviepy_clips_list: final_video_output_clip=processed_moviepy_clips_list[0]
428
+ if not final_video_output_clip: logger.error("Concatenation resulted in a None clip. Aborting."); return None
429
+ logger.info(f"Concatenated animatic base duration:{final_video_output_clip.duration:.2f}s")
430
+ if transition_duration_val > 0 and final_video_output_clip.duration > 0:
431
+ if final_video_output_clip.duration > transition_duration_val * 2: final_video_output_clip=final_video_output_clip.fx(vfx.fadein,transition_duration_val).fx(vfx.fadeout,transition_duration_val)
432
+ else: final_video_output_clip=final_video_output_clip.fx(vfx.fadein,min(transition_duration_val,final_video_output_clip.duration/2.0))
433
+ logger.debug("Applied fade in/out effects to final composite clip.")
434
+ if overall_narration_path and os.path.exists(overall_narration_path) and final_video_output_clip.duration > 0:
435
+ try: narration_audio_clip_mvpy=AudioFileClip(overall_narration_path); logger.info(f"Adding overall narration. Video duration: {final_video_output_clip.duration:.2f}s, Narration duration: {narration_audio_clip_mvpy.duration:.2f}s"); final_video_output_clip=final_video_output_clip.set_audio(narration_audio_clip_mvpy); logger.info("Overall narration successfully added to animatic.")
436
+ except Exception as e_narr_add_final:logger.error(f"Error adding overall narration to animatic:{e_narr_add_final}",exc_info=True)
437
+ elif final_video_output_clip.duration <= 0: logger.warning("Animatic has zero or negative duration before adding audio. Audio will not be added.")
438
+ if final_video_output_clip and final_video_output_clip.duration > 0:
439
+ final_output_path_str=os.path.join(self.output_dir,output_filename); logger.info(f"Writing final animatic video to: {final_output_path_str} (Target Duration: {final_video_output_clip.duration:.2f}s)")
440
+ num_threads = os.cpu_count(); num_threads = num_threads if isinstance(num_threads, int) and num_threads >= 1 else 2
441
+ final_video_output_clip.write_videofile(final_output_path_str, fps=fps, codec='libx264', preset='medium', audio_codec='aac', temp_audiofile=os.path.join(self.output_dir,f'temp-audio-{os.urandom(4).hex()}.m4a'), remove_temp=True, threads=num_threads, logger='bar', bitrate="5000k", ffmpeg_params=["-pix_fmt", "yuv420p"])
442
+ logger.info(f"Animatic video created successfully: {final_output_path_str}"); return final_output_path_str
443
+ else: logger.error("Final animatic clip is invalid or has zero duration. Cannot write video file."); return None
444
+ except Exception as e_vid_write_final_op: logger.error(f"Error during final animatic video file writing or composition stage: {e_vid_write_final_op}", exc_info=True); return None
445
+ finally:
446
+ logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` main finally block.")
447
+ # Only attempt to close clips that are actual MoviePy clip instances and haven't been closed
448
+ # The processed_moviepy_clips_list contains the clips *before* concatenation/final effects.
449
+ # The final_video_output_clip is the result of these operations.
450
+ # Narration clip is separate.
451
+
452
+ # Close clips from the list first
453
+ for clip_obj in processed_moviepy_clips_list:
454
+ if clip_obj and hasattr(clip_obj, 'close'):
455
+ try: clip_obj.close()
456
+ except Exception as e_cl_proc: logger.warning(f"Ignoring error closing a processed clip ({type(clip_obj).__name__}): {e_cl_proc}")
457
+
458
+ # Close narration clip if it exists
459
+ if narration_audio_clip_mvpy and hasattr(narration_audio_clip_mvpy, 'close'):
460
+ try: narration_audio_clip_mvpy.close()
461
+ except Exception as e_cl_narr: logger.warning(f"Ignoring error closing narration clip: {e_cl_narr}")
462
 
463
+ # Close the final composite clip if it exists and is different from single processed clip
464
+ if final_video_output_clip and hasattr(final_video_output_clip, 'close'):
465
+ # Avoid double-closing if it was the only clip in processed_moviepy_clips_list
466
+ if not (len(processed_moviepy_clips_list) == 1 and final_video_output_clip is processed_moviepy_clips_list[0]):
467
+ try: final_video_output_clip.close()
468
+ except Exception as e_cl_final: logger.warning(f"Ignoring error closing final composite clip: {e_cl_final}")