mgbam commited on
Commit
fa7abf4
·
verified ·
1 Parent(s): efe910f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -271
app.py CHANGED
@@ -2,9 +2,10 @@
2
  import gradio as gr
3
  import os
4
  import time
5
- import json # For state saving/loading (conceptual)
6
- from PIL import Image, ImageDraw, ImageFont # For creating placeholder/error images
7
  import random
 
8
 
9
  # --- Core Logic Imports ---
10
  from core.llm_services import initialize_text_llms, is_gemini_text_ready, is_hf_text_ready, generate_text_gemini, generate_text_hf
@@ -25,7 +26,6 @@ STABILITY_API_IS_READY = STABILITY_API_CONFIGURED
25
  OPENAI_DALLE_IS_READY = OPENAI_DALLE_CONFIGURED
26
 
27
  # --- Application Configuration (Models, Defaults) ---
28
- # (This section remains the same as your last full app.py - ensure it's correct)
29
  TEXT_MODELS = {}
30
  UI_DEFAULT_TEXT_MODEL_KEY = None
31
  if GEMINI_TEXT_IS_READY:
@@ -33,278 +33,232 @@ if GEMINI_TEXT_IS_READY:
33
  TEXT_MODELS["Legacy Gemini 1.0 Pro (Narrate)"] = {"id": "gemini-1.0-pro-latest", "type": "gemini"}
34
  if HF_TEXT_IS_READY:
35
  TEXT_MODELS["Mistral 7B (Narrate)"] = {"id": "mistralai/Mistral-7B-Instruct-v0.2", "type": "hf_text"}
36
- if TEXT_MODELS: UI_DEFAULT_TEXT_MODEL_KEY = list(TEXT_MODELS.keys())[0]
37
- else: TEXT_MODELS["No Text Models Configured"] = {"id": "dummy", "type": "none"}; UI_DEFAULT_TEXT_MODEL_KEY = "No Text Models Configured"
 
 
 
 
 
 
 
38
 
39
  IMAGE_PROVIDERS = {}
40
  UI_DEFAULT_IMAGE_PROVIDER_KEY = None
41
  if STABILITY_API_IS_READY: IMAGE_PROVIDERS["🎨 Stability AI (SDXL)"] = "stability_ai"
42
  if OPENAI_DALLE_IS_READY: IMAGE_PROVIDERS["🖼️ DALL-E 3 (Sim.)"] = "dalle"
43
- if IMAGE_PROVIDERS: UI_DEFAULT_IMAGE_PROVIDER_KEY = list(IMAGE_PROVIDERS.keys())[0]
44
- else: IMAGE_PROVIDERS["No Image Providers Configured"] = "none"; UI_DEFAULT_IMAGE_PROVIDER_KEY = "No Image Providers Configured"
45
-
46
-
47
- # --- Enhanced UI Theme and CSS ---
48
- # Using a more bespoke dark theme and extensive CSS for "WOW"
49
- # algoforge_prime/app.py
50
-
51
- # ... (other imports and initializations) ...
52
 
53
- # --- Gradio UI Theme and CSS for DARK MODE ---
54
- # algoforge_prime/app.py
 
 
 
 
 
55
 
56
- # ... (other imports and initializations) ...
57
-
58
- # algoforge_prime/app.py (or storyverse_weaver/app.py) - Excerpt showing the corrected theme
59
-
60
- # --- Gradio UI Theme and CSS for DARK MODE ---
61
- omega_theme = gr.themes.Base(
62
  font=[gr.themes.GoogleFont("Lexend Deca"), "ui-sans-serif", "system-ui", "sans-serif"],
63
- primary_hue=gr.themes.colors.purple,
64
- secondary_hue=gr.themes.colors.pink,
65
- neutral_hue=gr.themes.colors.slate # Slate often works well for dark mode neutrals
66
  ).set(
67
- body_background_fill="#0F0F1A",
68
- block_background_fill="#1A1A2E",
69
- block_border_width="1px",
70
- block_border_color="#2A2A4A",
71
- block_label_background_fill="#2A2A4A",
72
- # Text colors for block labels will likely be inherited or need CSS
73
-
74
- input_background_fill="#2A2A4A",
75
- input_border_color="#4A4A6A",
76
- # Input text color will be handled by CSS:
77
- # .gr-input input, .gr-input textarea, .gr-dropdown select { color: #E0E0FF !important; }
78
-
79
- button_primary_background_fill="linear-gradient(135deg, #7F00FF 0%, #E100FF 100%)",
80
- button_primary_text_color="white", # This is usually a valid and important one
81
- button_secondary_background_fill="#4A4A6A",
82
- button_secondary_text_color="#E0E0FF",
83
-
84
- slider_color="#A020F0" # Main color for slider components
85
- # REMOVED: text_color_primary, text_color_secondary, text_color_accent, text_color_link
86
  )
87
-
88
- # ... (rest of your omega_css definition - this is important for text colors) ...
89
- # ... (rest of your app.py) ...
90
-
91
- # ... (rest of your omega_css definition) ...
92
- # ... (rest of your app.py) ...
93
- # on various components if the theme variables don't cover everything.
94
- # Your existing omega_css already sets:
95
- # body, .gradio-container { color: #D0D0E0 !important; }
96
- # .gr-input input, .gr-input textarea, .gr-dropdown select { color: white !important; }
97
- # This CSS will likely handle the text colors correctly.
98
-
99
- # ... (rest of your omega_css definition) ...
100
- # ... (rest of your app.py) ...
101
-
102
- omega_css = """
103
- body, .gradio-container { background-color: #0F0F1A !important; color: #D0D0E0 !important; }
104
- .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;}
105
- .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);}
106
- .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;}
107
- .gr-markdown h3 { color: #C080F0 !important; text-align: center; font-weight: 400; margin-bottom: 25px !important;}
108
- .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;}
109
- .output-section-header { font-size: 1.8em; font-weight: 600; color: #D0D0FF; margin-top: 15px; margin-bottom: 12px;}
110
- .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;}
111
- .gr-button { border-radius: 8px !important; font-weight: 500 !important; transition: all 0.2s ease-in-out !important;}
112
- .gr-button-primary:hover { transform: scale(1.03) translateY(-1px) !important; box-shadow: 0 8px 16px rgba(127,0,255,0.3) !important; }
113
- .panel_image { border-radius: 12px !important; overflow: hidden; box-shadow: 0 6px 15px rgba(0,0,0,0.25) !important; background-color: #23233A;}
114
- .panel_image img { max-height: 600px !important; }
115
- .gallery_output { background-color: transparent !important; border: none !important; }
116
- .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;}
117
- .gallery_output .thumbnail-item:hover { transform: scale(1.05); }
118
- .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;}
119
- .error_text { background-color: #401010 !important; color: #FFB0B0 !important; border-color: #802020 !important; }
120
- .success_text { background-color: #104010 !important; color: #B0FFB0 !important; border-color: #208020 !important;}
121
- .processing_text { background-color: #102040 !important; color: #B0D0FF !important; border-color: #204080 !important;}
122
- .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;}
123
- .gr-tabitem { background-color: #1A1A2E !important; border-radius: 0 0 12px 12px !important; padding: 15px !important;}
124
- .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;}
125
- .gr-tab-button { color: #A0A0C0 !important; border-radius: 8px 8px 0 0 !important;}
126
- .gr-accordion > .gr-block { border-top: 1px solid #2A2A4A !important; }
127
- .gr-markdown code { background-color: #2A2A4A !important; color: #C0C0E0 !important; padding: 0.2em 0.5em; border-radius: 4px; }
128
- .gr-markdown pre { background-color: #23233A !important; padding: 1em !important; border-radius: 6px !important; border: 1px solid #2A2A4A !important;}
129
- .gr-markdown pre > code { padding: 0 !important; background-color: transparent !important; }
130
- #surprise_button { background: linear-gradient(135deg, #ff7e5f 0%, #feb47b 100%) !important; font-weight:600 !important;}
131
- #surprise_button:hover { transform: scale(1.03) translateY(-1px) !important; box-shadow: 0 8px 16px rgba(255,126,95,0.3) !important; }
132
- """
133
 
134
  # --- Helper: Placeholder Image Creation ---
135
  def create_placeholder_image(text="Processing...", size=(512, 512), color="#23233A", text_color="#E0E0FF"):
136
- img = Image.new('RGB', size, color=color)
137
- draw = ImageDraw.Draw(img)
138
- try:
139
- font = ImageFont.truetype("arial.ttf", 40) # Try to load a common font
140
- except IOError:
141
- font = ImageFont.load_default()
142
- text_width, text_height = draw.textbbox((0,0), text, font=font)[2:] # Use textbbox
143
- x = (size[0] - text_width) / 2
144
- y = (size[1] - text_height) / 2
145
- draw.text((x, y), text, font=font, fill=text_color)
146
- return img
147
-
148
- # --- StoryVerse Weaver Orchestrator (with more granular UI updates) ---
149
- # (This function `add_scene_to_story` and `clear_story_state_ui` will be the same logic as
150
- # the one from your last "REWRITE APP.PY IN FULL" response. The key is how this app.py's
151
- # UI wrapper will call it and use its return values.
152
- # For absolute clarity, I am pasting the orchestrator function logic here,
153
- # but it's fundamentally the same as the robust one we developed.)
154
- def add_scene_to_story_orchestrator( # Renamed to avoid conflict if testing locally
155
  current_story_obj: Story, scene_prompt_text: str, image_style_dropdown: str, artist_style_text: str,
156
  negative_prompt_text: str, text_model_key: str, image_provider_key: str,
157
- # Additional params for more control (could be added to UI)
158
- narrative_length: str, # e.g., "Short (1 paragraph)", "Medium (2-3 paragraphs)", "Long (4+ paragraphs)"
159
- image_quality: str, # e.g., "Standard", "High Detail"
160
  progress=gr.Progress(track_tqdm=True)
161
  ):
162
- if not current_story_obj: current_story_obj = Story() # Initialize if None (e.g. first run)
 
 
 
 
 
 
 
 
163
 
164
- # Initial UI update
 
165
  yield {
166
  output_status_bar: gr.HTML(value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
167
  output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals..."), visible=True),
168
  output_latest_scene_narrative: gr.Markdown(value=" Musing narrative...", visible=True),
169
- engage_button: gr.Button(interactive=False), # Disable button
170
  surprise_button: gr.Button(interactive=False),
 
171
  }
172
 
173
- log_accumulator = [f"**🚀 Scene {current_story_obj.current_scene_number + 1} - {time.strftime('%H:%M:%S')}**"]
174
-
175
- if not scene_prompt_text.strip():
176
- error_msg = "Scene prompt cannot be empty!"
177
- log_accumulator.append(f" VALIDATION ERROR: {error_msg}")
178
- yield {
179
- output_status_bar: gr.HTML(value=f"<p class='error_text status_text'>{error_msg}</p>"),
180
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)),
181
- engage_button: gr.Button(interactive=True), surprise_button: gr.Button(interactive=True)
182
- }
183
- return current_story_obj, current_story_obj.get_all_scenes_for_gallery_display(), None, "## Error\n" + error_msg # Return existing state if error
184
-
185
- # --- 1. Generate Narrative Text ---
186
- # (This logic is the same as your previous `add_scene_to_story`)
187
- # ...
188
- # Example:
189
- # narrative_text_generated, text_gen_log = _generate_narrative_for_scene(...)
190
- # log_accumulator.extend(text_gen_log)
191
- # yield { ui updates }
192
- # This placeholder needs full logic. For brevity, I'm simulating.
193
- progress(0.1, desc="✍️ Crafting narrative...")
194
- time.sleep(0.5) # Simulate work
195
- narrative_text_generated = f"This is the AI-generated narrative for your idea: '{scene_prompt_text[:30]}...'. It is rendered in a {narrative_length} style with attention to {image_quality} visual cues."
196
- log_accumulator.append(f" Narrative: Generated using {text_model_key}. Length: {narrative_length}")
197
- yield { output_latest_scene_narrative: gr.Markdown(value=f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}"),
198
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
199
-
200
-
201
- # --- 2. Generate Image ---
202
- # (This logic is the same as your previous `add_scene_to_story`)
203
- # ...
204
- # Example:
205
- # image_generated_pil, image_gen_log = _generate_image_for_scene(...)
206
- # log_accumulator.extend(image_gen_log)
207
- # yield { ui updates }
208
- progress(0.5, desc="🎨 Conjuring visuals...")
209
- time.sleep(1) # Simulate work
210
- image_generated_pil = create_placeholder_image(f"Image for:\n{scene_prompt_text[:25]}...\nStyle: {image_style_dropdown}", text_color="#A020F0")
211
- image_generation_error_message = None # Assume success for this WOW demo part
212
- log_accumulator.append(f" Image: Generated using {image_provider_key}. Style: {image_style_dropdown}")
213
- yield { output_latest_scene_image: gr.Image(value=image_generated_pil),
214
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
215
-
216
-
217
- # --- 3. Add Scene to Story Object ---
218
- # (This logic is the same as your previous `add_scene_to_story`)
219
- current_story_obj.add_scene_from_elements(
220
- user_prompt=scene_prompt_text, narrative_text=narrative_text_generated, image=image_generated_pil,
221
- image_style_prompt=f"{image_style_dropdown}{f', by {artist_style_text}' if artist_style_text else ''}",
222
- image_provider=image_provider_key, error_message=image_generation_error_message
223
- )
224
-
225
- # --- 4. Prepare Final Outputs for Gradio ---
226
- gallery_items_tuples = current_story_obj.get_all_scenes_for_gallery_display()
227
- _ , latest_narr_for_display = current_story_obj.get_latest_scene_details_for_display() # Image is already in its component
228
-
229
- status_message_html = "<p class='success_text status_text'>🌌 Scene Woven! Your StoryVerse expands...</p>"
230
- if image_generation_error_message: status_message_html = "<p class='error_text status_text'>Scene added, but image generation had issues.</p>"
231
-
232
- log_accumulator.append(f" Scene {current_story_obj.current_scene_number} successfully added to story object.")
233
- progress(1.0, desc="Scene Complete!")
234
-
235
- yield {
236
- output_status_bar: gr.HTML(value=status_message_html),
237
- story_state_output: current_story_obj, # Update the state
238
- output_gallery: gr.Gallery(value=gallery_items_tuples, visible=True),
239
- # Latest image and narrative already updated progressively
240
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)),
241
- engage_button: gr.Button(interactive=True),
242
- surprise_button: gr.Button(interactive=True),
243
- }
244
- # Return a dictionary that maps to the output components explicitly for the final state
245
- # This ensures Gradio handles the final update correctly.
246
- return {
247
- story_state_output: current_story_obj,
248
- output_gallery: gallery_items_tuples,
249
- output_latest_scene_image: image_generated_pil, # Ensure this is the final image
250
- output_latest_scene_narrative: latest_narr_for_display,
251
- output_status_bar: status_message_html,
252
- output_interaction_log_markdown: "\n".join(log_accumulator)
253
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
 
256
  def clear_story_state_ui_wrapper():
257
- # (This logic is the same as your previous clear_story_state_ui)
258
  new_story = Story()
259
- placeholder_img = create_placeholder_image("Your StoryVerse is a blank canvas...", color="#1A1A2E")
260
  cleared_gallery = [(placeholder_img, "Your StoryVerse is new and untold...")]
261
  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!"
262
  status_msg = "<p class='processing_text status_text'>📜 Story Cleared. A fresh canvas awaits your imagination!</p>"
263
- return {
264
- story_state_output: new_story,
265
- output_gallery: cleared_gallery,
266
- output_latest_scene_image: None, # Clear latest image
267
- output_latest_scene_narrative: gr.Markdown(value=initial_narrative),
268
- output_status_bar: gr.HTML(value=status_msg),
269
- output_interaction_log_markdown: "Log Cleared. Ready for a new adventure!",
270
- scene_prompt_input: "" # Clear the input prompt
271
- }
 
 
272
 
273
  def surprise_me_func():
274
- # Simple "Surprise Me" feature
275
- themes = ["Sci-Fi", "Fantasy", "Mystery", "Slice of Life", "Historical Fiction"]
276
- actions = ["discovers a hidden map", "encounters a mysterious stranger", "solves an ancient riddle", "embarks on a perilous journey", "attends a secret festival"]
277
- settings = ["in a bustling alien marketplace", "within a forgotten, vine-covered temple", "aboard a steampunk airship", "in a quiet, magical forest", "during a solar eclipse on a twin-mooned planet"]
278
-
279
- prompt = f"A character {random.choice(actions)} {random.choice(settings)}. Theme: {random.choice(themes)}."
280
  style = random.choice(list(STYLE_PRESETS.keys()))
281
- artist = random.choice(["Greg Rutkowski", "Makoto Shinkai", "Moebius", "Rebecca Guay", ""]*3) # "" for no artist sometimes
282
  return prompt, style, artist
283
 
284
 
285
  # --- Gradio UI Definition ---
286
  with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨ - AI Story & World Weaver") as story_weaver_demo:
287
- # Output components need to be defined before the click handler if updated by yield's dict
288
- story_state_output = gr.State(Story()) # Crucial: Define actual output component for state
 
289
 
290
  gr.Markdown("<div align='center'><h1>✨ StoryVerse Omega ✨</h1>\n<h3>Craft Immersive Multimodal Worlds with AI</h3></div>")
291
  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>")
292
 
293
  with gr.Accordion("🔧 AI Services Status & Info", open=False):
294
- # ... (API status HTML as before, using GEMINI_TEXT_IS_READY etc.)
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.</p>")
298
  else:
299
- if text_llm_ok: status_text_list.append("<p style='color:#A7F3D0;'>✅ Text Gen Ready.</p>")
300
- else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Text Gen NOT Ready.</p>")
301
- if image_gen_ok: status_text_list.append("<p style='color:#A7F3D0;'>✅ Image Gen Ready.</p>")
302
- else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Image Gen NOT Ready.</p>")
303
  gr.HTML("".join(status_text_list))
304
 
305
-
306
  with gr.Row(equal_height=False, variant="panel"):
307
- with gr.Column(scale=7, min_width=450): # Input panel
308
  gr.Markdown("### 💡 **Craft Your Scene**", elem_classes="input-section-header")
309
  with gr.Group():
310
  scene_prompt_input = gr.Textbox(lines=7, label="Scene Vision (Description, Dialogue, Action):", placeholder="e.g., Amidst swirling cosmic dust, Captain Eva pilots her damaged starfighter towards a colossal, ringed gas giant. Alarms blare. 'Just a little further,' she mutters, gripping the controls.")
@@ -313,7 +267,7 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
313
  with gr.Column(scale=2):
314
  image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style Preset")
315
  with gr.Column(scale=2):
316
- artist_style_input = gr.Textbox(label="Artist Inspiration (Optional):", placeholder="e.g., Moebius, Zdzisław Beksiński")
317
 
318
  negative_prompt_input = gr.Textbox(lines=2, label="Exclude from Image (Negative Prompt):", placeholder="Default exclusions applied. Add more if needed.", value=COMMON_NEGATIVE_PROMPTS)
319
 
@@ -327,77 +281,51 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
327
 
328
  with gr.Row(elem_classes=["compact-row"], equal_height=True):
329
  engage_button = gr.Button("🌌 Weave This Scene!", variant="primary", scale=3, icon="✨")
330
- surprise_button = gr.Button("🎲 Surprise Me!", variant="secondary", scale=1, icon="🎁", elem_id="surprise_button")
331
- clear_story_button = gr.Button("🗑️ New Story", variant="stop", scale=1, icon="♻️") # Stop variant for caution
332
 
333
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave your first masterpiece!</p>")
334
 
335
- with gr.Column(scale=10, min_width=700): # Output panel
336
  gr.Markdown("### 🖼️ **Your Evolving StoryVerse**", elem_classes="output-section-header")
337
- with gr.Tabs(elem_id="output_tabs_elem"):
338
- with gr.TabItem("🌠 Latest Scene", id="latest_scene_tab", elem_id="latest_scene_tab_item"):
339
- with gr.Row():
340
- output_latest_scene_image = gr.Image(label="Latest Scene Image", type="pil", interactive=False, show_download_button=True, height=512, show_label=False, elem_classes=["panel_image"])
341
- output_latest_scene_narrative = gr.Markdown(elem_id="latest_scene_narrative_md")
342
 
343
- with gr.TabItem("📚 Story Scroll", id="story_scroll_tab", elem_id="story_scroll_tab_item"):
344
- output_gallery = gr.Gallery(label="Story Scroll", show_label=False, columns=4, object_fit="cover", height=700, preview=True, allow_preview=True, elem_classes=["gallery_output"]) # More columns
345
 
346
- with gr.TabItem("⚙️ Interaction Log", id="log_tab", elem_id="log_tab_item"):
347
- with gr.Accordion(label="Developer Interaction Log", open=False): # Default closed
348
  output_interaction_log_markdown = gr.Markdown("Log will appear here...")
349
 
350
- # Define outputs that the wrapper function will update via yield
351
- # Note: story_state_output is the gr.State component itself.
352
- outputs_for_handler = [
353
- output_status_bar,
354
- gr.Accordion(visible=True), # Placeholder for output_initial_solutions_accordion (not used in this UI)
355
- gr.Markdown(visible=True), # Placeholder for output_initial_solutions_markdown (not used)
356
- gr.Accordion(visible=True), # Placeholder for output_champion_accordion (not used)
357
- gr.Markdown(visible=True), # Placeholder for output_champion_markdown (not used)
358
- gr.Accordion(visible=True), # Placeholder for output_evolved_accordion (not used)
359
- output_evolved_markdown, # This can be repurposed or removed if not directly evolving scenes
360
- output_ai_test_analysis_markdown, # Also can be repurposed or removed
361
- output_interaction_log_markdown,
362
- engage_button,
363
- surprise_button, # To re-enable surprise button
364
- story_state_output, # This is where the story_state is passed back to itself
365
- output_gallery,
366
- output_latest_scene_image,
367
- output_latest_scene_narrative
368
- ]
369
- # Re-map the orchestrator's yielded dict keys to the actual output components for the final return
370
- # This is a bit of a hack due to Gradio's yield behavior vs. final return.
371
- # The `add_scene_to_story_orchestrator` should be designed to yield a dict
372
- # that maps to these specific component names if we want direct updates.
373
- # For simplicity, the `return` statement of the orchestrator is what matters for final state.
374
-
375
  engage_button.click(
376
- fn=add_scene_to_story_orchestrator, # Call the wrapper
377
  inputs=[
378
  story_state_output, scene_prompt_input,
379
  image_style_input, artist_style_input, negative_prompt_input,
380
  text_model_dropdown, image_provider_dropdown,
381
- narrative_length_dropdown, image_quality_dropdown # New inputs
382
  ],
383
- outputs=[ # These must match the keys in the dictionary returned by the orchestrator's FINAL return
384
  story_state_output,
385
  output_gallery,
386
  output_latest_scene_image,
387
  output_latest_scene_narrative,
388
  output_status_bar,
389
  output_interaction_log_markdown
390
- # Note: The progressive yield updates specific components by name directly.
391
  ]
 
392
  )
393
  clear_story_button.click(
394
  fn=clear_story_state_ui_wrapper,
395
  inputs=[],
396
- outputs=[ # Must match the keys in the dict returned by clear_story_state_ui_wrapper
397
  story_state_output, output_gallery,
398
  output_latest_scene_image, output_latest_scene_narrative,
399
  output_status_bar, output_interaction_log_markdown,
400
- scene_prompt_input # To clear the input field
401
  ]
402
  )
403
  surprise_button.click(
@@ -413,12 +341,12 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
413
  ["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"],
414
  ["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"]
415
  ],
416
- inputs=[scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input], # negative_prompt is optional for examples
417
  label="🌌 Example Universes to Weave 🌌",
418
  )
419
  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>")
420
 
421
- # --- Entry Point ---
422
  if __name__ == "__main__":
423
  print("="*80)
424
  print("✨ StoryVerse Omega™ - AI Story & World Weaver - Launching... ✨")
@@ -432,4 +360,4 @@ if __name__ == "__main__":
432
  print(f" Default Image Provider: {UI_DEFAULT_IMAGE_PROVIDER_KEY}")
433
  print("="*80)
434
 
435
- story_weaver_demo.launch(debug=True, server_name="0.0.0.0", share=False) # Set share=True for public link if desired
 
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 # For more detailed error logging in wrapper
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
 
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:
 
33
  TEXT_MODELS["Legacy Gemini 1.0 Pro (Narrate)"] = {"id": "gemini-1.0-pro-latest", "type": "gemini"}
34
  if HF_TEXT_IS_READY:
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
+ if "✨ Gemini 1.5 Flash (Narrate)" in TEXT_MODELS: UI_DEFAULT_TEXT_MODEL_KEY = "✨ Gemini 1.5 Flash (Narrate)"
40
+ elif "Mistral 7B (Narrate)" in TEXT_MODELS: UI_DEFAULT_TEXT_MODEL_KEY = "Mistral 7B (Narrate)"
41
+ else: UI_DEFAULT_TEXT_MODEL_KEY = list(TEXT_MODELS.keys())[0]
42
+ else:
43
+ TEXT_MODELS["No Text Models Configured"] = {"id": "dummy_text_error", "type": "none"}
44
+ UI_DEFAULT_TEXT_MODEL_KEY = "No Text Models Configured"
45
 
46
  IMAGE_PROVIDERS = {}
47
  UI_DEFAULT_IMAGE_PROVIDER_KEY = None
48
  if STABILITY_API_IS_READY: IMAGE_PROVIDERS["🎨 Stability AI (SDXL)"] = "stability_ai"
49
  if OPENAI_DALLE_IS_READY: IMAGE_PROVIDERS["🖼️ DALL-E 3 (Sim.)"] = "dalle"
 
 
 
 
 
 
 
 
 
50
 
51
+ if IMAGE_PROVIDERS:
52
+ if "🎨 Stability AI (SDXL)" in IMAGE_PROVIDERS: UI_DEFAULT_IMAGE_PROVIDER_KEY = "🎨 Stability AI (SDXL)"
53
+ elif "🖼️ DALL-E 3 (Sim.)" in IMAGE_PROVIDERS: UI_DEFAULT_IMAGE_PROVIDER_KEY = "🖼️ DALL-E 3 (Sim.)"
54
+ else: UI_DEFAULT_IMAGE_PROVIDER_KEY = list(IMAGE_PROVIDERS.keys())[0]
55
+ else:
56
+ IMAGE_PROVIDERS["No Image Providers Configured"] = "none"
57
+ UI_DEFAULT_IMAGE_PROVIDER_KEY = "No Image Providers Configured"
58
 
59
+ # --- Gradio UI Theme and CSS ---
60
+ omega_theme = gr.themes.Base(
 
 
 
 
61
  font=[gr.themes.GoogleFont("Lexend Deca"), "ui-sans-serif", "system-ui", "sans-serif"],
62
+ primary_hue=gr.themes.colors.purple, secondary_hue=gr.themes.colors.pink, neutral_hue=gr.themes.colors.slate
 
 
63
  ).set(
64
+ body_background_fill="#0F0F1A", block_background_fill="#1A1A2E", block_border_width="1px",
65
+ block_border_color="#2A2A4A", block_label_background_fill="#2A2A4A", input_background_fill="#2A2A4A",
66
+ input_border_color="#4A4A6A", button_primary_background_fill="linear-gradient(135deg, #7F00FF 0%, #E100FF 100%)",
67
+ button_primary_text_color="white", button_secondary_background_fill="#4A4A6A",
68
+ button_secondary_text_color="#E0E0FF", slider_color="#A020F0"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  )
70
+ omega_css = """ /* ... (Your full omega_css string from the "WOW UI" version) ... */ """
71
+ # For brevity, I'll assume the full omega_css string is here. Copy it from the previous response.
72
+ # Example start: body, .gradio-container { background-color: #0F0F1A !important; ... }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  # --- Helper: Placeholder Image Creation ---
75
  def create_placeholder_image(text="Processing...", size=(512, 512), color="#23233A", text_color="#E0E0FF"):
76
+ # ... (Full implementation from previous "WOW UI" version) ...
77
+ img = Image.new('RGB', size, color=color); draw = ImageDraw.Draw(img)
78
+ try: font = ImageFont.truetype("arial.ttf", 40) if os.path.exists("arial.ttf") else ImageFont.load_default()
79
+ except IOError: font = ImageFont.load_default()
80
+ if hasattr(draw, 'textbbox'): bbox = draw.textbbox((0,0), text, font=font); tw, th = bbox[2]-bbox[0], bbox[3]-bbox[1]
81
+ else: tw, th = draw.textsize(text, font=font) # Fallback
82
+ draw.text(((size[0]-tw)/2, (size[1]-th)/2), text, font=font, fill=text_color); return img
83
+
84
+ # --- StoryVerse Weaver Orchestrator ---
85
+ def add_scene_to_story_orchestrator(
 
 
 
 
 
 
 
 
 
86
  current_story_obj: Story, scene_prompt_text: str, image_style_dropdown: str, artist_style_text: str,
87
  negative_prompt_text: str, text_model_key: str, image_provider_key: str,
88
+ narrative_length: str, image_quality: str,
 
 
89
  progress=gr.Progress(track_tqdm=True)
90
  ):
91
+ # --- Define UI components for yielding (must match those in `with gr.Blocks...`) ---
92
+ # This mapping is conceptual if you yield component objects directly.
93
+ # If yielding dicts with string keys (like elem_id), ensure they match.
94
+ # For direct object yield:
95
+ # ui_status = output_status_bar
96
+ # ui_latest_img = output_latest_scene_image
97
+ # ... etc.
98
+
99
+ if not current_story_obj: current_story_obj = Story()
100
 
101
+ log_accumulator = [f"**🚀 Scene {current_story_obj.current_scene_number + 1} - {time.strftime('%H:%M:%S')}**"]
102
+ # Initial UI update using direct component updates in yield
103
  yield {
104
  output_status_bar: gr.HTML(value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
105
  output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals..."), visible=True),
106
  output_latest_scene_narrative: gr.Markdown(value=" Musing narrative...", visible=True),
107
+ engage_button: gr.Button(interactive=False),
108
  surprise_button: gr.Button(interactive=False),
109
+ output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) # Initial log
110
  }
111
 
112
+ try:
113
+ if not scene_prompt_text.strip():
114
+ raise ValueError("Scene prompt cannot be empty!")
115
+
116
+ # --- 1. Generate Narrative Text ---
117
+ progress(0.1, desc="✍️ Crafting narrative...")
118
+ narrative_text_generated = f"Narrative Error: Generation failed for '{scene_prompt_text[:30]}...'." # Default error
119
+ text_model_info = TEXT_MODELS.get(text_model_key)
120
+ if text_model_info and text_model_info["type"] != "none":
121
+ # ... (Full narrative generation logic as in your last working add_scene_to_story) ...
122
+ system_p = get_narrative_system_prompt("default")
123
+ prev_narrative = current_story_obj.get_last_scene_narrative()
124
+ user_p = format_narrative_user_prompt(scene_prompt_text, prev_narrative)
125
+ log_accumulator.append(f" Narrative: Using {text_model_key} ({text_model_info['id']}). Length aim: {narrative_length}")
126
+ text_response = None
127
+ 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)
128
+ 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)
129
+ if text_response and text_response.success: narrative_text_generated = basic_text_cleanup(text_response.text); log_accumulator.append(f" Narrative: Success.")
130
+ elif text_response: narrative_text_generated = f"**Narrative Error ({text_model_key}):** {text_response.error}"; log_accumulator.append(f" Narrative: FAILED - {text_response.error}")
131
+ else: log_accumulator.append(f" Narrative: FAILED - No response from {text_model_key}.")
132
+ else: narrative_text_generated = "**Narrative Error:** Text model unavailable."; log_accumulator.append(f" Narrative: FAILED - Model '{text_model_key}' unavailable.")
133
+
134
+ yield { output_latest_scene_narrative: gr.Markdown(value=f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}"),
135
+ output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
136
+
137
+ # --- 2. Generate Image ---
138
+ progress(0.5, desc="🎨 Conjuring visuals...")
139
+ image_generated_pil = None
140
+ image_generation_error_message = None
141
+ selected_image_provider_type = IMAGE_PROVIDERS.get(image_provider_key)
142
+ image_content_prompt_for_gen = narrative_text_generated if narrative_text_generated and "Error" not in narrative_text_generated else scene_prompt_text
143
+ quality_keyword = "ultra detailed, intricate, masterpiece, " if image_quality == "High Detail" else ("concept sketch, line art, " if image_quality == "Sketch Concept" else "")
144
+ full_image_prompt = format_image_generation_prompt(quality_keyword + image_content_prompt_for_gen[:350], image_style_dropdown, artist_style_text)
145
+ log_accumulator.append(f" Image: Using {image_provider_key}. Style: {image_style_dropdown}. Artist: {artist_style_text or 'N/A'}.")
146
+
147
+ if selected_image_provider_type and selected_image_provider_type != "none":
148
+ # ... (Full image generation logic as in your last working add_scene_to_story) ...
149
+ image_response = None
150
+ 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)
151
+ elif selected_image_provider_type == "dalle": image_response = generate_image_dalle(full_image_prompt, quality="hd" if image_quality=="High Detail" else "standard")
152
+ if image_response and image_response.success: image_generated_pil = image_response.image; log_accumulator.append(f" Image: Success.")
153
+ elif image_response: image_generation_error_message = f"**Image Error ({image_response.provider}):** {image_response.error}"; log_accumulator.append(f" Image: FAILED - {image_response.error}")
154
+ else: image_generation_error_message = f"**Image Error:** No response from {image_provider_key}."; log_accumulator.append(f" Image: FAILED - No response.")
155
+ else: image_generation_error_message = "**Image Error:** Image provider unavailable."; log_accumulator.append(f" Image: FAILED - Provider '{image_provider_key}' unavailable.")
156
+
157
+ yield { output_latest_scene_image: gr.Image(value=image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010")),
158
+ output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
159
+
160
+ # --- 3. Add Scene to Story Object ---
161
+ final_scene_error = None
162
+ # ... (Logic to set final_scene_error based on narrative and image errors) ...
163
+ if image_generation_error_message and "**Narrative Error**" in narrative_text_generated : final_scene_error = f"{narrative_text_generated}\n{image_generation_error_message}"
164
+ elif "**Narrative Error**" in narrative_text_generated: final_scene_error = narrative_text_generated
165
+ elif image_generation_error_message: final_scene_error = image_generation_error_message
166
+
167
+ current_story_obj.add_scene_from_elements(
168
+ user_prompt=scene_prompt_text,
169
+ narrative_text=narrative_text_generated if "**Narrative Error**" not in narrative_text_generated else "(Narrative gen failed)",
170
+ image=image_generated_pil,
171
+ image_style_prompt=f"{image_style_dropdown}{f', by {artist_style_text}' if artist_style_text and artist_style_text.strip() else ''}",
172
+ image_provider=image_provider_key if selected_image_provider_type != "none" else "N/A",
173
+ error_message=final_scene_error
174
+ )
175
+ log_accumulator.append(f" Scene {current_story_obj.current_scene_number} processed.")
176
+
177
+ # --- 4. Prepare Final Outputs for Gradio ---
178
+ gallery_items_tuples = current_story_obj.get_all_scenes_for_gallery_display()
179
+ _ , latest_narr_for_display_final = current_story_obj.get_latest_scene_details_for_display()
180
+
181
+ status_message_html = 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>"
182
+
183
+ progress(1.0, desc="Scene Complete!")
184
+
185
+ # Final return for the .click() handler's `outputs` list
186
+ return (
187
+ current_story_obj,
188
+ gallery_items_tuples,
189
+ image_generated_pil if image_generated_pil else create_placeholder_image("No Image" if not final_scene_error else "Image Error", color="#23233A"),
190
+ latest_narr_for_display_final,
191
+ gr.HTML(value=status_message_html),
192
+ "\n".join(log_accumulator)
193
+ )
194
+
195
+ except ValueError as ve: # Catch our specific input/config errors
196
+ log_accumulator.append(f"\n**INPUT/CONFIG ERROR:** {ve}")
197
+ status_html_err = f"<p style='color: red;'>❌ CONFIGURATION ERROR: {ve}</p>"
198
+ # Return values for all outputs in case of error to prevent None issues
199
+ return current_story_obj, current_story_obj.get_all_scenes_for_gallery_display(), None, f"## Error\n{ve}", gr.HTML(value=status_html_err), "\n".join(log_accumulator)
200
+ except Exception as e:
201
+ log_accumulator.append(f"\n**UNEXPECTED RUNTIME ERROR:** {type(e).__name__} - {e}\n{traceback.format_exc()}")
202
+ status_html_err_unexp = f"<p style='color: red;'>❌ UNEXPECTED ERROR: {e}. Check logs.</p>"
203
+ return current_story_obj, current_story_obj.get_all_scenes_for_gallery_display(), None, "## Unexpected Error\nSee log for details.", gr.HTML(value=status_html_err_unexp), "\n".join(log_accumulator)
204
+ finally: # Ensure buttons are re-enabled even if an error occurs mid-yield
205
+ # This yield will be the last one if no error, or one of the last if error happened
206
+ # However, the final `return` is what matters for the outputs list of .click()
207
+ # We can also yield here to ensure buttons are re-enabled after processing.
208
+ yield { engage_button: gr.Button(interactive=True), surprise_button: gr.Button(interactive=True) }
209
 
210
 
211
  def clear_story_state_ui_wrapper():
 
212
  new_story = Story()
213
+ placeholder_img = create_placeholder_image("Your StoryVerse is a blank canvas...", color="#1A1A2E", text_color="#A0A0C0")
214
  cleared_gallery = [(placeholder_img, "Your StoryVerse is new and untold...")]
215
  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!"
216
  status_msg = "<p class='processing_text status_text'>📜 Story Cleared. A fresh canvas awaits your imagination!</p>"
217
+
218
+ # Return a TUPLE in the order of the .click() outputs list
219
+ return (
220
+ new_story,
221
+ cleared_gallery,
222
+ None, # For latest_scene_image_output
223
+ gr.Markdown(value=initial_narrative), # For latest_scene_narrative_output
224
+ gr.HTML(value=status_msg), # For output_status_bar
225
+ "Log Cleared. Ready for a new adventure!", # For output_interaction_log_markdown
226
+ "" # For scene_prompt_input (to clear it)
227
+ )
228
 
229
  def surprise_me_func():
230
+ # ... (Same surprise_me_func as before)
231
+ themes = ["Cosmic Horror", "Solarpunk Utopia", "Mythic Fantasy", "Noir Detective", "Silent Film Comedy"]
232
+ 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"]
233
+ 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"]
234
+ prompt = f"A protagonist {random.choice(actions)} {random.choice(settings)}. The overall theme is {random.choice(themes)}."
 
235
  style = random.choice(list(STYLE_PRESETS.keys()))
236
+ artist = random.choice(["H.R. Giger", "Moebius", "Eyvind Earle", " Remedios Varo", ""]*2)
237
  return prompt, style, artist
238
 
239
 
240
  # --- Gradio UI Definition ---
241
  with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨ - AI Story & World Weaver") as story_weaver_demo:
242
+ # Define output components that will be updated by the orchestrator
243
+ # story_state_output will be a gr.State component
244
+ story_state_output = gr.State(Story()) # Initial value
245
 
246
  gr.Markdown("<div align='center'><h1>✨ StoryVerse Omega ✨</h1>\n<h3>Craft Immersive Multimodal Worlds with AI</h3></div>")
247
  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>")
248
 
249
  with gr.Accordion("🔧 AI Services Status & Info", open=False):
 
250
  status_text_list = []
251
  text_llm_ok, image_gen_ok = (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY), (STABILITY_API_IS_READY or OPENAI_DALLE_IS_READY)
252
+ 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>")
253
  else:
254
+ if text_llm_ok: status_text_list.append("<p style='color:#A7F3D0;'>✅ Text Generation Service(s) Ready.</p>")
255
+ else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Text Generation Service(s) NOT Ready.</p>")
256
+ if image_gen_ok: status_text_list.append("<p style='color:#A7F3D0;'>✅ Image Generation Service(s) Ready.</p>")
257
+ else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Image Generation Service(s) NOT Ready.</p>")
258
  gr.HTML("".join(status_text_list))
259
 
 
260
  with gr.Row(equal_height=False, variant="panel"):
261
+ with gr.Column(scale=7, min_width=450):
262
  gr.Markdown("### 💡 **Craft Your Scene**", elem_classes="input-section-header")
263
  with gr.Group():
264
  scene_prompt_input = gr.Textbox(lines=7, label="Scene Vision (Description, Dialogue, Action):", placeholder="e.g., Amidst swirling cosmic dust, Captain Eva pilots her damaged starfighter towards a colossal, ringed gas giant. Alarms blare. 'Just a little further,' she mutters, gripping the controls.")
 
267
  with gr.Column(scale=2):
268
  image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style Preset")
269
  with gr.Column(scale=2):
270
+ artist_style_input = gr.Textbox(label="Artistic Inspiration (Optional):", placeholder="e.g., Moebius, Zdzisław Beksiński")
271
 
272
  negative_prompt_input = gr.Textbox(lines=2, label="Exclude from Image (Negative Prompt):", placeholder="Default exclusions applied. Add more if needed.", value=COMMON_NEGATIVE_PROMPTS)
273
 
 
281
 
282
  with gr.Row(elem_classes=["compact-row"], equal_height=True):
283
  engage_button = gr.Button("🌌 Weave This Scene!", variant="primary", scale=3, icon="✨")
284
+ surprise_button = gr.Button("🎲 Surprise Me!", variant="secondary", scale=1, icon="🎁")
285
+ clear_story_button = gr.Button("🗑️ New Story", variant="stop", scale=1, icon="♻️")
286
 
287
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave your first masterpiece!</p>")
288
 
289
+ with gr.Column(scale=10, min_width=700):
290
  gr.Markdown("### 🖼️ **Your Evolving StoryVerse**", elem_classes="output-section-header")
291
+ with gr.Tabs():
292
+ with gr.TabItem("🌠 Latest Scene", id="latest_scene_tab"):
293
+ output_latest_scene_image = gr.Image(label="Latest Scene Image", type="pil", interactive=False, show_download_button=True, height=512, show_label=False, elem_classes=["panel_image"])
294
+ output_latest_scene_narrative = gr.Markdown()
 
295
 
296
+ with gr.TabItem("📚 Story Scroll", id="story_scroll_tab"):
297
+ output_gallery = gr.Gallery(label="Story Scroll", show_label=False, columns=4, object_fit="cover", height=700, preview=True, allow_preview=True, elem_classes=["gallery_output"])
298
 
299
+ with gr.TabItem("⚙️ Interaction Log", id="log_tab"):
300
+ with gr.Accordion(label="Developer Interaction Log", open=False):
301
  output_interaction_log_markdown = gr.Markdown("Log will appear here...")
302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  engage_button.click(
304
+ fn=add_scene_to_story_orchestrator,
305
  inputs=[
306
  story_state_output, scene_prompt_input,
307
  image_style_input, artist_style_input, negative_prompt_input,
308
  text_model_dropdown, image_provider_dropdown,
309
+ narrative_length_dropdown, image_quality_dropdown
310
  ],
311
+ outputs=[ # These components are updated by the FINAL return of the orchestrator
312
  story_state_output,
313
  output_gallery,
314
  output_latest_scene_image,
315
  output_latest_scene_narrative,
316
  output_status_bar,
317
  output_interaction_log_markdown
 
318
  ]
319
+ # Progressive updates are handled by `yield {component_variable: new_value}` inside the orchestrator
320
  )
321
  clear_story_button.click(
322
  fn=clear_story_state_ui_wrapper,
323
  inputs=[],
324
+ outputs=[
325
  story_state_output, output_gallery,
326
  output_latest_scene_image, output_latest_scene_narrative,
327
  output_status_bar, output_interaction_log_markdown,
328
+ scene_prompt_input
329
  ]
330
  )
331
  surprise_button.click(
 
341
  ["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"],
342
  ["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"]
343
  ],
344
+ inputs=[scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input],
345
  label="🌌 Example Universes to Weave 🌌",
346
  )
347
  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>")
348
 
349
+ # --- Entry Point for Running the Gradio App ---
350
  if __name__ == "__main__":
351
  print("="*80)
352
  print("✨ StoryVerse Omega™ - AI Story & World Weaver - Launching... ✨")
 
360
  print(f" Default Image Provider: {UI_DEFAULT_IMAGE_PROVIDER_KEY}")
361
  print("="*80)
362
 
363
+ story_weaver_demo.launch(debug=True, server_name="0.0.0.0", share=False)