mgbam commited on
Commit
857e0f9
Β·
verified Β·
1 Parent(s): 754c854

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -25
app.py CHANGED
@@ -10,12 +10,13 @@ from core.prompt_engineering import (
10
  create_visual_regeneration_prompt
11
  )
12
  import os
13
- import logging # For better logging
14
 
15
  # --- Configuration & Initialization ---
16
  st.set_page_config(page_title="CineGen AI Ultra+", layout="wide", initial_sidebar_state="expanded")
 
17
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
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):
@@ -24,7 +25,7 @@ def load_api_key(key_name_streamlit, key_name_env, service_name):
24
  if secrets_available and key_name_streamlit in st.secrets:
25
  key = st.secrets[key_name_streamlit]
26
  if key: logger.info(f"{service_name} API Key found in Streamlit secrets.")
27
- except Exception as e: logger.warning(f"Could not access st.secrets for {key_name_streamlit}: {e}")
28
  if not key and key_name_env in os.environ:
29
  key = os.environ[key_name_env]
30
  if key: logger.info(f"{service_name} API Key found in environment variable.")
@@ -39,7 +40,7 @@ if 'services_initialized' not in st.session_state:
39
  st.session_state.PEXELS_API_KEY = load_api_key("PEXELS_API_KEY", "PEXELS_API_KEY", "Pexels")
40
 
41
  if not st.session_state.GEMINI_API_KEY:
42
- st.error("CRITICAL: Gemini API Key is essential and missing! Application cannot proceed."); logger.critical("Gemini API Key missing. Halting."); st.stop()
43
 
44
  try:
45
  st.session_state.gemini_handler = GeminiHandler(api_key=st.session_state.GEMINI_API_KEY)
@@ -54,9 +55,10 @@ if 'services_initialized' not in st.session_state:
54
  logger.info("VisualEngine initialized and API keys set (or attempted).")
55
  except Exception as e:
56
  st.error(f"Failed to init VisualEngine or set its API keys: {e}"); logger.critical(f"VisualEngine init/key setting failed: {e}", exc_info=True)
57
- st.warning("VisualEngine critical setup issue. Some features will be disabled.")
58
  st.session_state.services_initialized = True; logger.info("Service initialization sequence complete.")
59
 
 
60
  for key, default_val in [
61
  ('story_treatment_scenes', []), ('scene_dalle_prompts', []), ('generated_visual_paths', []),
62
  ('video_path', None), ('character_definitions', {}), ('global_style_additions', ""),
@@ -64,7 +66,6 @@ for key, default_val in [
64
  ]:
65
  if key not in st.session_state: st.session_state[key] = default_val
66
 
67
- # --- Helper Functions ---
68
  def initialize_new_project(): # Same
69
  st.session_state.story_treatment_scenes, st.session_state.scene_dalle_prompts, st.session_state.generated_visual_paths = [], [], []
70
  st.session_state.video_path, st.session_state.overall_narration_audio_path, st.session_state.narration_script_display = None, None, ""
@@ -104,10 +105,10 @@ with st.sidebar:
104
  status.write("Phase 1: Gemini crafting cinematic treatment... πŸ“œ"); logger.info("Phase 1: Cinematic Treatment Gen.")
105
  treatment_prompt = create_cinematic_treatment_prompt(user_idea, genre, mood, num_scenes, actual_creative_guidance)
106
  treatment_result_json = st.session_state.gemini_handler.generate_story_breakdown(treatment_prompt)
107
- if not isinstance(treatment_result_json, list) or not treatment_result_json: raise ValueError("Gemini returned invalid scene list.")
108
  st.session_state.story_treatment_scenes = treatment_result_json; num_gen_scenes = len(st.session_state.story_treatment_scenes)
109
  st.session_state.scene_dalle_prompts = [""]*num_gen_scenes; st.session_state.generated_visual_paths = [None]*num_gen_scenes
110
- logger.info(f"Phase 1 complete. {num_gen_scenes} scenes.")
111
  status.update(label="Treatment complete! βœ… Generating visuals...", state="running")
112
 
113
  status.write("Phase 2: Creating visuals (DALL-E/Pexels)... πŸ–ΌοΈ"); logger.info("Phase 2: Visual Gen.")
@@ -118,10 +119,9 @@ with st.sidebar:
118
  if generate_visual_for_scene_core(i, sc_data, version=1): visual_successes += 1
119
 
120
  current_status_label_ph2 = "Visuals ready! "
121
- next_step_state = "running"
122
  if visual_successes == 0 and num_gen_scenes > 0:
123
- logger.error("Visual gen failed all scenes."); current_status_label_ph2 = "Visual gen FAILED for all scenes."; next_step_state="error";
124
- status.update(label=current_status_label_ph2, state=next_step_state, expanded=True); st.stop()
125
  elif visual_successes < num_gen_scenes:
126
  logger.warning(f"Visuals partial ({visual_successes}/{num_gen_scenes})."); current_status_label_ph2 = f"Visuals partially generated ({visual_successes}/{num_gen_scenes}). "
127
  else: logger.info("All visuals OK.")
@@ -137,17 +137,17 @@ with st.sidebar:
137
  st.session_state.overall_narration_audio_path = st.session_state.visual_engine.generate_narration_audio(st.session_state.narration_script_display)
138
 
139
  final_label = "All components ready! Storyboard below. πŸš€"
140
- final_state_val = "complete"
141
  if not st.session_state.overall_narration_audio_path:
142
- final_label = f"{current_status_label_ph2}Storyboard ready (Voiceover skipped/failed)."
143
- logger.warning("Voiceover was skipped or failed.")
144
  else: logger.info("Voiceover generated successfully.")
145
- status.update(label=final_label, state=final_state_val, expanded=False)
146
 
147
- except ValueError as ve: logger.error(f"ValueError: {ve}", exc_info=True); status.update(label=f"Input/Gemini response error: {ve}", state="error", expanded=True);
148
  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);
149
 
150
- st.markdown("---"); st.markdown("### Fine-Tuning Options")
151
  with st.expander("Define Characters", expanded=False):
152
  char_name = st.text_input("Character Name", key="char_name_adv_ultra_v3"); char_desc = st.text_area("Visual Description", key="char_desc_adv_ultra_v3", height=100, placeholder="e.g., Jax: rugged male astronaut...")
153
  if st.button("Save Character", key="add_char_adv_ultra_v3"):
@@ -169,12 +169,12 @@ with st.sidebar:
169
  if cur_style: st.caption(f"Active global styles: \"{cur_style}\"")
170
 
171
  with st.expander("Voice Customization (ElevenLabs)", expanded=False):
172
- el_voices = ["Rachel", "Adam", "Bella", "Antoni", "Elli", "Josh", "Arnold", "Domi"]
173
  engine_v_id = "Rachel";
174
  if hasattr(st.session_state, 'visual_engine') and st.session_state.visual_engine: engine_v_id = st.session_state.visual_engine.elevenlabs_voice_id
175
- try: cur_v_idx = el_voices.index(engine_v_id)
176
  except ValueError: cur_v_idx = 0
177
- sel_el_voice = st.selectbox("Narrator Voice:", el_voices, index=cur_v_idx, key="el_voice_sel_ultra_v3")
178
  prompt_v_styles = {"Cinematic Trailer": "cinematic_trailer", "Neutral Documentary": "documentary_neutral", "Character Introspection": "introspective_character"}
179
  sel_prompt_v_style_key = st.selectbox("Narration Script Style:", list(prompt_v_styles.keys()), key="narr_style_sel_v3")
180
  if st.button("Set Narrator Voice & Style", key="set_voice_btn_ultra_v3"):
@@ -182,7 +182,6 @@ with st.sidebar:
182
  st.session_state.selected_voice_style_for_generation = prompt_v_styles[sel_prompt_v_style_key]
183
  st.success(f"Narrator: {sel_el_voice}. Script Style: {sel_prompt_v_style_key}")
184
 
185
-
186
  # --- Main Content Area ---
187
  st.header("🎬 Cinematic Storyboard & Treatment")
188
  if st.session_state.narration_script_display:
@@ -192,12 +191,11 @@ if not st.session_state.story_treatment_scenes: st.info("Use the sidebar to gene
192
  else:
193
  for i_main, scene_content_display in enumerate(st.session_state.story_treatment_scenes):
194
  scene_n = scene_content_display.get('scene_number', i_main + 1); scene_t = scene_content_display.get('scene_title', 'Untitled')
195
- key_base = f"s{scene_n}_{''.join(filter(str.isalnum, scene_t[:10]))}_v3" # Added version to key_base for uniqueness
196
  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']}")
197
  st.subheader(f"SCENE {scene_n}: {scene_t.upper()}"); col_d, col_v = st.columns([0.45, 0.55])
198
  with col_d:
199
  with st.expander("πŸ“ Scene Treatment", expanded=True):
200
- # ... (markdown display of scene details, same as before) ...
201
  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')}_")
202
  cur_d_prompt = st.session_state.scene_dalle_prompts[i_main] if i_main < len(st.session_state.scene_dalle_prompts) else None
203
  if cur_d_prompt:
@@ -206,7 +204,7 @@ else:
206
  if pexels_q: st.caption(f"Pexels Fallback Query: `{pexels_q}`")
207
  with col_v:
208
  cur_img_p = st.session_state.generated_visual_paths[i_main] if i_main < len(st.session_state.generated_visual_paths) else None
209
- if cur_img_p and os.path.exists(cur_img_p): st.image(cur_img_p, caption=f"Scene {scene_n}: {scene_t}", use_column_width='always')
210
  else:
211
  if st.session_state.story_treatment_scenes: st.caption("Visual pending/failed.")
212
 
@@ -256,7 +254,6 @@ else:
256
  else: st.warning("Please provide feedback.")
257
  st.markdown("---")
258
 
259
- # Video Generation Button & Display (same as previous)
260
  if st.session_state.story_treatment_scenes and any(p for p in st.session_state.generated_visual_paths if p is not None):
261
  if st.button("🎬 Assemble Narrated Cinematic Animatic", key="assemble_ultra_video_btn_v3", type="primary", use_container_width=True):
262
  with st.status("Assembling Ultra Animatic...", expanded=True) as status_vid:
 
10
  create_visual_regeneration_prompt
11
  )
12
  import os
13
+ import logging
14
 
15
  # --- Configuration & Initialization ---
16
  st.set_page_config(page_title="CineGen AI Ultra+", layout="wide", initial_sidebar_state="expanded")
17
+ # Setup logger for this app module
18
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
19
+ logger = logging.getLogger(__name__) # Use __name__ for module-specific logger
20
 
21
  # --- Global State Variables & API Key Setup ---
22
  def load_api_key(key_name_streamlit, key_name_env, service_name):
 
25
  if secrets_available and key_name_streamlit in st.secrets:
26
  key = st.secrets[key_name_streamlit]
27
  if key: logger.info(f"{service_name} API Key found in Streamlit secrets.")
28
+ except Exception as e: logger.warning(f"Could not access st.secrets for {key_name_streamlit} (may be local dev or misconfiguration): {e}")
29
  if not key and key_name_env in os.environ:
30
  key = os.environ[key_name_env]
31
  if key: logger.info(f"{service_name} API Key found in environment variable.")
 
40
  st.session_state.PEXELS_API_KEY = load_api_key("PEXELS_API_KEY", "PEXELS_API_KEY", "Pexels")
41
 
42
  if not st.session_state.GEMINI_API_KEY:
43
+ st.error("CRITICAL: Gemini API Key is essential and missing! Please set it in secrets or environment variables."); logger.critical("Gemini API Key missing. Halting."); st.stop()
44
 
45
  try:
46
  st.session_state.gemini_handler = GeminiHandler(api_key=st.session_state.GEMINI_API_KEY)
 
55
  logger.info("VisualEngine initialized and API keys set (or attempted).")
56
  except Exception as e:
57
  st.error(f"Failed to init VisualEngine or set its API keys: {e}"); logger.critical(f"VisualEngine init/key setting failed: {e}", exc_info=True)
58
+ st.warning("VisualEngine critical setup issue. Some features will be disabled.") # App can continue with placeholders
59
  st.session_state.services_initialized = True; logger.info("Service initialization sequence complete.")
60
 
61
+ # Initialize other session state variables
62
  for key, default_val in [
63
  ('story_treatment_scenes', []), ('scene_dalle_prompts', []), ('generated_visual_paths', []),
64
  ('video_path', None), ('character_definitions', {}), ('global_style_additions', ""),
 
66
  ]:
67
  if key not in st.session_state: st.session_state[key] = default_val
68
 
 
69
  def initialize_new_project(): # Same
70
  st.session_state.story_treatment_scenes, st.session_state.scene_dalle_prompts, st.session_state.generated_visual_paths = [], [], []
71
  st.session_state.video_path, st.session_state.overall_narration_audio_path, st.session_state.narration_script_display = None, None, ""
 
105
  status.write("Phase 1: Gemini crafting cinematic treatment... πŸ“œ"); logger.info("Phase 1: Cinematic Treatment Gen.")
106
  treatment_prompt = create_cinematic_treatment_prompt(user_idea, genre, mood, num_scenes, actual_creative_guidance)
107
  treatment_result_json = st.session_state.gemini_handler.generate_story_breakdown(treatment_prompt)
108
+ if not isinstance(treatment_result_json, list) or not treatment_result_json: raise ValueError("Gemini returned invalid scene list for treatment.")
109
  st.session_state.story_treatment_scenes = treatment_result_json; num_gen_scenes = len(st.session_state.story_treatment_scenes)
110
  st.session_state.scene_dalle_prompts = [""]*num_gen_scenes; st.session_state.generated_visual_paths = [None]*num_gen_scenes
111
+ logger.info(f"Phase 1 complete. Generated {num_gen_scenes} scenes.")
112
  status.update(label="Treatment complete! βœ… Generating visuals...", state="running")
113
 
114
  status.write("Phase 2: Creating visuals (DALL-E/Pexels)... πŸ–ΌοΈ"); logger.info("Phase 2: Visual Gen.")
 
119
  if generate_visual_for_scene_core(i, sc_data, version=1): visual_successes += 1
120
 
121
  current_status_label_ph2 = "Visuals ready! "
 
122
  if visual_successes == 0 and num_gen_scenes > 0:
123
+ logger.error("Visual gen failed all scenes."); current_status_label_ph2 = "Visual gen FAILED for all scenes.";
124
+ status.update(label=current_status_label_ph2, state="error", expanded=True); st.stop()
125
  elif visual_successes < num_gen_scenes:
126
  logger.warning(f"Visuals partial ({visual_successes}/{num_gen_scenes})."); current_status_label_ph2 = f"Visuals partially generated ({visual_successes}/{num_gen_scenes}). "
127
  else: logger.info("All visuals OK.")
 
137
  st.session_state.overall_narration_audio_path = st.session_state.visual_engine.generate_narration_audio(st.session_state.narration_script_display)
138
 
139
  final_label = "All components ready! Storyboard below. πŸš€"
140
+ final_state_val = "complete" # Default to complete
141
  if not st.session_state.overall_narration_audio_path:
142
+ final_label = f"{current_status_label_ph2}Storyboard ready (Voiceover skipped or failed)." # Adjust label if voice failed
143
+ logger.warning("Voiceover was skipped or failed, but other components might be ready.")
144
  else: logger.info("Voiceover generated successfully.")
145
+ status.update(label=final_label, state=final_state_val, expanded=False) # Keep state complete, label reflects issues
146
 
147
+ 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);
148
  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);
149
 
150
+ st.markdown("---"); st.markdown("### Fine-Tuning Options") # UI for these remain same as previous full app.py
151
  with st.expander("Define Characters", expanded=False):
152
  char_name = st.text_input("Character Name", key="char_name_adv_ultra_v3"); char_desc = st.text_area("Visual Description", key="char_desc_adv_ultra_v3", height=100, placeholder="e.g., Jax: rugged male astronaut...")
153
  if st.button("Save Character", key="add_char_adv_ultra_v3"):
 
169
  if cur_style: st.caption(f"Active global styles: \"{cur_style}\"")
170
 
171
  with st.expander("Voice Customization (ElevenLabs)", expanded=False):
172
+ el_voices_conceptual = ["Rachel", "Adam", "Bella", "Antoni", "Elli", "Josh", "Arnold", "Domi", "Fin", "Sarah", "Charlie", "Clyde", "Dorothy", "George"]
173
  engine_v_id = "Rachel";
174
  if hasattr(st.session_state, 'visual_engine') and st.session_state.visual_engine: engine_v_id = st.session_state.visual_engine.elevenlabs_voice_id
175
+ try: cur_v_idx = el_voices_conceptual.index(engine_v_id)
176
  except ValueError: cur_v_idx = 0
177
+ sel_el_voice = st.selectbox("Narrator Voice:", el_voices_conceptual, index=cur_v_idx, key="el_voice_sel_ultra_v3")
178
  prompt_v_styles = {"Cinematic Trailer": "cinematic_trailer", "Neutral Documentary": "documentary_neutral", "Character Introspection": "introspective_character"}
179
  sel_prompt_v_style_key = st.selectbox("Narration Script Style:", list(prompt_v_styles.keys()), key="narr_style_sel_v3")
180
  if st.button("Set Narrator Voice & Style", key="set_voice_btn_ultra_v3"):
 
182
  st.session_state.selected_voice_style_for_generation = prompt_v_styles[sel_prompt_v_style_key]
183
  st.success(f"Narrator: {sel_el_voice}. Script Style: {sel_prompt_v_style_key}")
184
 
 
185
  # --- Main Content Area ---
186
  st.header("🎬 Cinematic Storyboard & Treatment")
187
  if st.session_state.narration_script_display:
 
191
  else:
192
  for i_main, scene_content_display in enumerate(st.session_state.story_treatment_scenes):
193
  scene_n = scene_content_display.get('scene_number', i_main + 1); scene_t = scene_content_display.get('scene_title', 'Untitled')
194
+ key_base = f"s{scene_n}_{''.join(filter(str.isalnum, scene_t[:10]))}_v3"
195
  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']}")
196
  st.subheader(f"SCENE {scene_n}: {scene_t.upper()}"); col_d, col_v = st.columns([0.45, 0.55])
197
  with col_d:
198
  with st.expander("πŸ“ Scene Treatment", expanded=True):
 
199
  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')}_")
200
  cur_d_prompt = st.session_state.scene_dalle_prompts[i_main] if i_main < len(st.session_state.scene_dalle_prompts) else None
201
  if cur_d_prompt:
 
204
  if pexels_q: st.caption(f"Pexels Fallback Query: `{pexels_q}`")
205
  with col_v:
206
  cur_img_p = st.session_state.generated_visual_paths[i_main] if i_main < len(st.session_state.generated_visual_paths) else None
207
+ if cur_img_p and os.path.exists(cur_img_p): st.image(cur_img_p, caption=f"Scene {scene_n}: {scene_t}") # Removed use_column_width
208
  else:
209
  if st.session_state.story_treatment_scenes: st.caption("Visual pending/failed.")
210
 
 
254
  else: st.warning("Please provide feedback.")
255
  st.markdown("---")
256
 
 
257
  if st.session_state.story_treatment_scenes and any(p for p in st.session_state.generated_visual_paths if p is not None):
258
  if st.button("🎬 Assemble Narrated Cinematic Animatic", key="assemble_ultra_video_btn_v3", type="primary", use_container_width=True):
259
  with st.status("Assembling Ultra Animatic...", expanded=True) as status_vid: