mgbam commited on
Commit
fe7d37a
Β·
verified Β·
1 Parent(s): a1354f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +225 -89
app.py CHANGED
@@ -2,41 +2,119 @@
2
  import gradio as gr
3
  import os
4
  import time
5
- # ... (all other imports remain the same)
 
 
 
 
 
6
  from core.llm_services import initialize_text_llms, is_gemini_text_ready, is_hf_text_ready, generate_text_gemini, generate_text_hf
7
  from core.image_services import initialize_image_llms, STABILITY_API_CONFIGURED, OPENAI_DALLE_CONFIGURED, generate_image_stabilityai, generate_image_dalle, ImageGenResponse
8
  from core.story_engine import Story, Scene
9
  from prompts.narrative_prompts import get_narrative_system_prompt, format_narrative_user_prompt
10
  from prompts.image_style_prompts import STYLE_PRESETS, COMMON_NEGATIVE_PROMPTS, format_image_generation_prompt
11
  from core.utils import basic_text_cleanup
12
- import traceback
13
-
14
 
15
- # ... (Initialization, API Status, Model Config, Theme, CSS, create_placeholder_image - all remain the same)
16
  initialize_text_llms()
17
  initialize_image_llms()
 
 
18
  GEMINI_TEXT_IS_READY = is_gemini_text_ready()
19
  HF_TEXT_IS_READY = is_hf_text_ready()
20
  STABILITY_API_IS_READY = STABILITY_API_CONFIGURED
21
  OPENAI_DALLE_IS_READY = OPENAI_DALLE_CONFIGURED
22
- # ... (TEXT_MODELS, IMAGE_PROVIDERS, UI_DEFAULT_KEYS, omega_theme, omega_css, create_placeholder_image as before)
 
23
  TEXT_MODELS = {}
24
  UI_DEFAULT_TEXT_MODEL_KEY = None
25
- if GEMINI_TEXT_IS_READY: TEXT_MODELS["✨ Gemini 1.5 Flash (Narrate)"] = {"id": "gemini-1.5-flash-latest", "type": "gemini"}
26
- if HF_TEXT_IS_READY: TEXT_MODELS["Mistral 7B (Narrate)"] = {"id": "mistralai/Mistral-7B-Instruct-v0.2", "type": "hf_text"}
27
- if TEXT_MODELS: UI_DEFAULT_TEXT_MODEL_KEY = list(TEXT_MODELS.keys())[0]
28
- else: TEXT_MODELS["No Text Models"] = {"id": "dummy", "type": "none"}; UI_DEFAULT_TEXT_MODEL_KEY = "No Text Models"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  IMAGE_PROVIDERS = {}
30
  UI_DEFAULT_IMAGE_PROVIDER_KEY = None
31
- if STABILITY_API_IS_READY: IMAGE_PROVIDERS["🎨 Stability AI"] = "stability_ai"
32
- if OPENAI_DALLE_IS_READY: IMAGE_PROVIDERS["πŸ–ΌοΈ DALL-E (Sim.)"] = "dalle"
33
- if IMAGE_PROVIDERS: UI_DEFAULT_IMAGE_PROVIDER_KEY = list(IMAGE_PROVIDERS.keys())[0]
34
- else: IMAGE_PROVIDERS["No Image Providers"] = "none"; UI_DEFAULT_IMAGE_PROVIDER_KEY = "No Image Providers"
35
- omega_theme = gr.themes.Base(font=[gr.themes.GoogleFont("Lexend Deca")], primary_hue=gr.themes.colors.purple).set(body_background_fill="#0F0F1A", block_background_fill="#1A1A2E", slider_color="#A020F0")
36
- omega_css = "body, .gradio-container { background-color: #0F0F1A !important; color: #D0D0E0 !important; } /* Ensure this is complete */"
37
 
 
 
 
 
 
 
 
38
 
39
- # --- StoryVerse Weaver Orchestrator (MODIFIED `finally` and `yields`) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def add_scene_to_story_orchestrator(
41
  current_story_obj: Story, scene_prompt_text: str, image_style_dropdown: str, artist_style_text: str,
42
  negative_prompt_text: str, text_model_key: str, image_provider_key: str,
@@ -52,15 +130,17 @@ def add_scene_to_story_orchestrator(
52
  ret_story_state = current_story_obj
53
  ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
54
  ret_latest_image = None
55
- ret_latest_narrative_md_obj = gr.Markdown(value="## Processing...\nNarrative being woven...")
56
- ret_status_bar_html_obj = gr.HTML(value="<p class='processing_text status_text'>Processing...</p>")
57
  # ret_log_md will be built up
58
 
59
- # Initial UI update for status, placeholders. Buttons disabled by preceding .click() event.
 
60
  yield {
61
  output_status_bar: gr.HTML(value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
62
- output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals...")),
63
- output_latest_scene_narrative: gr.Markdown(value=" Musing narrative..."),
 
64
  output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator))
65
  }
66
 
@@ -70,21 +150,60 @@ def add_scene_to_story_orchestrator(
70
 
71
  # --- 1. Generate Narrative Text ---
72
  progress(0.1, desc="✍️ Crafting narrative...")
73
- # ... (Full narrative generation logic as before, updating narrative_text_generated and log_accumulator)
74
- narrative_text_generated = "Simulated Narrative for " + scene_prompt_text[:20] # Placeholder for actual call
75
- log_accumulator.append(f" Narrative: Generated (simulated).") # Placeholder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- ret_latest_narrative_str_content = f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}"
78
- ret_latest_narrative_md_obj = gr.Markdown(value=ret_latest_narrative_str_content)
79
- yield { output_latest_scene_narrative: ret_latest_narrative_md_obj,
80
  output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
81
 
82
  # --- 2. Generate Image ---
83
  progress(0.5, desc="🎨 Conjuring visuals...")
84
- # ... (Full image generation logic as before, updating image_generated_pil, image_generation_error_message, log_accumulator)
85
- image_generated_pil = create_placeholder_image("Simulated Image") # Placeholder for actual call
86
- image_generation_error_message = None # Placeholder
87
- log_accumulator.append(f" Image: Generated (simulated).") # Placeholder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
  ret_latest_image = image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010")
90
  yield { output_latest_scene_image: gr.Image(value=ret_latest_image),
@@ -92,14 +211,16 @@ def add_scene_to_story_orchestrator(
92
 
93
  # --- 3. Add Scene to Story Object ---
94
  final_scene_error = None
95
- # ... (Logic to set final_scene_error based on narrative and image errors) ...
 
 
96
 
97
  current_story_obj.add_scene_from_elements(
98
  user_prompt=scene_prompt_text,
99
  narrative_text=narrative_text_generated if "**Narrative Error**" not in narrative_text_generated else "(Narrative gen failed)",
100
  image=image_generated_pil,
101
  image_style_prompt=f"{image_style_dropdown}{f', by {artist_style_text}' if artist_style_text and artist_style_text.strip() else ''}",
102
- image_provider=image_provider_key,
103
  error_message=final_scene_error
104
  )
105
  ret_story_state = current_story_obj
@@ -108,68 +229,89 @@ def add_scene_to_story_orchestrator(
108
  # --- 4. Prepare Final Values for Return Tuple ---
109
  ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
110
  _ , latest_narr_for_display_final_str_temp = current_story_obj.get_latest_scene_details_for_display()
111
- ret_latest_narrative_md_obj = gr.Markdown(value=latest_narr_for_display_final_str_temp)
112
 
113
  status_html_str_temp = f"<p class='error_text status_text'>Scene {current_story_obj.current_scene_number} added with errors.</p>" if final_scene_error else f"<p class='success_text status_text'>🌌 Scene {current_story_obj.current_scene_number} woven!</p>"
114
- ret_status_bar_html_obj = gr.HTML(value=status_html_str_temp)
115
 
116
  progress(1.0, desc="Scene Complete!")
117
 
118
  except ValueError as ve:
119
  log_accumulator.append(f"\n**INPUT/CONFIG ERROR:** {ve}")
120
- ret_status_bar_html_obj = gr.HTML(value=f"<p class='error_text status_text'>❌ CONFIGURATION ERROR: {ve}</p>")
121
- ret_latest_narrative_md_obj = gr.Markdown(value=f"## Error\n{ve}")
122
  except Exception as e:
123
  log_accumulator.append(f"\n**UNEXPECTED RUNTIME ERROR:** {type(e).__name__} - {e}\n{traceback.format_exc()}")
124
- ret_status_bar_html_obj = gr.HTML(value=f"<p class='error_text status_text'>❌ UNEXPECTED ERROR: {type(e).__name__}. Check logs.</p>")
125
- ret_latest_narrative_md_obj = gr.Markdown(value=f"## Unexpected Error\n{type(e).__name__}: {e}\nSee log for details.")
126
- # `finally` block is removed from here for this test. Button re-enabling will be handled by a separate .then()
127
 
128
  current_total_time = time.time() - start_time
129
  log_accumulator.append(f" Cycle ended at {time.strftime('%H:%M:%S')}. Total time: {current_total_time:.2f}s")
130
- ret_log_md = gr.Markdown(value="\n".join(log_accumulator))
131
 
132
  # This is the FINAL return. It must be a tuple matching the `outputs` list of engage_button.click()
133
  return (
134
  ret_story_state,
135
  ret_gallery,
136
  ret_latest_image,
137
- ret_latest_narrative_md_obj, # Return the Gradio component update object
138
- ret_status_bar_html_obj, # Return the Gradio component update object
139
- ret_log_md # Return the Gradio component update object
140
  )
141
 
142
- # --- clear_story_state_ui_wrapper (ensure it returns a tuple matching its outputs) ---
143
  def clear_story_state_ui_wrapper():
144
- # ... (Same as before)
145
- new_story = Story(); ph_img = create_placeholder_image("Blank canvas...", color="#1A1A2E", text_color="#A0A0C0")
146
- return (new_story, [(ph_img,"New StoryVerse...")], None, gr.Markdown("## ✨ New Story ✨"), gr.HTML("<p>Cleared.</p>"), "Log Cleared.", "")
 
 
 
147
 
148
- # --- surprise_me_func (no changes needed) ---
149
  def surprise_me_func():
150
- # ... (Same as before)
151
- themes = ["Cosmic Horror", "Solarpunk Utopia"]; actions = ["unearths an artifact", "negotiates"]; settings = ["on a rogue planet", "in a city in a tree"]; prompt = f"A protagonist {random.choice(actions)} {random.choice(settings)}. Theme: {random.choice(themes)}."; style = random.choice(list(STYLE_PRESETS.keys())); artist = random.choice(["H.R. Giger", "Moebius", ""]*2); return prompt, style, artist
 
 
 
 
 
152
 
153
  # --- Functions to control button interactivity ---
154
- def disable_buttons():
155
  return gr.Button(interactive=False), gr.Button(interactive=False)
156
 
157
- def enable_buttons():
158
  return gr.Button(interactive=True), gr.Button(interactive=True)
159
 
160
-
161
  # --- Gradio UI Definition ---
162
- with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨") as story_weaver_demo:
163
  story_state_output = gr.State(Story())
164
- # Define all UI components with their full parameters ONCE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  with gr.Row(equal_height=False, variant="panel"):
166
  with gr.Column(scale=7, min_width=450):
167
  gr.Markdown("### πŸ’‘ **Craft Your Scene**", elem_classes="input-section-header")
168
  with gr.Group():
169
  scene_prompt_input = gr.Textbox(lines=7, label="Scene Vision (Description, Dialogue, Action):", placeholder="e.g., Amidst swirling cosmic dust...")
170
  with gr.Row(elem_classes=["compact-row"]):
171
- with gr.Column(scale=2): image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style Preset")
172
- with gr.Column(scale=2): artist_style_input = gr.Textbox(label="Artistic Inspiration (Optional):", placeholder="e.g., Moebius...")
 
 
173
  negative_prompt_input = gr.Textbox(lines=2, label="Exclude from Image (Negative Prompt):", value=COMMON_NEGATIVE_PROMPTS)
174
  with gr.Accordion("βš™οΈ Advanced AI Configuration", open=False):
175
  with gr.Group():
@@ -183,6 +325,7 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
183
  surprise_button = gr.Button("🎲 Surprise Me!", variant="secondary", scale=1, icon="🎁")
184
  clear_story_button = gr.Button("πŸ—‘οΈ New Story", variant="stop", scale=1, icon="♻️")
185
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave your first masterpiece!</p>")
 
186
  with gr.Column(scale=10, min_width=700):
187
  gr.Markdown("### πŸ–ΌοΈ **Your Evolving StoryVerse**", elem_classes="output-section-header")
188
  with gr.Tabs():
@@ -195,44 +338,30 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
195
  with gr.Accordion(label="Developer Interaction Log", open=False):
196
  output_interaction_log_markdown = gr.Markdown("Log will appear here...")
197
 
198
- # API Status Accordion (defined after main components)
199
- with gr.Accordion("πŸ”§ AI Services Status & Info", open=False):
200
- status_text_list = []; text_llm_ok, image_gen_ok = (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY), (STABILITY_API_IS_READY or OPENAI_DALLE_IS_READY)
201
- if not text_llm_ok and not image_gen_ok: status_text_list.append("<p style='color:#FCA5A5;font-weight:bold;'>⚠️ CRITICAL: NO AI SERVICES CONFIGURED.</p>")
202
- else:
203
- if text_llm_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Text Generation Ready.</p>")
204
- else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Text Generation NOT Ready.</p>")
205
- if image_gen_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Image Generation Ready.</p>")
206
- else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Image Generation NOT Ready.</p>")
207
- gr.HTML("".join(status_text_list))
208
-
209
- # Event Handlers
210
- # When engage_button is clicked:
211
- # 1. Call `disable_buttons` immediately to disable engage and surprise buttons.
212
- # 2. Then, call the main orchestrator.
213
- # 3. After the orchestrator is done (successfully or with error), call `enable_buttons`.
214
- engage_event = engage_button.click( # Assign to a variable to chain .then()
215
- fn=disable_buttons,
216
  inputs=None,
217
  outputs=[engage_button, surprise_button],
218
- queue=False # Run this part immediately
219
  ).then(
220
- fn=add_scene_to_story_orchestrator,
221
  inputs=[
222
  story_state_output, scene_prompt_input,
223
  image_style_input, artist_style_input, negative_prompt_input,
224
  text_model_dropdown, image_provider_dropdown,
225
  narrative_length_dropdown, image_quality_dropdown
226
  ],
227
- outputs=[
228
  story_state_output, output_gallery, output_latest_scene_image,
229
  output_latest_scene_narrative, output_status_bar, output_interaction_log_markdown
230
  ]
231
- ).then( # This .then() executes after add_scene_to_story_orchestrator completes
232
- fn=enable_buttons,
 
233
  inputs=None,
234
  outputs=[engage_button, surprise_button],
235
- queue=False # Run this part immediately after the main function
236
  )
237
 
238
  clear_story_button.click(
@@ -253,19 +382,26 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
253
  examples=[
254
  ["A lone, weary traveler on a mechanical steed crosses a vast, crimson desert under twin suns. Dust devils dance in the distance.", "Sci-Fi Western", "Moebius", "greenery, water, modern city"],
255
  ["Deep within an ancient, bioluminescent forest, a hidden civilization of sentient fungi perform a mystical ritual around a pulsating crystal.", "Psychedelic Fantasy", "Alex Grey", "technology, buildings, roads"],
 
 
256
  ],
257
  inputs=[scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input],
258
  label="🌌 Example Universes to Weave 🌌",
259
  )
260
- gr.HTML("<div style='text-align:center; margin-top:30px; padding-bottom:20px;'><p style='font-size:0.9em; color:#8080A0;'>✨ StoryVerse Omegaβ„’</p></div>")
261
 
262
  # --- Entry Point ---
263
  if __name__ == "__main__":
264
- print("="*80); print("✨ StoryVerse Omegaβ„’ Launching... ✨")
265
- # ... (Startup print messages for API status, default models etc.)
266
- print(f" Gemini Text Ready: {GEMINI_TEXT_IS_READY}"); print(f" HF Text Ready: {HF_TEXT_IS_READY}")
267
- print(f" Stability AI Ready: {STABILITY_API_IS_READY}"); print(f" DALL-E Ready: {OPENAI_DALLE_IS_READY}")
268
- if not (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY) or not (STABILITY_API_IS_READY or OPENAI_DALLE_IS_READY): print(" πŸ”΄ WARNING: Not all services configured.")
269
- print(f" Default Text Model: {UI_DEFAULT_TEXT_MODEL_KEY}"); print(f" Default Image Provider: {UI_DEFAULT_IMAGE_PROVIDER_KEY}")
270
  print("="*80)
 
 
 
 
 
 
 
 
 
 
 
271
  story_weaver_demo.launch(debug=True, server_name="0.0.0.0", share=False)
 
2
  import gradio as gr
3
  import os
4
  import time
5
+ import json
6
+ from PIL import Image, ImageDraw, ImageFont
7
+ import random
8
+ import traceback
9
+
10
+ # --- Core Logic Imports ---
11
  from core.llm_services import initialize_text_llms, is_gemini_text_ready, is_hf_text_ready, generate_text_gemini, generate_text_hf
12
  from core.image_services import initialize_image_llms, STABILITY_API_CONFIGURED, OPENAI_DALLE_CONFIGURED, generate_image_stabilityai, generate_image_dalle, ImageGenResponse
13
  from core.story_engine import Story, Scene
14
  from prompts.narrative_prompts import get_narrative_system_prompt, format_narrative_user_prompt
15
  from prompts.image_style_prompts import STYLE_PRESETS, COMMON_NEGATIVE_PROMPTS, format_image_generation_prompt
16
  from core.utils import basic_text_cleanup
 
 
17
 
18
+ # --- Initialize Services ---
19
  initialize_text_llms()
20
  initialize_image_llms()
21
+
22
+ # --- Get API Readiness Status ---
23
  GEMINI_TEXT_IS_READY = is_gemini_text_ready()
24
  HF_TEXT_IS_READY = is_hf_text_ready()
25
  STABILITY_API_IS_READY = STABILITY_API_CONFIGURED
26
  OPENAI_DALLE_IS_READY = OPENAI_DALLE_CONFIGURED
27
+
28
+ # --- Application Configuration (Models, Defaults) ---
29
  TEXT_MODELS = {}
30
  UI_DEFAULT_TEXT_MODEL_KEY = None
31
+ if GEMINI_TEXT_IS_READY:
32
+ TEXT_MODELS["✨ Gemini 1.5 Flash (Narrate)"] = {"id": "gemini-1.5-flash-latest", "type": "gemini"}
33
+ TEXT_MODELS["Legacy Gemini 1.0 Pro (Narrate)"] = {"id": "gemini-1.0-pro-latest", "type": "gemini"}
34
+ if HF_TEXT_IS_READY: # This condition was correct
35
+ TEXT_MODELS["Mistral 7B (Narrate)"] = {"id": "mistralai/Mistral-7B-Instruct-v0.2", "type": "hf_text"}
36
+ TEXT_MODELS["Gemma 2B (Narrate)"] = {"id": "google/gemma-2b-it", "type": "hf_text"}
37
+
38
+ if TEXT_MODELS:
39
+ # Prioritize based on readiness and preference
40
+ if GEMINI_TEXT_IS_READY and "✨ Gemini 1.5 Flash (Narrate)" in TEXT_MODELS:
41
+ UI_DEFAULT_TEXT_MODEL_KEY = "✨ Gemini 1.5 Flash (Narrate)"
42
+ elif HF_TEXT_IS_READY and "Mistral 7B (Narrate)" in TEXT_MODELS:
43
+ UI_DEFAULT_TEXT_MODEL_KEY = "Mistral 7B (Narrate)"
44
+ elif TEXT_MODELS: # Fallback to first available
45
+ UI_DEFAULT_TEXT_MODEL_KEY = list(TEXT_MODELS.keys())[0]
46
+ else:
47
+ TEXT_MODELS["No Text Models Configured"] = {"id": "dummy_text_error", "type": "none"}
48
+ UI_DEFAULT_TEXT_MODEL_KEY = "No Text Models Configured"
49
+
50
  IMAGE_PROVIDERS = {}
51
  UI_DEFAULT_IMAGE_PROVIDER_KEY = None
52
+ if STABILITY_API_IS_READY: IMAGE_PROVIDERS["🎨 Stability AI (SDXL)"] = "stability_ai"
53
+ if OPENAI_DALLE_IS_READY: IMAGE_PROVIDERS["πŸ–ΌοΈ DALL-E 3 (Sim.)"] = "dalle"
 
 
 
 
54
 
55
+ if IMAGE_PROVIDERS:
56
+ if "🎨 Stability AI (SDXL)" in IMAGE_PROVIDERS: UI_DEFAULT_IMAGE_PROVIDER_KEY = "🎨 Stability AI (SDXL)"
57
+ elif "πŸ–ΌοΈ DALL-E 3 (Sim.)" in IMAGE_PROVIDERS: UI_DEFAULT_IMAGE_PROVIDER_KEY = "πŸ–ΌοΈ DALL-E 3 (Sim.)"
58
+ else: UI_DEFAULT_IMAGE_PROVIDER_KEY = list(IMAGE_PROVIDERS.keys())[0]
59
+ else:
60
+ IMAGE_PROVIDERS["No Image Providers Configured"] = "none"
61
+ UI_DEFAULT_IMAGE_PROVIDER_KEY = "No Image Providers Configured"
62
 
63
+ # --- Gradio UI Theme and CSS ---
64
+ omega_theme = gr.themes.Base(
65
+ font=[gr.themes.GoogleFont("Lexend Deca"), "ui-sans-serif", "system-ui", "sans-serif"],
66
+ primary_hue=gr.themes.colors.purple, secondary_hue=gr.themes.colors.pink, neutral_hue=gr.themes.colors.slate
67
+ ).set(
68
+ body_background_fill="#0F0F1A", block_background_fill="#1A1A2E", block_border_width="1px",
69
+ block_border_color="#2A2A4A", block_label_background_fill="#2A2A4A", input_background_fill="#2A2A4A",
70
+ input_border_color="#4A4A6A", button_primary_background_fill="linear-gradient(135deg, #7F00FF 0%, #E100FF 100%)",
71
+ button_primary_text_color="white", button_secondary_background_fill="#4A4A6A",
72
+ button_secondary_text_color="#E0E0FF", slider_color="#A020F0"
73
+ )
74
+ omega_css = """
75
+ body, .gradio-container { background-color: #0F0F1A !important; color: #D0D0E0 !important; }
76
+ .gradio-container { max-width: 1400px !important; margin: auto !important; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); padding: 25px !important; border: 1px solid #2A2A4A;}
77
+ .gr-panel, .gr-box, .gr-accordion { background-color: #1A1A2E !important; border: 1px solid #2A2A4A !important; border-radius: 12px !important; box-shadow: 0 4px 15px rgba(0,0,0,0.1);}
78
+ .gr-markdown h1 { font-size: 2.8em !important; text-align: center; color: transparent; background: linear-gradient(135deg, #A020F0 0%, #E040FB 100%); -webkit-background-clip: text; background-clip: text; margin-bottom: 5px !important; letter-spacing: -1px;}
79
+ .gr-markdown h3 { color: #C080F0 !important; text-align: center; font-weight: 400; margin-bottom: 25px !important;}
80
+ .input-section-header { font-size: 1.6em; font-weight: 600; color: #D0D0FF; margin-top: 15px; margin-bottom: 8px; border-bottom: 2px solid #7F00FF; padding-bottom: 5px;}
81
+ .output-section-header { font-size: 1.8em; font-weight: 600; color: #D0D0FF; margin-top: 15px; margin-bottom: 12px;}
82
+ .gr-input input, .gr-input textarea, .gr-dropdown select, .gr-textbox textarea { background-color: #2A2A4A !important; color: #E0E0FF !important; border: 1px solid #4A4A6A !important; border-radius: 8px !important; padding: 10px !important;}
83
+ .gr-button { border-radius: 8px !important; font-weight: 500 !important; transition: all 0.2s ease-in-out !important;}
84
+ .gr-button-primary:hover { transform: scale(1.03) translateY(-1px) !important; box-shadow: 0 8px 16px rgba(127,0,255,0.3) !important; }
85
+ .panel_image { border-radius: 12px !important; overflow: hidden; box-shadow: 0 6px 15px rgba(0,0,0,0.25) !important; background-color: #23233A;}
86
+ .panel_image img { max-height: 600px !important; }
87
+ .gallery_output { background-color: transparent !important; border: none !important; }
88
+ .gallery_output .thumbnail-item { border-radius: 8px !important; box-shadow: 0 3px 8px rgba(0,0,0,0.2) !important; margin: 6px !important; transition: transform 0.2s ease; height: 180px !important; width: 180px !important;}
89
+ .gallery_output .thumbnail-item:hover { transform: scale(1.05); }
90
+ .status_text { font-weight: 500; padding: 12px 18px; text-align: center; border-radius: 8px; margin-top:12px; border: 1px solid transparent; font-size: 1.05em;}
91
+ .error_text { background-color: #401010 !important; color: #FFB0B0 !important; border-color: #802020 !important; }
92
+ .success_text { background-color: #104010 !important; color: #B0FFB0 !important; border-color: #208020 !important;}
93
+ .processing_text { background-color: #102040 !important; color: #B0D0FF !important; border-color: #204080 !important;}
94
+ .important-note { background-color: rgba(127,0,255,0.1); border-left: 5px solid #7F00FF; padding: 15px; margin-bottom:20px; color: #E0E0FF; border-radius: 6px;}
95
+ .gr-tabitem { background-color: #1A1A2E !important; border-radius: 0 0 12px 12px !important; padding: 15px !important;}
96
+ .gr-tab-button.selected { background-color: #2A2A4A !important; color: white !important; border-bottom: 3px solid #A020F0 !important; border-radius: 8px 8px 0 0 !important; font-weight: 600 !important;}
97
+ .gr-tab-button { color: #A0A0C0 !important; border-radius: 8px 8px 0 0 !important;}
98
+ .gr-accordion > .gr-block { border-top: 1px solid #2A2A4A !important; }
99
+ .gr-markdown code { background-color: #2A2A4A !important; color: #C0C0E0 !important; padding: 0.2em 0.5em; border-radius: 4px; }
100
+ .gr-markdown pre { background-color: #23233A !important; padding: 1em !important; border-radius: 6px !important; border: 1px solid #2A2A4A !important;}
101
+ .gr-markdown pre > code { padding: 0 !important; background-color: transparent !important; }
102
+ #surprise_button { background: linear-gradient(135deg, #ff7e5f 0%, #feb47b 100%) !important; font-weight:600 !important;}
103
+ #surprise_button:hover { transform: scale(1.03) translateY(-1px) !important; box-shadow: 0 8px 16px rgba(255,126,95,0.3) !important; }
104
+ """
105
+
106
+ # --- Helper: Placeholder Image Creation (Defined at global scope) ---
107
+ def create_placeholder_image(text="Processing...", size=(512, 512), color="#23233A", text_color="#E0E0FF"):
108
+ img = Image.new('RGB', size, color=color); draw = ImageDraw.Draw(img)
109
+ try: font_path = "arial.ttf" if os.path.exists("arial.ttf") else None
110
+ except: font_path = None
111
+ try: font = ImageFont.truetype(font_path, 40) if font_path else ImageFont.load_default()
112
+ except IOError: font = ImageFont.load_default()
113
+ if hasattr(draw, 'textbbox'): bbox = draw.textbbox((0,0), text, font=font); tw, th = bbox[2]-bbox[0], bbox[3]-bbox[1]
114
+ else: tw, th = draw.textsize(text, font=font)
115
+ draw.text(((size[0]-tw)/2, (size[1]-th)/2), text, font=font, fill=text_color); return img
116
+
117
+ # --- StoryVerse Weaver Orchestrator ---
118
  def add_scene_to_story_orchestrator(
119
  current_story_obj: Story, scene_prompt_text: str, image_style_dropdown: str, artist_style_text: str,
120
  negative_prompt_text: str, text_model_key: str, image_provider_key: str,
 
130
  ret_story_state = current_story_obj
131
  ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
132
  ret_latest_image = None
133
+ ret_latest_narrative_str = "## Processing...\nNarrative being woven..."
134
+ ret_status_bar_html = "<p class='processing_text status_text'>Processing...</p>"
135
  # ret_log_md will be built up
136
 
137
+ # Initial UI update using direct component updates in yield
138
+ # These component variables (output_status_bar etc.) must be defined in the `with gr.Blocks` scope
139
  yield {
140
  output_status_bar: gr.HTML(value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
141
+ output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals...")), # Removed visible=True, Gradio handles it
142
+ output_latest_scene_narrative: gr.Markdown(value=" Musing narrative..."), # Removed visible=True
143
+ # engage_button and surprise_button will be handled by the .then() chaining in the UI definition
144
  output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator))
145
  }
146
 
 
150
 
151
  # --- 1. Generate Narrative Text ---
152
  progress(0.1, desc="✍️ Crafting narrative...")
153
+ narrative_text_generated = f"Narrative Error: Init failed."
154
+ text_model_info = TEXT_MODELS.get(text_model_key)
155
+ if text_model_info and text_model_info["type"] != "none":
156
+ system_p = get_narrative_system_prompt("default")
157
+ prev_narrative = current_story_obj.get_last_scene_narrative()
158
+ user_p = format_narrative_user_prompt(scene_prompt_text, prev_narrative)
159
+ log_accumulator.append(f" Narrative: Using {text_model_key} ({text_model_info['id']}). Length: {narrative_length}")
160
+ text_response = None
161
+ if text_model_info["type"] == "gemini": text_response = generate_text_gemini(user_p, model_id=text_model_info["id"], system_prompt=system_p, max_tokens=768 if narrative_length.startswith("Detailed") else 400)
162
+ elif text_model_info["type"] == "hf_text": text_response = generate_text_hf(user_p, model_id=text_model_info["id"], system_prompt=system_p, max_tokens=768 if narrative_length.startswith("Detailed") else 400)
163
+
164
+ if text_response and text_response.success:
165
+ narrative_text_generated = basic_text_cleanup(text_response.text)
166
+ log_accumulator.append(f" Narrative: Success. (Snippet: {narrative_text_generated[:50]}...)")
167
+ elif text_response:
168
+ narrative_text_generated = f"**Narrative Error ({text_model_key}):** {text_response.error}"
169
+ log_accumulator.append(f" Narrative: FAILED - {text_response.error}")
170
+ else:
171
+ log_accumulator.append(f" Narrative: FAILED - No response object from {text_model_key}.")
172
+ else:
173
+ narrative_text_generated = "**Narrative Error:** Selected text model not available or misconfigured."
174
+ log_accumulator.append(f" Narrative: FAILED - Model '{text_model_key}' not available.")
175
 
176
+ ret_latest_narrative_str = f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}"
177
+ yield { output_latest_scene_narrative: gr.Markdown(value=ret_latest_narrative_str),
 
178
  output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
179
 
180
  # --- 2. Generate Image ---
181
  progress(0.5, desc="🎨 Conjuring visuals...")
182
+ image_generated_pil = None
183
+ image_generation_error_message = None
184
+ selected_image_provider_type = IMAGE_PROVIDERS.get(image_provider_key)
185
+ image_content_prompt_for_gen = narrative_text_generated if narrative_text_generated and "Error" not in narrative_text_generated else scene_prompt_text
186
+ quality_keyword = "ultra detailed, intricate, masterpiece, " if image_quality == "High Detail" else ("concept sketch, line art, " if image_quality == "Sketch Concept" else "")
187
+ full_image_prompt = format_image_generation_prompt(quality_keyword + image_content_prompt_for_gen[:350], image_style_dropdown, artist_style_text)
188
+ log_accumulator.append(f" Image: Using {image_provider_key}. Style: {image_style_dropdown}. Artist: {artist_style_text or 'N/A'}.")
189
+
190
+ if selected_image_provider_type and selected_image_provider_type != "none":
191
+ image_response = None
192
+ if selected_image_provider_type == "stability_ai": image_response = generate_image_stabilityai(full_image_prompt, negative_prompt=negative_prompt_text or COMMON_NEGATIVE_PROMPTS, steps=40 if image_quality=="High Detail" else 25)
193
+ elif selected_image_provider_type == "dalle": image_response = generate_image_dalle(full_image_prompt, quality="hd" if image_quality=="High Detail" else "standard")
194
+
195
+ if image_response and image_response.success:
196
+ image_generated_pil = image_response.image
197
+ log_accumulator.append(f" Image: Success from {image_response.provider}.")
198
+ elif image_response:
199
+ image_generation_error_message = f"**Image Error ({image_response.provider}):** {image_response.error}"
200
+ log_accumulator.append(f" Image: FAILED - {image_response.error}")
201
+ else:
202
+ image_generation_error_message = f"**Image Error:** No response object from {image_provider_key} service."
203
+ log_accumulator.append(f" Image: FAILED - No response object from {image_provider_key}.")
204
+ else:
205
+ image_generation_error_message = "**Image Error:** Selected image provider not available or misconfigured."
206
+ log_accumulator.append(f" Image: FAILED - Provider '{image_provider_key}' unavailable.")
207
 
208
  ret_latest_image = image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010")
209
  yield { output_latest_scene_image: gr.Image(value=ret_latest_image),
 
211
 
212
  # --- 3. Add Scene to Story Object ---
213
  final_scene_error = None
214
+ if image_generation_error_message and "**Narrative Error**" in narrative_text_generated : final_scene_error = f"{narrative_text_generated}\n{image_generation_error_message}"
215
+ elif "**Narrative Error**" in narrative_text_generated: final_scene_error = narrative_text_generated
216
+ elif image_generation_error_message: final_scene_error = image_generation_error_message
217
 
218
  current_story_obj.add_scene_from_elements(
219
  user_prompt=scene_prompt_text,
220
  narrative_text=narrative_text_generated if "**Narrative Error**" not in narrative_text_generated else "(Narrative gen failed)",
221
  image=image_generated_pil,
222
  image_style_prompt=f"{image_style_dropdown}{f', by {artist_style_text}' if artist_style_text and artist_style_text.strip() else ''}",
223
+ image_provider=image_provider_key if selected_image_provider_type != "none" else "N/A",
224
  error_message=final_scene_error
225
  )
226
  ret_story_state = current_story_obj
 
229
  # --- 4. Prepare Final Values for Return Tuple ---
230
  ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
231
  _ , latest_narr_for_display_final_str_temp = current_story_obj.get_latest_scene_details_for_display()
232
+ ret_latest_narrative_str = latest_narr_for_display_final_str_temp
233
 
234
  status_html_str_temp = f"<p class='error_text status_text'>Scene {current_story_obj.current_scene_number} added with errors.</p>" if final_scene_error else f"<p class='success_text status_text'>🌌 Scene {current_story_obj.current_scene_number} woven!</p>"
235
+ ret_status_bar_html = gr.HTML(value=status_html_str_temp)
236
 
237
  progress(1.0, desc="Scene Complete!")
238
 
239
  except ValueError as ve:
240
  log_accumulator.append(f"\n**INPUT/CONFIG ERROR:** {ve}")
241
+ ret_status_bar_html = gr.HTML(value=f"<p class='error_text status_text'>❌ CONFIGURATION ERROR: {ve}</p>")
242
+ ret_latest_narrative_str = f"## Error\n{ve}"
243
  except Exception as e:
244
  log_accumulator.append(f"\n**UNEXPECTED RUNTIME ERROR:** {type(e).__name__} - {e}\n{traceback.format_exc()}")
245
+ ret_status_bar_html = gr.HTML(value=f"<p class='error_text status_text'>❌ UNEXPECTED ERROR: {type(e).__name__}. Check logs.</p>")
246
+ ret_latest_narrative_str = f"## Unexpected Error\n{type(e).__name__}: {e}\nSee log for details."
247
+ # No `finally` block here for button updates; handled by `.then()`
248
 
249
  current_total_time = time.time() - start_time
250
  log_accumulator.append(f" Cycle ended at {time.strftime('%H:%M:%S')}. Total time: {current_total_time:.2f}s")
251
+ ret_log_str = "\n".join(log_accumulator)
252
 
253
  # This is the FINAL return. It must be a tuple matching the `outputs` list of engage_button.click()
254
  return (
255
  ret_story_state,
256
  ret_gallery,
257
  ret_latest_image,
258
+ gr.Markdown(value=ret_latest_narrative_str),
259
+ ret_status_bar_html,
260
+ gr.Markdown(value=ret_log_str)
261
  )
262
 
 
263
  def clear_story_state_ui_wrapper():
264
+ new_story = Story()
265
+ placeholder_img = create_placeholder_image("Your StoryVerse is a blank canvas...", color="#1A1A2E", text_color="#A0A0C0")
266
+ cleared_gallery = [(placeholder_img, "Your StoryVerse is new and untold...")]
267
+ initial_narrative = "## ✨ A New Story Begins ✨\nDescribe your first scene idea in the panel to the left and let the AI help you weave your world!"
268
+ status_msg = "<p class='processing_text status_text'>πŸ“œ Story Cleared. A fresh canvas awaits your imagination!</p>"
269
+ return (new_story, cleared_gallery, None, gr.Markdown(value=initial_narrative), gr.HTML(value=status_msg), "Log Cleared. Ready for a new adventure!", "")
270
 
 
271
  def surprise_me_func():
272
+ themes = ["Cosmic Horror", "Solarpunk Utopia", "Mythic Fantasy", "Noir Detective", "Silent Film Comedy", "Deep Sea Exploration", "Prehistoric Survival"]
273
+ actions = ["unearths an artifact of immense power", "negotiates with an interdimensional being", "solves an ancient riddle", "embarks on a perilous journey", "attends a secret festival", "witnesses a celestial event", "finds a hidden sanctuary"]
274
+ settings = ["on a rogue planet drifting through an empty void", "in a city built within a colossal, living tree", "within a library containing all possible books", "on a generation ship nearing its ancient destination", "in a dreamlike landscape where physics is suggestive", "at the bottom of a Mariana Trench-like abyss", "in a lush jungle teeming with dinosaurs"]
275
+ prompt = f"A protagonist {random.choice(actions)} {random.choice(settings)}. The overall theme is {random.choice(themes)}."
276
+ style = random.choice(list(STYLE_PRESETS.keys()))
277
+ artist = random.choice(["H.R. Giger", "Moebius", "Eyvind Earle", " Remedios Varo", "Alphonse Mucha", ""]*2)
278
+ return prompt, style, artist
279
 
280
  # --- Functions to control button interactivity ---
281
+ def disable_buttons_for_processing():
282
  return gr.Button(interactive=False), gr.Button(interactive=False)
283
 
284
+ def enable_buttons_after_processing():
285
  return gr.Button(interactive=True), gr.Button(interactive=True)
286
 
 
287
  # --- Gradio UI Definition ---
288
+ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨ - AI Story & World Weaver") as story_weaver_demo:
289
  story_state_output = gr.State(Story())
290
+
291
+ gr.Markdown("<div align='center'><h1>✨ StoryVerse Omega ✨</h1>\n<h3>Craft Immersive Multimodal Worlds with AI</h3></div>")
292
+ gr.HTML("<div class='important-note'><strong>Welcome, Worldsmith!</strong> Describe your vision, choose your style, and let Omega help you weave captivating scenes with narrative and imagery. Ensure API keys (<code>STORYVERSE_...</code>) are correctly set in Space Secrets!</div>")
293
+
294
+ with gr.Accordion("πŸ”§ AI Services Status & Info", open=False):
295
+ status_text_list = []
296
+ text_llm_ok, image_gen_ok = (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY), (STABILITY_API_IS_READY or OPENAI_DALLE_IS_READY)
297
+ if not text_llm_ok and not image_gen_ok: status_text_list.append("<p style='color:#FCA5A5;font-weight:bold;'>⚠️ CRITICAL: NO AI SERVICES CONFIGURED.</p>")
298
+ else:
299
+ if text_llm_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Text Generation Service(s) Ready.</p>")
300
+ else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Text Generation Service(s) NOT Ready.</p>")
301
+ if image_gen_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Image Generation Service(s) Ready.</p>")
302
+ else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Image Generation Service(s) NOT Ready.</p>")
303
+ gr.HTML("".join(status_text_list))
304
+
305
  with gr.Row(equal_height=False, variant="panel"):
306
  with gr.Column(scale=7, min_width=450):
307
  gr.Markdown("### πŸ’‘ **Craft Your Scene**", elem_classes="input-section-header")
308
  with gr.Group():
309
  scene_prompt_input = gr.Textbox(lines=7, label="Scene Vision (Description, Dialogue, Action):", placeholder="e.g., Amidst swirling cosmic dust...")
310
  with gr.Row(elem_classes=["compact-row"]):
311
+ with gr.Column(scale=2):
312
+ image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style Preset")
313
+ with gr.Column(scale=2):
314
+ artist_style_input = gr.Textbox(label="Artistic Inspiration (Optional):", placeholder="e.g., Moebius...")
315
  negative_prompt_input = gr.Textbox(lines=2, label="Exclude from Image (Negative Prompt):", value=COMMON_NEGATIVE_PROMPTS)
316
  with gr.Accordion("βš™οΈ Advanced AI Configuration", open=False):
317
  with gr.Group():
 
325
  surprise_button = gr.Button("🎲 Surprise Me!", variant="secondary", scale=1, icon="🎁")
326
  clear_story_button = gr.Button("πŸ—‘οΈ New Story", variant="stop", scale=1, icon="♻️")
327
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave your first masterpiece!</p>")
328
+
329
  with gr.Column(scale=10, min_width=700):
330
  gr.Markdown("### πŸ–ΌοΈ **Your Evolving StoryVerse**", elem_classes="output-section-header")
331
  with gr.Tabs():
 
338
  with gr.Accordion(label="Developer Interaction Log", open=False):
339
  output_interaction_log_markdown = gr.Markdown("Log will appear here...")
340
 
341
+ # Chained event handling for engage_button
342
+ click_event_engage = engage_button.click(
343
+ fn=disable_buttons_for_processing, # Step 1: Disable buttons
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  inputs=None,
345
  outputs=[engage_button, surprise_button],
346
+ queue=False # Run immediately without queuing for this UI update
347
  ).then(
348
+ fn=add_scene_to_story_orchestrator, # Step 2: Run the main orchestrator
349
  inputs=[
350
  story_state_output, scene_prompt_input,
351
  image_style_input, artist_style_input, negative_prompt_input,
352
  text_model_dropdown, image_provider_dropdown,
353
  narrative_length_dropdown, image_quality_dropdown
354
  ],
355
+ outputs=[ # These are updated by the FINAL RETURN of the orchestrator
356
  story_state_output, output_gallery, output_latest_scene_image,
357
  output_latest_scene_narrative, output_status_bar, output_interaction_log_markdown
358
  ]
359
+ # Progressive updates within orchestrator happen via `yield {component_var: update}`
360
+ ).then(
361
+ fn=enable_buttons_after_processing, # Step 3: Re-enable buttons
362
  inputs=None,
363
  outputs=[engage_button, surprise_button],
364
+ queue=False # Run immediately after orchestrator finishes
365
  )
366
 
367
  clear_story_button.click(
 
382
  examples=[
383
  ["A lone, weary traveler on a mechanical steed crosses a vast, crimson desert under twin suns. Dust devils dance in the distance.", "Sci-Fi Western", "Moebius", "greenery, water, modern city"],
384
  ["Deep within an ancient, bioluminescent forest, a hidden civilization of sentient fungi perform a mystical ritual around a pulsating crystal.", "Psychedelic Fantasy", "Alex Grey", "technology, buildings, roads"],
385
+ ["A child sits on a crescent moon, fishing for stars in a swirling nebula. A friendly space whale swims nearby.", "Whimsical Cosmic", "James Jean", "realistic, dark, scary"],
386
+ ["A grand, baroque library where the books fly freely and whisper forgotten lore to those who listen closely.", "Magical Realism", "Remedios Varo", "minimalist, simple, technology"]
387
  ],
388
  inputs=[scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input],
389
  label="🌌 Example Universes to Weave 🌌",
390
  )
391
+ gr.HTML("<div style='text-align:center; margin-top:30px; padding-bottom:20px;'><p style='font-size:0.9em; color:#8080A0;'>✨ StoryVerse Omegaβ„’ - Weaving Worlds with Words and Pixels ✨</p></div>")
392
 
393
  # --- Entry Point ---
394
  if __name__ == "__main__":
 
 
 
 
 
 
395
  print("="*80)
396
+ print("✨ StoryVerse Omegaβ„’ - AI Story & World Weaver - Launching... ✨")
397
+ print(f" Text LLM Ready (Gemini): {GEMINI_TEXT_IS_READY}")
398
+ print(f" Text LLM Ready (HF): {HF_TEXT_IS_READY}")
399
+ print(f" Image Provider Ready (Stability AI): {STABILITY_API_IS_READY}")
400
+ print(f" Image Provider Ready (DALL-E): {OPENAI_DALLE_IS_READY}")
401
+ if not (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY) or not (STABILITY_API_IS_READY or OPENAI_DALLE_IS_READY):
402
+ print(" πŸ”΄ WARNING: Not all required AI services are configured correctly.")
403
+ print(f" Default Text Model: {UI_DEFAULT_TEXT_MODEL_KEY}")
404
+ print(f" Default Image Provider: {UI_DEFAULT_IMAGE_PROVIDER_KEY}")
405
+ print("="*80)
406
+
407
  story_weaver_demo.launch(debug=True, server_name="0.0.0.0", share=False)