Update app.py
Browse files
app.py
CHANGED
@@ -18,7 +18,7 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(level
|
|
18 |
logger = logging.getLogger(__name__)
|
19 |
|
20 |
# --- Global State Variables & API Key Setup ---
|
21 |
-
def load_api_key(key_name_streamlit, key_name_env, service_name): # Same
|
22 |
key = None; secrets_available = hasattr(st, 'secrets')
|
23 |
try:
|
24 |
if secrets_available and key_name_streamlit in st.secrets:
|
@@ -31,36 +31,23 @@ def load_api_key(key_name_streamlit, key_name_env, service_name): # Same
|
|
31 |
if not key: logger.warning(f"{service_name} API Key NOT FOUND. Related features may be disabled or use fallbacks.")
|
32 |
return key
|
33 |
|
34 |
-
if 'services_initialized' not in st.session_state:
|
35 |
logger.info("Initializing services and API keys for the first time this session...")
|
36 |
st.session_state.GEMINI_API_KEY = load_api_key("GEMINI_API_KEY", "GEMINI_API_KEY", "Gemini")
|
37 |
st.session_state.OPENAI_API_KEY = load_api_key("OPENAI_API_KEY", "OPENAI_API_KEY", "OpenAI/DALL-E")
|
38 |
st.session_state.ELEVENLABS_API_KEY = load_api_key("ELEVENLABS_API_KEY", "ELEVENLABS_API_KEY", "ElevenLabs")
|
39 |
st.session_state.PEXELS_API_KEY = load_api_key("PEXELS_API_KEY", "PEXELS_API_KEY", "Pexels")
|
40 |
-
# --- NEW: Load ElevenLabs Voice ID ---
|
41 |
st.session_state.ELEVENLABS_VOICE_ID_CONFIG = load_api_key("ELEVENLABS_VOICE_ID", "ELEVENLABS_VOICE_ID", "ElevenLabs Voice ID")
|
42 |
-
|
43 |
-
if not st.session_state.GEMINI_API_KEY:
|
44 |
-
st.error("CRITICAL: Gemini API Key is essential and missing!"); logger.critical("Gemini API Key missing. Halting."); st.stop()
|
45 |
-
|
46 |
try:
|
47 |
st.session_state.gemini_handler = GeminiHandler(api_key=st.session_state.GEMINI_API_KEY)
|
48 |
logger.info("GeminiHandler initialized successfully.")
|
49 |
except Exception as e: st.error(f"Failed to init GeminiHandler: {e}"); logger.critical(f"GeminiHandler init failed: {e}", exc_info=True); st.stop()
|
50 |
-
|
51 |
try:
|
52 |
-
|
53 |
-
|
54 |
-
st.session_state.visual_engine = VisualEngine(
|
55 |
-
output_dir="temp_cinegen_media",
|
56 |
-
default_elevenlabs_voice_id=st.session_state.ELEVENLABS_VOICE_ID_CONFIG or default_voice
|
57 |
-
)
|
58 |
st.session_state.visual_engine.set_openai_api_key(st.session_state.OPENAI_API_KEY)
|
59 |
-
|
60 |
-
st.session_state.visual_engine.set_elevenlabs_api_key(
|
61 |
-
st.session_state.ELEVENLABS_API_KEY,
|
62 |
-
voice_id_from_secret=st.session_state.ELEVENLABS_VOICE_ID_CONFIG # This might be None
|
63 |
-
)
|
64 |
st.session_state.visual_engine.set_pexels_api_key(st.session_state.PEXELS_API_KEY)
|
65 |
logger.info("VisualEngine initialized and API keys set (or attempted).")
|
66 |
except Exception as e:
|
@@ -68,8 +55,7 @@ if 'services_initialized' not in st.session_state:
|
|
68 |
st.warning("VisualEngine critical setup issue. Some features will be disabled.")
|
69 |
st.session_state.services_initialized = True; logger.info("Service initialization sequence complete.")
|
70 |
|
71 |
-
|
72 |
-
for key, default_val in [
|
73 |
('story_treatment_scenes', []), ('scene_dalle_prompts', []), ('generated_visual_paths', []),
|
74 |
('video_path', None), ('character_definitions', {}), ('global_style_additions', ""),
|
75 |
('overall_narration_audio_path', None), ('narration_script_display', "")
|
@@ -95,30 +81,27 @@ def generate_visual_for_scene_core(scene_index, scene_data, version=1): # Same
|
|
95 |
else:
|
96 |
st.session_state.generated_visual_paths[scene_index] = None; logger.warning(f"Visual generation FAILED for Scene {scene_data.get('scene_number', scene_index+1)}. img_path was: {img_path}"); return False
|
97 |
|
98 |
-
# --- UI Sidebar ---
|
99 |
-
with st.sidebar:
|
100 |
-
st.title("π¬ CineGen AI Ultra+")
|
101 |
-
st.
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
mood = st.selectbox("Overall Mood:", ["Hopeful yet Desperate", "Mysterious & Eerie", "Gritty & Tense"], index=0, key="mood_main_v4")
|
106 |
-
num_scenes = st.slider("Number of Key Scenes:", 1, 3, 1, key="num_scenes_main_v4")
|
107 |
creative_guidance_options = {"Standard Director": "standard", "Artistic Visionary": "more_artistic", "Experimental Storyteller": "experimental_narrative"}
|
108 |
-
selected_creative_guidance_key = st.selectbox("AI Creative Director Style:",
|
109 |
actual_creative_guidance = creative_guidance_options[selected_creative_guidance_key]
|
110 |
|
111 |
-
if st.button("π Generate Cinematic Treatment", type="primary", key="
|
112 |
-
# ... (Main generation flow - same logic for calling phases) ...
|
113 |
initialize_new_project()
|
114 |
if not user_idea.strip(): st.warning("Please provide a story idea.")
|
115 |
else:
|
116 |
with st.status("AI Director is envisioning your masterpiece...", expanded=True) as status:
|
117 |
-
try:
|
118 |
status.write("Phase 1: Gemini crafting cinematic treatment..."); logger.info("Phase 1: Treatment Gen.")
|
119 |
treatment_prompt = create_cinematic_treatment_prompt(user_idea, genre, mood, num_scenes, actual_creative_guidance)
|
120 |
treatment_result_json = st.session_state.gemini_handler.generate_story_breakdown(treatment_prompt)
|
121 |
-
if not isinstance(treatment_result_json, list) or not treatment_result_json: raise ValueError("Gemini invalid scene list.")
|
122 |
st.session_state.story_treatment_scenes = treatment_result_json; num_gen_scenes = len(st.session_state.story_treatment_scenes)
|
123 |
st.session_state.scene_dalle_prompts = [""]*num_gen_scenes; st.session_state.generated_visual_paths = [None]*num_gen_scenes
|
124 |
logger.info(f"Phase 1 complete. {num_gen_scenes} scenes."); status.update(label="Treatment complete! β
Generating visuals...", state="running")
|
@@ -129,12 +112,13 @@ with st.sidebar: # Voice Customization UI slightly changed
|
|
129 |
status.write(f" Visual for Scene {sc_num_log}..."); logger.info(f" Processing visual for Scene {sc_num_log}.")
|
130 |
if generate_visual_for_scene_core(i, sc_data, version=1): visual_successes += 1
|
131 |
current_status_label_ph2 = "Visuals ready! "; next_step_state = "running"
|
132 |
-
if visual_successes == 0 and num_gen_scenes > 0:
|
133 |
-
|
134 |
-
|
135 |
-
|
|
|
|
|
136 |
if next_step_state == "error": st.stop()
|
137 |
-
|
138 |
status.write("Phase 3: Generating narration script..."); logger.info("Phase 3: Narration Script Gen.")
|
139 |
voice_style = st.session_state.get("selected_voice_style_for_generation", "cinematic_trailer")
|
140 |
narr_prompt = create_narration_script_prompt_enhanced(st.session_state.story_treatment_scenes, mood, genre, voice_style)
|
@@ -145,57 +129,44 @@ with st.sidebar: # Voice Customization UI slightly changed
|
|
145 |
final_label = "All components ready! Storyboard below. π"; final_state_val = "complete"
|
146 |
if not st.session_state.overall_narration_audio_path:
|
147 |
final_label = f"{current_status_label_ph2}Storyboard ready (Voiceover skipped/failed)."
|
148 |
-
logger.warning("Voiceover skipped
|
149 |
else: logger.info("Voiceover generated successfully.")
|
150 |
status.update(label=final_label, state=final_state_val, expanded=False)
|
151 |
-
except ValueError as ve: logger.error(f"ValueError: {ve}", exc_info=True); status.update(label=f"Input
|
152 |
except Exception as e: logger.error(f"Unhandled Exception: {e}", exc_info=True); status.update(label=f"An unexpected error occurred: {e}", state="error", expanded=True);
|
153 |
|
154 |
st.markdown("---"); st.markdown("### Fine-Tuning Options")
|
155 |
with st.expander("Define Characters", expanded=False): # Same
|
156 |
-
char_name = st.text_input("Character Name", key="
|
157 |
-
if st.button("Save Character", key="
|
158 |
if char_name and char_desc: st.session_state.character_definitions[char_name.strip().lower()] = char_desc.strip(); st.success(f"Char '{char_name.strip()}' saved.")
|
159 |
else: st.warning("Name and description needed.")
|
160 |
if st.session_state.character_definitions: st.caption("Current Characters:"); [st.markdown(f"**{k.title()}:** _{v}_") for k,v in st.session_state.character_definitions.items()]
|
161 |
-
|
162 |
with st.expander("Global Style Overrides", expanded=False): # Same
|
163 |
presets = { "Default (Director's Choice)": "", "Hyper-Realistic Gritty Noir": "hyper-realistic gritty neo-noir...", "Surreal Dreamscape Fantasy": "surreal dreamscape...", "Vintage Analog Sci-Fi": "70s analog sci-fi..."}
|
164 |
-
sel_preset = st.selectbox("Base Style Preset:", options=list(presets.keys()), key="
|
165 |
-
custom_kw = st.text_area("Additional Custom Style Keywords:", key="
|
166 |
cur_style = st.session_state.global_style_additions
|
167 |
-
if st.button("Apply Global Styles", key="
|
168 |
final_s = presets[sel_preset];
|
169 |
if custom_kw.strip(): final_s = f"{final_s}, {custom_kw.strip()}" if final_s else custom_kw.strip()
|
170 |
st.session_state.global_style_additions = final_s.strip(); cur_style = final_s.strip()
|
171 |
if cur_style: st.success("Global styles applied!")
|
172 |
else: st.info("Global style additions cleared.")
|
173 |
if cur_style: st.caption(f"Active global styles: \"{cur_style}\"")
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
default_voice_from_secret = st.session_state.get("ELEVENLABS_VOICE_ID_CONFIG", "Rachel") # Default if secret not set
|
178 |
-
|
179 |
-
user_voice_id_override = st.text_input(
|
180 |
-
"ElevenLabs Voice ID (optional - override secret/default):",
|
181 |
-
value=default_voice_from_secret, # Pre-fill with secret or default
|
182 |
-
key="el_voice_id_override_v4",
|
183 |
-
help="Enter a specific Voice ID from your ElevenLabs account. If empty, uses the one from secrets or a default."
|
184 |
-
)
|
185 |
-
|
186 |
prompt_v_styles = {"Cinematic Trailer": "cinematic_trailer", "Neutral Documentary": "documentary_neutral", "Character Introspection": "introspective_character"}
|
187 |
-
sel_prompt_v_style_key = st.selectbox("Narration Script Style:", list(prompt_v_styles.keys()), key="
|
188 |
-
|
189 |
-
if st.button("Set Voice & Narration Style", key="set_voice_btn_ultra_v4"):
|
190 |
final_voice_id_to_use = user_voice_id_override.strip() or default_voice_from_secret
|
191 |
-
if hasattr(st.session_state, 'visual_engine'):
|
192 |
-
st.session_state.visual_engine.elevenlabs_voice_id = final_voice_id_to_use
|
193 |
st.session_state.selected_voice_style_for_generation = prompt_v_styles[sel_prompt_v_style_key]
|
194 |
-
st.success(f"Narrator Voice ID
|
195 |
-
logger.info(f"User updated ElevenLabs Voice ID to: {final_voice_id_to_use}
|
196 |
-
|
197 |
|
198 |
-
# --- Main Content Area ---
|
199 |
st.header("π¬ Cinematic Storyboard & Treatment")
|
200 |
if st.session_state.narration_script_display:
|
201 |
with st.expander("π View Full Narration Script", expanded=False): st.markdown(f"> _{st.session_state.narration_script_display}_")
|
@@ -204,10 +175,10 @@ if not st.session_state.story_treatment_scenes: st.info("Use the sidebar to gene
|
|
204 |
else:
|
205 |
for i_main, scene_content_display in enumerate(st.session_state.story_treatment_scenes):
|
206 |
scene_n = scene_content_display.get('scene_number', i_main + 1); scene_t = scene_content_display.get('scene_title', 'Untitled')
|
207 |
-
key_base = f"s{scene_n}_{''.join(filter(str.isalnum, scene_t[:10]))}
|
208 |
if "director_note" in scene_content_display and scene_content_display['director_note']: st.info(f"π¬ Director Note S{scene_n}: {scene_content_display['director_note']}")
|
209 |
st.subheader(f"SCENE {scene_n}: {scene_t.upper()}"); col_d, col_v = st.columns([0.45, 0.55])
|
210 |
-
with col_d: # Scene Details (same display
|
211 |
with st.expander("π Scene Treatment", expanded=True):
|
212 |
st.markdown(f"**Beat:** {scene_content_display.get('emotional_beat', 'N/A')}"); st.markdown(f"**Setting:** {scene_content_display.get('setting_description', 'N/A')}"); st.markdown(f"**Chars:** {', '.join(scene_content_display.get('characters_involved', ['N/A']))}"); st.markdown(f"**Focus Moment:** _{scene_content_display.get('character_focus_moment', 'N/A')}_"); st.markdown(f"**Plot Beat:** {scene_content_display.get('key_plot_beat', 'N/A')}"); st.markdown(f"**Dialogue Hook:** `\"{scene_content_display.get('suggested_dialogue_hook', '...')}\"`"); st.markdown("---"); st.markdown(f"**Dir. Visual Style:** _{scene_content_display.get('PROACTIVE_visual_style_κ°λ
', 'N/A')}_"); st.markdown(f"**Dir. Camera:** _{scene_content_display.get('PROACTIVE_camera_work_κ°λ
', 'N/A')}_"); st.markdown(f"**Dir. Sound:** _{scene_content_display.get('PROACTIVE_sound_design_κ°λ
', 'N/A')}_")
|
213 |
cur_d_prompt = st.session_state.scene_dalle_prompts[i_main] if i_main < len(st.session_state.scene_dalle_prompts) else None
|
@@ -217,7 +188,7 @@ else:
|
|
217 |
if pexels_q: st.caption(f"Pexels Fallback Query: `{pexels_q}`")
|
218 |
with col_v: # Image Display and Edit Popovers
|
219 |
cur_img_p = st.session_state.generated_visual_paths[i_main] if i_main < len(st.session_state.generated_visual_paths) else None
|
220 |
-
if cur_img_p and os.path.exists(cur_img_p): st.image(cur_img_p, caption=f"Scene {scene_n}: {scene_t}")
|
221 |
else:
|
222 |
if st.session_state.story_treatment_scenes: st.caption("Visual pending/failed.")
|
223 |
|
@@ -231,9 +202,17 @@ else:
|
|
231 |
updated_sc_data = st.session_state.gemini_handler.regenerate_scene_script_details(prompt_text)
|
232 |
st.session_state.story_treatment_scenes[i_main] = updated_sc_data
|
233 |
s_treat_regen.update(label="Treatment updated! Regenerating visual...", state="running")
|
234 |
-
|
235 |
-
|
236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
237 |
if generate_visual_for_scene_core(i_main, updated_sc_data, version=v_num): s_treat_regen.update(label="Treatment & Visual Updated! π", state="complete", expanded=False)
|
238 |
else: s_treat_regen.update(label="Treatment updated, visual failed.", state="complete", expanded=False)
|
239 |
st.rerun()
|
@@ -253,9 +232,17 @@ else:
|
|
253 |
refined_d_prompt = st.session_state.gemini_handler.generate_image_prompt(ref_req_prompt)
|
254 |
st.session_state.scene_dalle_prompts[i_main] = refined_d_prompt
|
255 |
s_visual_regen.update(label="DALL-E prompt refined! Regenerating visual...", state="running")
|
|
|
|
|
256 |
v_num = 1
|
257 |
-
if cur_img_p and os.path.exists(cur_img_p):
|
|
|
|
|
|
|
|
|
|
|
258 |
else: v_num = 1
|
|
|
259 |
if generate_visual_for_scene_core(i_main, scene_content_display, version=v_num): s_visual_regen.update(label="Visual Updated! π", state="complete", expanded=False)
|
260 |
else: s_visual_regen.update(label="Prompt refined, visual failed.", state="complete", expanded=False)
|
261 |
st.rerun()
|
@@ -265,13 +252,13 @@ else:
|
|
265 |
|
266 |
# Video Generation Button & Display (same logic)
|
267 |
if st.session_state.story_treatment_scenes and any(p for p in st.session_state.generated_visual_paths if p is not None):
|
268 |
-
if st.button("π¬ Assemble Narrated Cinematic Animatic", key="
|
269 |
with st.status("Assembling Ultra Animatic...", expanded=True) as status_vid:
|
270 |
img_data_vid = []
|
271 |
for i_v, sc_c in enumerate(st.session_state.story_treatment_scenes):
|
272 |
img_p_v = st.session_state.generated_visual_paths[i_v] if i_v < len(st.session_state.generated_visual_paths) else None
|
273 |
if img_p_v and os.path.exists(img_p_v):
|
274 |
-
img_data_vid.append({'path':img_p_v, 'scene_num':sc_c.get('scene_number',i_v+1), 'key_action':sc_c.get('key_plot_beat','')}); status_vid.write(f"Adding Scene {sc_c.get('scene_number', i_v + 1)}
|
275 |
if img_data_vid:
|
276 |
status_vid.write("Calling video engine..."); st.session_state.video_path = st.session_state.visual_engine.create_video_from_images(
|
277 |
img_data_vid, overall_narration_path=st.session_state.overall_narration_audio_path,
|
@@ -287,7 +274,7 @@ else:
|
|
287 |
with open(st.session_state.video_path, 'rb') as vf_obj: video_bytes = vf_obj.read()
|
288 |
st.video(video_bytes, format="video/mp4")
|
289 |
with open(st.session_state.video_path, "rb") as fp_dl:
|
290 |
-
st.download_button(label="Download Ultra Animatic", data=fp_dl, file_name=os.path.basename(st.session_state.video_path), mime="video/mp4", use_container_width=True, key="
|
291 |
except Exception as e: st.error(f"Error displaying video: {e}"); logger.error(f"Error displaying video: {e}", exc_info=True)
|
292 |
|
293 |
# --- Footer ---
|
|
|
18 |
logger = logging.getLogger(__name__)
|
19 |
|
20 |
# --- Global State Variables & API Key Setup ---
|
21 |
+
def load_api_key(key_name_streamlit, key_name_env, service_name): # Same as previous
|
22 |
key = None; secrets_available = hasattr(st, 'secrets')
|
23 |
try:
|
24 |
if secrets_available and key_name_streamlit in st.secrets:
|
|
|
31 |
if not key: logger.warning(f"{service_name} API Key NOT FOUND. Related features may be disabled or use fallbacks.")
|
32 |
return key
|
33 |
|
34 |
+
if 'services_initialized' not in st.session_state: # Same as previous
|
35 |
logger.info("Initializing services and API keys for the first time this session...")
|
36 |
st.session_state.GEMINI_API_KEY = load_api_key("GEMINI_API_KEY", "GEMINI_API_KEY", "Gemini")
|
37 |
st.session_state.OPENAI_API_KEY = load_api_key("OPENAI_API_KEY", "OPENAI_API_KEY", "OpenAI/DALL-E")
|
38 |
st.session_state.ELEVENLABS_API_KEY = load_api_key("ELEVENLABS_API_KEY", "ELEVENLABS_API_KEY", "ElevenLabs")
|
39 |
st.session_state.PEXELS_API_KEY = load_api_key("PEXELS_API_KEY", "PEXELS_API_KEY", "Pexels")
|
|
|
40 |
st.session_state.ELEVENLABS_VOICE_ID_CONFIG = load_api_key("ELEVENLABS_VOICE_ID", "ELEVENLABS_VOICE_ID", "ElevenLabs Voice ID")
|
41 |
+
if not st.session_state.GEMINI_API_KEY: st.error("CRITICAL: Gemini API Key is essential and missing!"); logger.critical("Gemini API Key missing. Halting."); st.stop()
|
|
|
|
|
|
|
42 |
try:
|
43 |
st.session_state.gemini_handler = GeminiHandler(api_key=st.session_state.GEMINI_API_KEY)
|
44 |
logger.info("GeminiHandler initialized successfully.")
|
45 |
except Exception as e: st.error(f"Failed to init GeminiHandler: {e}"); logger.critical(f"GeminiHandler init failed: {e}", exc_info=True); st.stop()
|
|
|
46 |
try:
|
47 |
+
default_voice = "Rachel"
|
48 |
+
st.session_state.visual_engine = VisualEngine(output_dir="temp_cinegen_media", default_elevenlabs_voice_id=st.session_state.ELEVENLABS_VOICE_ID_CONFIG or default_voice)
|
|
|
|
|
|
|
|
|
49 |
st.session_state.visual_engine.set_openai_api_key(st.session_state.OPENAI_API_KEY)
|
50 |
+
st.session_state.visual_engine.set_elevenlabs_api_key(st.session_state.ELEVENLABS_API_KEY, voice_id_from_secret=st.session_state.ELEVENLABS_VOICE_ID_CONFIG)
|
|
|
|
|
|
|
|
|
51 |
st.session_state.visual_engine.set_pexels_api_key(st.session_state.PEXELS_API_KEY)
|
52 |
logger.info("VisualEngine initialized and API keys set (or attempted).")
|
53 |
except Exception as e:
|
|
|
55 |
st.warning("VisualEngine critical setup issue. Some features will be disabled.")
|
56 |
st.session_state.services_initialized = True; logger.info("Service initialization sequence complete.")
|
57 |
|
58 |
+
for key, default_val in [ # Same
|
|
|
59 |
('story_treatment_scenes', []), ('scene_dalle_prompts', []), ('generated_visual_paths', []),
|
60 |
('video_path', None), ('character_definitions', {}), ('global_style_additions', ""),
|
61 |
('overall_narration_audio_path', None), ('narration_script_display', "")
|
|
|
81 |
else:
|
82 |
st.session_state.generated_visual_paths[scene_index] = None; logger.warning(f"Visual generation FAILED for Scene {scene_data.get('scene_number', scene_index+1)}. img_path was: {img_path}"); return False
|
83 |
|
84 |
+
# --- UI Sidebar --- (Same as previous, with unique keys for this pass if needed)
|
85 |
+
with st.sidebar:
|
86 |
+
st.title("π¬ CineGen AI Ultra+"); st.markdown("### Creative Seed")
|
87 |
+
user_idea = st.text_area("Core Story Idea / Theme:", "A lone wanderer searches for a mythical oasis...", height=120, key="user_idea_main_v5") # Key updated
|
88 |
+
genre = st.selectbox("Primary Genre:", ["Cyberpunk", "Sci-Fi", "Post-Apocalyptic"], index=2, key="genre_main_v5")
|
89 |
+
mood = st.selectbox("Overall Mood:", ["Hopeful yet Desperate", "Mysterious & Eerie"], index=0, key="mood_main_v5")
|
90 |
+
num_scenes = st.slider("Number of Key Scenes:", 1, 3, 1, key="num_scenes_main_v5")
|
|
|
|
|
91 |
creative_guidance_options = {"Standard Director": "standard", "Artistic Visionary": "more_artistic", "Experimental Storyteller": "experimental_narrative"}
|
92 |
+
selected_creative_guidance_key = st.selectbox("AI Creative Director Style:", list(creative_guidance_options.keys()), key="creative_guidance_select_v5")
|
93 |
actual_creative_guidance = creative_guidance_options[selected_creative_guidance_key]
|
94 |
|
95 |
+
if st.button("π Generate Cinematic Treatment", type="primary", key="generate_treatment_btn_v5", use_container_width=True):
|
|
|
96 |
initialize_new_project()
|
97 |
if not user_idea.strip(): st.warning("Please provide a story idea.")
|
98 |
else:
|
99 |
with st.status("AI Director is envisioning your masterpiece...", expanded=True) as status:
|
100 |
+
try: # Main generation try-except block
|
101 |
status.write("Phase 1: Gemini crafting cinematic treatment..."); logger.info("Phase 1: Treatment Gen.")
|
102 |
treatment_prompt = create_cinematic_treatment_prompt(user_idea, genre, mood, num_scenes, actual_creative_guidance)
|
103 |
treatment_result_json = st.session_state.gemini_handler.generate_story_breakdown(treatment_prompt)
|
104 |
+
if not isinstance(treatment_result_json, list) or not treatment_result_json: raise ValueError("Gemini returned invalid scene list.")
|
105 |
st.session_state.story_treatment_scenes = treatment_result_json; num_gen_scenes = len(st.session_state.story_treatment_scenes)
|
106 |
st.session_state.scene_dalle_prompts = [""]*num_gen_scenes; st.session_state.generated_visual_paths = [None]*num_gen_scenes
|
107 |
logger.info(f"Phase 1 complete. {num_gen_scenes} scenes."); status.update(label="Treatment complete! β
Generating visuals...", state="running")
|
|
|
112 |
status.write(f" Visual for Scene {sc_num_log}..."); logger.info(f" Processing visual for Scene {sc_num_log}.")
|
113 |
if generate_visual_for_scene_core(i, sc_data, version=1): visual_successes += 1
|
114 |
current_status_label_ph2 = "Visuals ready! "; next_step_state = "running"
|
115 |
+
if visual_successes == 0 and num_gen_scenes > 0:
|
116 |
+
logger.error("Visual gen failed all scenes."); current_status_label_ph2 = "Visual gen FAILED for all scenes."; next_step_state="error";
|
117 |
+
status.update(label=current_status_label_ph2, state=next_step_state, expanded=True); st.stop()
|
118 |
+
elif visual_successes < num_gen_scenes:
|
119 |
+
logger.warning(f"Visuals partial ({visual_successes}/{num_gen_scenes})."); current_status_label_ph2 = f"Visuals partially generated ({visual_successes}/{num_gen_scenes}). "
|
120 |
+
status.update(label=f"{current_status_label_ph2}Generating narration script...", state=next_step_state if next_step_state=="error" else "running")
|
121 |
if next_step_state == "error": st.stop()
|
|
|
122 |
status.write("Phase 3: Generating narration script..."); logger.info("Phase 3: Narration Script Gen.")
|
123 |
voice_style = st.session_state.get("selected_voice_style_for_generation", "cinematic_trailer")
|
124 |
narr_prompt = create_narration_script_prompt_enhanced(st.session_state.story_treatment_scenes, mood, genre, voice_style)
|
|
|
129 |
final_label = "All components ready! Storyboard below. π"; final_state_val = "complete"
|
130 |
if not st.session_state.overall_narration_audio_path:
|
131 |
final_label = f"{current_status_label_ph2}Storyboard ready (Voiceover skipped/failed)."
|
132 |
+
logger.warning("Voiceover was skipped or failed.")
|
133 |
else: logger.info("Voiceover generated successfully.")
|
134 |
status.update(label=final_label, state=final_state_val, expanded=False)
|
135 |
+
except ValueError as ve: logger.error(f"ValueError: {ve}", exc_info=True); status.update(label=f"Input or Gemini response error: {ve}", state="error", expanded=True);
|
136 |
except Exception as e: logger.error(f"Unhandled Exception: {e}", exc_info=True); status.update(label=f"An unexpected error occurred: {e}", state="error", expanded=True);
|
137 |
|
138 |
st.markdown("---"); st.markdown("### Fine-Tuning Options")
|
139 |
with st.expander("Define Characters", expanded=False): # Same
|
140 |
+
char_name = st.text_input("Character Name", key="char_name_adv_ultra_v5"); char_desc = st.text_area("Visual Description", key="char_desc_adv_ultra_v5", height=100, placeholder="e.g., Jax: rugged male astronaut...")
|
141 |
+
if st.button("Save Character", key="add_char_adv_ultra_v5"):
|
142 |
if char_name and char_desc: st.session_state.character_definitions[char_name.strip().lower()] = char_desc.strip(); st.success(f"Char '{char_name.strip()}' saved.")
|
143 |
else: st.warning("Name and description needed.")
|
144 |
if st.session_state.character_definitions: st.caption("Current Characters:"); [st.markdown(f"**{k.title()}:** _{v}_") for k,v in st.session_state.character_definitions.items()]
|
|
|
145 |
with st.expander("Global Style Overrides", expanded=False): # Same
|
146 |
presets = { "Default (Director's Choice)": "", "Hyper-Realistic Gritty Noir": "hyper-realistic gritty neo-noir...", "Surreal Dreamscape Fantasy": "surreal dreamscape...", "Vintage Analog Sci-Fi": "70s analog sci-fi..."}
|
147 |
+
sel_preset = st.selectbox("Base Style Preset:", options=list(presets.keys()), key="style_preset_adv_ultra_v5")
|
148 |
+
custom_kw = st.text_area("Additional Custom Style Keywords:", key="custom_style_adv_ultra_v5", height=80, placeholder="e.g., 'Dutch angle'")
|
149 |
cur_style = st.session_state.global_style_additions
|
150 |
+
if st.button("Apply Global Styles", key="apply_styles_adv_ultra_v5"):
|
151 |
final_s = presets[sel_preset];
|
152 |
if custom_kw.strip(): final_s = f"{final_s}, {custom_kw.strip()}" if final_s else custom_kw.strip()
|
153 |
st.session_state.global_style_additions = final_s.strip(); cur_style = final_s.strip()
|
154 |
if cur_style: st.success("Global styles applied!")
|
155 |
else: st.info("Global style additions cleared.")
|
156 |
if cur_style: st.caption(f"Active global styles: \"{cur_style}\"")
|
157 |
+
with st.expander("Voice & Narration Style", expanded=False): # Same
|
158 |
+
default_voice_from_secret = st.session_state.get("ELEVENLABS_VOICE_ID_CONFIG", "Rachel")
|
159 |
+
user_voice_id_override = st.text_input("ElevenLabs Voice ID (optional):", value=default_voice_from_secret, key="el_voice_id_override_v5",help="Overrides secret/default.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
prompt_v_styles = {"Cinematic Trailer": "cinematic_trailer", "Neutral Documentary": "documentary_neutral", "Character Introspection": "introspective_character"}
|
161 |
+
sel_prompt_v_style_key = st.selectbox("Narration Script Style:", list(prompt_v_styles.keys()), key="narr_style_sel_v5", index=0)
|
162 |
+
if st.button("Set Narrator Voice & Style", key="set_voice_btn_ultra_v5"):
|
|
|
163 |
final_voice_id_to_use = user_voice_id_override.strip() or default_voice_from_secret
|
164 |
+
if hasattr(st.session_state, 'visual_engine'): st.session_state.visual_engine.elevenlabs_voice_id = final_voice_id_to_use
|
|
|
165 |
st.session_state.selected_voice_style_for_generation = prompt_v_styles[sel_prompt_v_style_key]
|
166 |
+
st.success(f"Narrator Voice ID: {final_voice_id_to_use}. Script Style: {sel_prompt_v_style_key}")
|
167 |
+
logger.info(f"User updated ElevenLabs Voice ID to: {final_voice_id_to_use}, Script Style: {sel_prompt_v_style_key}")
|
|
|
168 |
|
169 |
+
# --- Main Content Area ---
|
170 |
st.header("π¬ Cinematic Storyboard & Treatment")
|
171 |
if st.session_state.narration_script_display:
|
172 |
with st.expander("π View Full Narration Script", expanded=False): st.markdown(f"> _{st.session_state.narration_script_display}_")
|
|
|
175 |
else:
|
176 |
for i_main, scene_content_display in enumerate(st.session_state.story_treatment_scenes):
|
177 |
scene_n = scene_content_display.get('scene_number', i_main + 1); scene_t = scene_content_display.get('scene_title', 'Untitled')
|
178 |
+
key_base = f"s{scene_n}_{''.join(filter(str.isalnum, scene_t[:10]))}_v5" # Updated key for uniqueness
|
179 |
if "director_note" in scene_content_display and scene_content_display['director_note']: st.info(f"π¬ Director Note S{scene_n}: {scene_content_display['director_note']}")
|
180 |
st.subheader(f"SCENE {scene_n}: {scene_t.upper()}"); col_d, col_v = st.columns([0.45, 0.55])
|
181 |
+
with col_d: # Scene Details (same display)
|
182 |
with st.expander("π Scene Treatment", expanded=True):
|
183 |
st.markdown(f"**Beat:** {scene_content_display.get('emotional_beat', 'N/A')}"); st.markdown(f"**Setting:** {scene_content_display.get('setting_description', 'N/A')}"); st.markdown(f"**Chars:** {', '.join(scene_content_display.get('characters_involved', ['N/A']))}"); st.markdown(f"**Focus Moment:** _{scene_content_display.get('character_focus_moment', 'N/A')}_"); st.markdown(f"**Plot Beat:** {scene_content_display.get('key_plot_beat', 'N/A')}"); st.markdown(f"**Dialogue Hook:** `\"{scene_content_display.get('suggested_dialogue_hook', '...')}\"`"); st.markdown("---"); st.markdown(f"**Dir. Visual Style:** _{scene_content_display.get('PROACTIVE_visual_style_κ°λ
', 'N/A')}_"); st.markdown(f"**Dir. Camera:** _{scene_content_display.get('PROACTIVE_camera_work_κ°λ
', 'N/A')}_"); st.markdown(f"**Dir. Sound:** _{scene_content_display.get('PROACTIVE_sound_design_κ°λ
', 'N/A')}_")
|
184 |
cur_d_prompt = st.session_state.scene_dalle_prompts[i_main] if i_main < len(st.session_state.scene_dalle_prompts) else None
|
|
|
188 |
if pexels_q: st.caption(f"Pexels Fallback Query: `{pexels_q}`")
|
189 |
with col_v: # Image Display and Edit Popovers
|
190 |
cur_img_p = st.session_state.generated_visual_paths[i_main] if i_main < len(st.session_state.generated_visual_paths) else None
|
191 |
+
if cur_img_p and os.path.exists(cur_img_p): st.image(cur_img_p, caption=f"Scene {scene_n}: {scene_t}")
|
192 |
else:
|
193 |
if st.session_state.story_treatment_scenes: st.caption("Visual pending/failed.")
|
194 |
|
|
|
202 |
updated_sc_data = st.session_state.gemini_handler.regenerate_scene_script_details(prompt_text)
|
203 |
st.session_state.story_treatment_scenes[i_main] = updated_sc_data
|
204 |
s_treat_regen.update(label="Treatment updated! Regenerating visual...", state="running")
|
205 |
+
|
206 |
+
# CORRECTED VERSIONING LOGIC
|
207 |
+
v_num = 1
|
208 |
+
if cur_img_p and os.path.exists(cur_img_p):
|
209 |
+
try:
|
210 |
+
base,_=os.path.splitext(os.path.basename(cur_img_p))
|
211 |
+
if '_v' in base: v_num = int(base.split('_v')[-1])+1
|
212 |
+
else: v_num = 2
|
213 |
+
except (ValueError, IndexError, TypeError): v_num = 2
|
214 |
+
else: v_num = 1
|
215 |
+
|
216 |
if generate_visual_for_scene_core(i_main, updated_sc_data, version=v_num): s_treat_regen.update(label="Treatment & Visual Updated! π", state="complete", expanded=False)
|
217 |
else: s_treat_regen.update(label="Treatment updated, visual failed.", state="complete", expanded=False)
|
218 |
st.rerun()
|
|
|
232 |
refined_d_prompt = st.session_state.gemini_handler.generate_image_prompt(ref_req_prompt)
|
233 |
st.session_state.scene_dalle_prompts[i_main] = refined_d_prompt
|
234 |
s_visual_regen.update(label="DALL-E prompt refined! Regenerating visual...", state="running")
|
235 |
+
|
236 |
+
# CORRECTED VERSIONING LOGIC
|
237 |
v_num = 1
|
238 |
+
if cur_img_p and os.path.exists(cur_img_p):
|
239 |
+
try:
|
240 |
+
base,_=os.path.splitext(os.path.basename(cur_img_p))
|
241 |
+
if '_v' in base: v_num = int(base.split('_v')[-1])+1
|
242 |
+
else: v_num = 2
|
243 |
+
except (ValueError, IndexError, TypeError): v_num=2
|
244 |
else: v_num = 1
|
245 |
+
|
246 |
if generate_visual_for_scene_core(i_main, scene_content_display, version=v_num): s_visual_regen.update(label="Visual Updated! π", state="complete", expanded=False)
|
247 |
else: s_visual_regen.update(label="Prompt refined, visual failed.", state="complete", expanded=False)
|
248 |
st.rerun()
|
|
|
252 |
|
253 |
# Video Generation Button & Display (same logic)
|
254 |
if st.session_state.story_treatment_scenes and any(p for p in st.session_state.generated_visual_paths if p is not None):
|
255 |
+
if st.button("π¬ Assemble Narrated Cinematic Animatic", key="assemble_ultra_video_btn_v5", type="primary", use_container_width=True): # Key updated
|
256 |
with st.status("Assembling Ultra Animatic...", expanded=True) as status_vid:
|
257 |
img_data_vid = []
|
258 |
for i_v, sc_c in enumerate(st.session_state.story_treatment_scenes):
|
259 |
img_p_v = st.session_state.generated_visual_paths[i_v] if i_v < len(st.session_state.generated_visual_paths) else None
|
260 |
if img_p_v and os.path.exists(img_p_v):
|
261 |
+
img_data_vid.append({'path':img_p_v, 'scene_num':sc_c.get('scene_number',i_v+1), 'key_action':sc_c.get('key_plot_beat','')}); status_vid.write(f"Adding Scene {sc_c.get('scene_number', i_v + 1)}.")
|
262 |
if img_data_vid:
|
263 |
status_vid.write("Calling video engine..."); st.session_state.video_path = st.session_state.visual_engine.create_video_from_images(
|
264 |
img_data_vid, overall_narration_path=st.session_state.overall_narration_audio_path,
|
|
|
274 |
with open(st.session_state.video_path, 'rb') as vf_obj: video_bytes = vf_obj.read()
|
275 |
st.video(video_bytes, format="video/mp4")
|
276 |
with open(st.session_state.video_path, "rb") as fp_dl:
|
277 |
+
st.download_button(label="Download Ultra Animatic", data=fp_dl, file_name=os.path.basename(st.session_state.video_path), mime="video/mp4", use_container_width=True, key="download_ultra_video_btn_v5" ) # Key updated
|
278 |
except Exception as e: st.error(f"Error displaying video: {e}"); logger.error(f"Error displaying video: {e}", exc_info=True)
|
279 |
|
280 |
# --- Footer ---
|