Update app.py
Browse files
app.py
CHANGED
@@ -1,340 +1,468 @@
|
|
1 |
-
#
|
2 |
-
import
|
|
|
|
|
|
|
3 |
import os
|
|
|
|
|
|
|
|
|
|
|
4 |
import logging
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
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 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
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 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
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 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
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 |
-
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
-
def
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
73 |
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
"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 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
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 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
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 |
-
|
208 |
-
if
|
209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
217 |
|
218 |
-
|
219 |
-
|
220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
221 |
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
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 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
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 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
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 |
-
|
333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
334 |
try:
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
339 |
|
340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
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}")
|