mgbam commited on
Commit
6bf2bd9
Β·
verified Β·
1 Parent(s): 3c54be4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -145
app.py CHANGED
@@ -26,6 +26,7 @@ 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:
@@ -56,51 +57,16 @@ 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 = """
71
- body, .gradio-container { background-color: #0F0F1A !important; color: #D0D0E0 !important; }
72
- .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;}
73
- .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);}
74
- .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;}
75
- .gr-markdown h3 { color: #C080F0 !important; text-align: center; font-weight: 400; margin-bottom: 25px !important;}
76
- .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;}
77
- .output-section-header { font-size: 1.8em; font-weight: 600; color: #D0D0FF; margin-top: 15px; margin-bottom: 12px;}
78
- .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;}
79
- .gr-button { border-radius: 8px !important; font-weight: 500 !important; transition: all 0.2s ease-in-out !important;}
80
- .gr-button-primary:hover { transform: scale(1.03) translateY(-1px) !important; box-shadow: 0 8px 16px rgba(127,0,255,0.3) !important; }
81
- .panel_image { border-radius: 12px !important; overflow: hidden; box-shadow: 0 6px 15px rgba(0,0,0,0.25) !important; background-color: #23233A;}
82
- .panel_image img { max-height: 600px !important; }
83
- .gallery_output { background-color: transparent !important; border: none !important; }
84
- .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;}
85
- .gallery_output .thumbnail-item:hover { transform: scale(1.05); }
86
- .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;}
87
- .error_text { background-color: #401010 !important; color: #FFB0B0 !important; border-color: #802020 !important; }
88
- .success_text { background-color: #104010 !important; color: #B0FFB0 !important; border-color: #208020 !important;}
89
- .processing_text { background-color: #102040 !important; color: #B0D0FF !important; border-color: #204080 !important;}
90
- .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;}
91
- .gr-tabitem { background-color: #1A1A2E !important; border-radius: 0 0 12px 12px !important; padding: 15px !important;}
92
- .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;}
93
- .gr-tab-button { color: #A0A0C0 !important; border-radius: 8px 8px 0 0 !important;}
94
- .gr-accordion > .gr-block { border-top: 1px solid #2A2A4A !important; }
95
- .gr-markdown code { background-color: #2A2A4A !important; color: #C0C0E0 !important; padding: 0.2em 0.5em; border-radius: 4px; }
96
- .gr-markdown pre { background-color: #23233A !important; padding: 1em !important; border-radius: 6px !important; border: 1px solid #2A2A4A !important;}
97
- .gr-markdown pre > code { padding: 0 !important; background-color: transparent !important; }
98
- #surprise_button { background: linear-gradient(135deg, #ff7e5f 0%, #feb47b 100%) !important; font-weight:600 !important;}
99
- #surprise_button:hover { transform: scale(1.03) translateY(-1px) !important; box-shadow: 0 8px 16px rgba(255,126,95,0.3) !important; }
100
- """
101
 
102
  # --- Helper: Placeholder Image Creation ---
103
  def create_placeholder_image(text="Processing...", size=(512, 512), color="#23233A", text_color="#E0E0FF"):
 
104
  img = Image.new('RGB', size, color=color); draw = ImageDraw.Draw(img)
105
  try: font_path = "arial.ttf" if os.path.exists("arial.ttf") else None
106
  except: font_path = None
@@ -117,33 +83,25 @@ def add_scene_to_story_orchestrator(
117
  narrative_length: str, image_quality: str,
118
  progress=gr.Progress(track_tqdm=True)
119
  ):
120
- # Initialize start_time here
121
  start_time = time.time()
122
-
123
  if not current_story_obj: current_story_obj = Story()
124
 
125
  log_accumulator = [f"**πŸš€ Scene {current_story_obj.current_scene_number + 1} - {time.strftime('%H:%M:%S')}**"]
126
 
127
- # Define placeholders for the final return tuple values
128
- # This ensures they exist even if errors occur early.
129
- # Order must match engage_button.click outputs list
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 = gr.Markdown(value="## Error\nProcessing did not complete.")
134
- ret_status_bar = gr.HTML(value="<p class='error_text status_text'>An error occurred during processing.</p>")
135
- ret_log = gr.Markdown(value="\n".join(log_accumulator))
136
-
137
-
138
- # Initial UI update using direct component updates in yield by component variable name
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..."), visible=True),
142
  output_latest_scene_narrative: gr.Markdown(value=" Musing narrative...", visible=True),
143
- engage_button: gr.Button(interactive=False), # Disable button
144
  surprise_button: gr.Button(interactive=False),
145
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator))
 
 
 
146
  }
 
147
 
148
  try:
149
  if not scene_prompt_text.strip():
@@ -152,11 +110,10 @@ def add_scene_to_story_orchestrator(
152
  # --- 1. Generate Narrative Text ---
153
  progress(0.1, desc="✍️ Crafting narrative...")
154
  narrative_text_generated = f"Narrative Error: Init failed."
 
155
  text_model_info = TEXT_MODELS.get(text_model_key)
156
  if text_model_info and text_model_info["type"] != "none":
157
- system_p = get_narrative_system_prompt("default")
158
- prev_narrative = current_story_obj.get_last_scene_narrative()
159
- user_p = format_narrative_user_prompt(scene_prompt_text, prev_narrative)
160
  log_accumulator.append(f" Narrative: Using {text_model_key} ({text_model_info['id']}). Length: {narrative_length}")
161
  text_response = None
162
  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)
@@ -166,20 +123,20 @@ def add_scene_to_story_orchestrator(
166
  else: log_accumulator.append(f" Narrative: FAILED - No response from {text_model_key}.")
167
  else: narrative_text_generated = "**Narrative Error:** Text model unavailable."; log_accumulator.append(f" Narrative: FAILED - Model '{text_model_key}' unavailable.")
168
 
169
- ret_latest_narrative = gr.Markdown(value=f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}")
170
- yield { output_latest_scene_narrative: ret_latest_narrative,
171
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
172
 
173
  # --- 2. Generate Image ---
174
  progress(0.5, desc="🎨 Conjuring visuals...")
175
  image_generated_pil = None
176
  image_generation_error_message = None
 
177
  selected_image_provider_type = IMAGE_PROVIDERS.get(image_provider_key)
178
  image_content_prompt_for_gen = narrative_text_generated if narrative_text_generated and "Error" not in narrative_text_generated else scene_prompt_text
179
- quality_keyword = "ultra detailed, intricate, masterpiece, " if image_quality == "High Detail" else ("concept sketch, line art, " if image_quality == "Sketch Concept" else "")
180
  full_image_prompt = format_image_generation_prompt(quality_keyword + image_content_prompt_for_gen[:350], image_style_dropdown, artist_style_text)
181
  log_accumulator.append(f" Image: Using {image_provider_key}. Style: {image_style_dropdown}. Artist: {artist_style_text or 'N/A'}.")
182
-
183
  if selected_image_provider_type and selected_image_provider_type != "none":
184
  image_response = None
185
  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)
@@ -189,12 +146,13 @@ def add_scene_to_story_orchestrator(
189
  else: image_generation_error_message = f"**Image Error:** No response from {image_provider_key}."; log_accumulator.append(f" Image: FAILED - No response.")
190
  else: image_generation_error_message = "**Image Error:** Image provider unavailable."; log_accumulator.append(f" Image: FAILED - Provider '{image_provider_key}' unavailable.")
191
 
192
- ret_latest_image = image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010")
193
- yield { output_latest_scene_image: gr.Image(value=ret_latest_image),
194
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
195
 
196
  # --- 3. Add Scene to Story Object ---
197
  final_scene_error = None
 
198
  if image_generation_error_message and "**Narrative Error**" in narrative_text_generated : final_scene_error = f"{narrative_text_generated}\n{image_generation_error_message}"
199
  elif "**Narrative Error**" in narrative_text_generated: final_scene_error = narrative_text_generated
200
  elif image_generation_error_message: final_scene_error = image_generation_error_message
@@ -207,93 +165,103 @@ def add_scene_to_story_orchestrator(
207
  image_provider=image_provider_key if selected_image_provider_type != "none" else "N/A",
208
  error_message=final_scene_error
209
  )
210
- ret_story_state = current_story_obj
211
- log_accumulator.append(f" Scene {current_story_obj.current_scene_number} processed and added.")
212
 
213
- # --- 4. Prepare Final Values for Return Tuple ---
214
- ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
215
  _ , latest_narr_for_display_final_str = current_story_obj.get_latest_scene_details_for_display()
216
- ret_latest_narrative = gr.Markdown(value=latest_narr_for_display_final_str)
217
 
218
  status_html_str = 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>"
219
- ret_status_bar = gr.HTML(value=status_html_str)
220
 
221
  progress(1.0, desc="Scene Complete!")
222
 
223
  except ValueError as ve:
224
  log_accumulator.append(f"\n**INPUT/CONFIG ERROR:** {ve}")
225
- ret_status_bar = gr.HTML(value=f"<p class='error_text status_text'>❌ CONFIGURATION ERROR: {ve}</p>")
226
- ret_latest_narrative = gr.Markdown(value=f"## Error\n{ve}")
227
  except Exception as e:
228
  log_accumulator.append(f"\n**UNEXPECTED RUNTIME ERROR:** {type(e).__name__} - {e}\n{traceback.format_exc()}")
229
- ret_status_bar = gr.HTML(value=f"<p class='error_text status_text'>❌ UNEXPECTED ERROR: {type(e).__name__}. Check logs.</p>")
230
- ret_latest_narrative = gr.Markdown(value=f"## Unexpected Error\n{type(e).__name__}: {e}\nSee log for details.")
231
  finally:
232
  current_total_time = time.time() - start_time
233
  log_accumulator.append(f" Cycle ended at {time.strftime('%H:%M:%S')}. Total time: {current_total_time:.2f}s")
234
- ret_log = gr.Markdown(value="\n".join(log_accumulator))
 
 
235
 
236
- # This yield is only for button states, does not affect the main 'return'
237
- yield {
238
- engage_button: gr.Button(interactive=True),
239
- surprise_button: gr.Button(interactive=True),
240
- output_interaction_log_markdown: ret_log # Update log one last time via yield
241
- }
242
 
243
- # Final return for the .click() handler's `outputs` list
244
- return ret_story_state, ret_gallery, ret_latest_image, ret_latest_narrative, ret_status_bar, ret_log
 
245
 
246
 
247
  def clear_story_state_ui_wrapper():
248
- new_story = Story()
249
- placeholder_img = create_placeholder_image("Your StoryVerse is a blank canvas...", color="#1A1A2E", text_color="#A0A0C0")
250
- cleared_gallery = [(placeholder_img, "Your StoryVerse is new and untold...")]
251
- 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!"
252
- status_msg = "<p class='processing_text status_text'>πŸ“œ Story Cleared. A fresh canvas awaits your imagination!</p>"
253
- return (new_story, cleared_gallery, None, gr.Markdown(value=initial_narrative), gr.HTML(value=status_msg), "Log Cleared. Ready for a new adventure!", "")
254
 
255
  def surprise_me_func():
256
- themes = ["Cosmic Horror", "Solarpunk Utopia", "Mythic Fantasy", "Noir Detective", "Silent Film Comedy", "Deep Sea Exploration", "Prehistoric Survival"]
257
- 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"]
258
- 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"]
259
- prompt = f"A protagonist {random.choice(actions)} {random.choice(settings)}. The overall theme is {random.choice(themes)}."
260
- style = random.choice(list(STYLE_PRESETS.keys()))
261
- artist = random.choice(["H.R. Giger", "Moebius", "Eyvind Earle", " Remedios Varo", "Alphonse Mucha", ""]*2)
262
- return prompt, style, artist
263
 
264
  # --- Gradio UI Definition ---
265
- with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨ - AI Story & World Weaver") as story_weaver_demo:
266
- # Define output components that will be updated by the orchestrator
 
267
  story_state_output = gr.State(Story())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
 
269
  gr.Markdown("<div align='center'><h1>✨ StoryVerse Omega ✨</h1>\n<h3>Craft Immersive Multimodal Worlds with AI</h3></div>")
270
- 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>")
271
 
272
  with gr.Accordion("πŸ”§ AI Services Status & Info", open=False):
273
- status_text_list = []
274
- text_llm_ok, image_gen_ok = (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY), (STABILITY_API_IS_READY or OPENAI_DALLE_IS_READY)
275
  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>")
276
  else:
277
- if text_llm_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Text Generation Service(s) Ready.</p>")
278
- else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Text Generation Service(s) NOT Ready.</p>")
279
- if image_gen_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Image Generation Service(s) Ready.</p>")
280
- else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Image Generation Service(s) NOT Ready.</p>")
281
  gr.HTML("".join(status_text_list))
282
 
283
  with gr.Row(equal_height=False, variant="panel"):
284
  with gr.Column(scale=7, min_width=450):
285
  gr.Markdown("### πŸ’‘ **Craft Your Scene**", elem_classes="input-section-header")
286
- with gr.Group():
287
- 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.")
288
-
289
  with gr.Row(elem_classes=["compact-row"]):
290
  with gr.Column(scale=2):
291
  image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style Preset")
292
  with gr.Column(scale=2):
293
- artist_style_input = gr.Textbox(label="Artistic Inspiration (Optional):", placeholder="e.g., Moebius, ZdzisΕ‚aw BeksiΕ„ski")
294
-
295
- 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)
296
-
297
  with gr.Accordion("βš™οΈ Advanced AI Configuration", open=False):
298
  with gr.Group():
299
  text_model_dropdown = gr.Dropdown(choices=list(TEXT_MODELS.keys()), value=UI_DEFAULT_TEXT_MODEL_KEY, label="Narrative AI Engine")
@@ -301,24 +269,20 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
301
  with gr.Row():
302
  narrative_length_dropdown = gr.Dropdown(["Short (1 paragraph)", "Medium (2-3 paragraphs)", "Detailed (4+ paragraphs)"], value="Medium (2-3 paragraphs)", label="Narrative Detail")
303
  image_quality_dropdown = gr.Dropdown(["Standard", "High Detail", "Sketch Concept"], value="Standard", label="Image Detail/Style")
304
-
305
- with gr.Row(elem_classes=["compact-row"], equal_height=True):
306
  engage_button = gr.Button("🌌 Weave This Scene!", variant="primary", scale=3, icon="✨")
307
  surprise_button = gr.Button("🎲 Surprise Me!", variant="secondary", scale=1, icon="🎁")
308
  clear_story_button = gr.Button("πŸ—‘οΈ New Story", variant="stop", scale=1, icon="♻️")
309
-
310
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave your first masterpiece!</p>")
311
 
312
  with gr.Column(scale=10, min_width=700):
313
  gr.Markdown("### πŸ–ΌοΈ **Your Evolving StoryVerse**", elem_classes="output-section-header")
314
  with gr.Tabs():
315
- with gr.TabItem("🌠 Latest Scene", id="latest_scene_tab"):
316
  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"])
317
  output_latest_scene_narrative = gr.Markdown()
318
-
319
  with gr.TabItem("πŸ“š Story Scroll", id="story_scroll_tab"):
320
  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"])
321
-
322
  with gr.TabItem("βš™οΈ Interaction Log", id="log_tab"):
323
  with gr.Accordion(label="Developer Interaction Log", open=False):
324
  output_interaction_log_markdown = gr.Markdown("Log will appear here...")
@@ -331,13 +295,18 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
331
  text_model_dropdown, image_provider_dropdown,
332
  narrative_length_dropdown, image_quality_dropdown
333
  ],
334
- outputs=[ # These components are updated by the FINAL return tuple of the orchestrator
335
  story_state_output,
336
  output_gallery,
337
  output_latest_scene_image,
338
  output_latest_scene_narrative,
339
  output_status_bar,
340
  output_interaction_log_markdown
 
 
 
 
 
341
  ]
342
  )
343
  clear_story_button.click(
@@ -355,31 +324,20 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
355
  inputs=[],
356
  outputs=[scene_prompt_input, image_style_input, artist_style_input]
357
  )
358
-
359
- gr.Examples(
360
- examples=[
361
- ["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"],
362
- ["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"],
363
- ["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"],
364
- ["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"]
365
- ],
366
- inputs=[scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input],
367
  label="🌌 Example Universes to Weave 🌌",
368
  )
369
- 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>")
370
 
371
  # --- Entry Point ---
372
  if __name__ == "__main__":
 
 
 
 
 
 
373
  print("="*80)
374
- print("✨ StoryVerse Omegaβ„’ - AI Story & World Weaver - Launching... ✨")
375
- print(f" Text LLM Ready (Gemini): {GEMINI_TEXT_IS_READY}")
376
- print(f" Text LLM Ready (HF): {HF_TEXT_IS_READY}")
377
- print(f" Image Provider Ready (Stability AI): {STABILITY_API_IS_READY}")
378
- print(f" Image Provider Ready (DALL-E): {OPENAI_DALLE_IS_READY}")
379
- if not (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY) or not (STABILITY_API_IS_READY or OPENAI_DALLE_IS_READY):
380
- print(" πŸ”΄ WARNING: Not all required AI services are configured correctly.")
381
- print(f" Default Text Model: {UI_DEFAULT_TEXT_MODEL_KEY}")
382
- print(f" Default Image Provider: {UI_DEFAULT_IMAGE_PROVIDER_KEY}")
383
- print("="*80)
384
-
385
  story_weaver_demo.launch(debug=True, server_name="0.0.0.0", share=False)
 
26
  OPENAI_DALLE_IS_READY = OPENAI_DALLE_CONFIGURED
27
 
28
  # --- Application Configuration (Models, Defaults) ---
29
+ # (This section remains the same - ensure TEXT_MODELS, UI_DEFAULT_TEXT_MODEL_KEY, etc. are defined)
30
  TEXT_MODELS = {}
31
  UI_DEFAULT_TEXT_MODEL_KEY = None
32
  if GEMINI_TEXT_IS_READY:
 
57
  IMAGE_PROVIDERS["No Image Providers Configured"] = "none"
58
  UI_DEFAULT_IMAGE_PROVIDER_KEY = "No Image Providers Configured"
59
 
60
+
61
  # --- Gradio UI Theme and CSS ---
62
+ # (omega_theme and omega_css definitions remain the same as the last full version)
63
+ omega_theme = gr.themes.Base(font=[gr.themes.GoogleFont("Lexend Deca"), "ui-sans-serif"], primary_hue=gr.themes.colors.purple, secondary_hue=gr.themes.colors.pink, neutral_hue=gr.themes.colors.slate).set(body_background_fill="#0F0F1A", block_background_fill="#1A1A2E", block_border_width="1px", block_border_color="#2A2A4A", block_label_background_fill="#2A2A4A", input_background_fill="#2A2A4A", input_border_color="#4A4A6A", button_primary_background_fill="linear-gradient(135deg, #7F00FF 0%, #E100FF 100%)", button_primary_text_color="white", button_secondary_background_fill="#4A4A6A", button_secondary_text_color="#E0E0FF", slider_color="#A020F0")
64
+ omega_css = """ /* ... Paste your full omega_css string here ... */ """
65
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  # --- Helper: Placeholder Image Creation ---
68
  def create_placeholder_image(text="Processing...", size=(512, 512), color="#23233A", text_color="#E0E0FF"):
69
+ # ... (Full implementation from previous version) ...
70
  img = Image.new('RGB', size, color=color); draw = ImageDraw.Draw(img)
71
  try: font_path = "arial.ttf" if os.path.exists("arial.ttf") else None
72
  except: font_path = None
 
83
  narrative_length: str, image_quality: str,
84
  progress=gr.Progress(track_tqdm=True)
85
  ):
 
86
  start_time = time.time()
 
87
  if not current_story_obj: current_story_obj = Story()
88
 
89
  log_accumulator = [f"**πŸš€ Scene {current_story_obj.current_scene_number + 1} - {time.strftime('%H:%M:%S')}**"]
90
 
91
+ # --- Define dictionary for UI updates ---
92
+ # Keys are the Python component variables
93
+ updates_dict = {
 
 
 
 
 
 
 
 
 
 
94
  output_status_bar: gr.HTML(value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
95
  output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals..."), visible=True),
96
  output_latest_scene_narrative: gr.Markdown(value=" Musing narrative...", visible=True),
97
+ engage_button: gr.Button(interactive=False),
98
  surprise_button: gr.Button(interactive=False),
99
+ output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)),
100
+ # Initialize other output components that are in the .click() outputs list
101
+ story_state_output: current_story_obj, # Pass current state
102
+ output_gallery: current_story_obj.get_all_scenes_for_gallery_display() # Initial gallery
103
  }
104
+ yield updates_dict
105
 
106
  try:
107
  if not scene_prompt_text.strip():
 
110
  # --- 1. Generate Narrative Text ---
111
  progress(0.1, desc="✍️ Crafting narrative...")
112
  narrative_text_generated = f"Narrative Error: Init failed."
113
+ # ... (Full narrative generation logic, updating narrative_text_generated and log_accumulator) ...
114
  text_model_info = TEXT_MODELS.get(text_model_key)
115
  if text_model_info and text_model_info["type"] != "none":
116
+ system_p = get_narrative_system_prompt("default"); prev_narrative = current_story_obj.get_last_scene_narrative(); user_p = format_narrative_user_prompt(scene_prompt_text, prev_narrative)
 
 
117
  log_accumulator.append(f" Narrative: Using {text_model_key} ({text_model_info['id']}). Length: {narrative_length}")
118
  text_response = None
119
  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)
 
123
  else: log_accumulator.append(f" Narrative: FAILED - No response from {text_model_key}.")
124
  else: narrative_text_generated = "**Narrative Error:** Text model unavailable."; log_accumulator.append(f" Narrative: FAILED - Model '{text_model_key}' unavailable.")
125
 
126
+ updates_dict[output_latest_scene_narrative] = gr.Markdown(value=f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}")
127
+ updates_dict[output_interaction_log_markdown] = gr.Markdown(value="\n".join(log_accumulator))
128
+ yield updates_dict
129
 
130
  # --- 2. Generate Image ---
131
  progress(0.5, desc="🎨 Conjuring visuals...")
132
  image_generated_pil = None
133
  image_generation_error_message = None
134
+ # ... (Full image generation logic, updating image_generated_pil, image_generation_error_message, log_accumulator) ...
135
  selected_image_provider_type = IMAGE_PROVIDERS.get(image_provider_key)
136
  image_content_prompt_for_gen = narrative_text_generated if narrative_text_generated and "Error" not in narrative_text_generated else scene_prompt_text
137
+ quality_keyword = "ultra detailed, " if image_quality == "High Detail" else ("concept sketch, " if image_quality == "Sketch Concept" else "")
138
  full_image_prompt = format_image_generation_prompt(quality_keyword + image_content_prompt_for_gen[:350], image_style_dropdown, artist_style_text)
139
  log_accumulator.append(f" Image: Using {image_provider_key}. Style: {image_style_dropdown}. Artist: {artist_style_text or 'N/A'}.")
 
140
  if selected_image_provider_type and selected_image_provider_type != "none":
141
  image_response = None
142
  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)
 
146
  else: image_generation_error_message = f"**Image Error:** No response from {image_provider_key}."; log_accumulator.append(f" Image: FAILED - No response.")
147
  else: image_generation_error_message = "**Image Error:** Image provider unavailable."; log_accumulator.append(f" Image: FAILED - Provider '{image_provider_key}' unavailable.")
148
 
149
+ updates_dict[output_latest_scene_image] = gr.Image(value=image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010"))
150
+ updates_dict[output_interaction_log_markdown] = gr.Markdown(value="\n".join(log_accumulator))
151
+ yield updates_dict
152
 
153
  # --- 3. Add Scene to Story Object ---
154
  final_scene_error = None
155
+ # ... (Logic to set final_scene_error) ...
156
  if image_generation_error_message and "**Narrative Error**" in narrative_text_generated : final_scene_error = f"{narrative_text_generated}\n{image_generation_error_message}"
157
  elif "**Narrative Error**" in narrative_text_generated: final_scene_error = narrative_text_generated
158
  elif image_generation_error_message: final_scene_error = image_generation_error_message
 
165
  image_provider=image_provider_key if selected_image_provider_type != "none" else "N/A",
166
  error_message=final_scene_error
167
  )
168
+ updates_dict[story_state_output] = current_story_obj
169
+ log_accumulator.append(f" Scene {current_story_obj.current_scene_number} processed.")
170
 
171
+ # --- 4. Prepare Final Values for UI Update via Yield ---
172
+ updates_dict[output_gallery] = current_story_obj.get_all_scenes_for_gallery_display()
173
  _ , latest_narr_for_display_final_str = current_story_obj.get_latest_scene_details_for_display()
174
+ updates_dict[output_latest_scene_narrative] = gr.Markdown(value=latest_narr_for_display_final_str)
175
 
176
  status_html_str = 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>"
177
+ updates_dict[output_status_bar] = gr.HTML(value=status_html_str)
178
 
179
  progress(1.0, desc="Scene Complete!")
180
 
181
  except ValueError as ve:
182
  log_accumulator.append(f"\n**INPUT/CONFIG ERROR:** {ve}")
183
+ updates_dict[output_status_bar] = gr.HTML(value=f"<p class='error_text status_text'>❌ CONFIGURATION ERROR: {ve}</p>")
184
+ updates_dict[output_latest_scene_narrative] = gr.Markdown(value=f"## Error\n{ve}")
185
  except Exception as e:
186
  log_accumulator.append(f"\n**UNEXPECTED RUNTIME ERROR:** {type(e).__name__} - {e}\n{traceback.format_exc()}")
187
+ updates_dict[output_status_bar] = gr.HTML(value=f"<p class='error_text status_text'>❌ UNEXPECTED ERROR: {type(e).__name__}. Check logs.</p>")
188
+ updates_dict[output_latest_scene_narrative] = gr.Markdown(value=f"## Unexpected Error\n{type(e).__name__}: {e}\nSee log for details.")
189
  finally:
190
  current_total_time = time.time() - start_time
191
  log_accumulator.append(f" Cycle ended at {time.strftime('%H:%M:%S')}. Total time: {current_total_time:.2f}s")
192
+ updates_dict[output_interaction_log_markdown] = gr.Markdown(value="\n".join(log_accumulator))
193
+ updates_dict[engage_button] = gr.Button(interactive=True)
194
+ updates_dict[surprise_button] = gr.Button(interactive=True)
195
 
196
+ # Final yield containing all updates for components in the outputs list and others
197
+ yield updates_dict
 
 
 
 
198
 
199
+ # No explicit return is needed if all updates are handled by the final yield.
200
+ # Gradio will use the last yielded dictionary for the components in the `outputs` list.
201
+ return # Or return None
202
 
203
 
204
  def clear_story_state_ui_wrapper():
205
+ # ... (Same clear_story_state_ui_wrapper, ensure it returns a TUPLE matching outputs)
206
+ new_story = Story(); placeholder_img = create_placeholder_image("Blank canvas...", color="#1A1A2E", text_color="#A0A0C0")
207
+ cleared_gallery = [(placeholder_img, "StoryVerse is new...")]
208
+ initial_narrative = "## ✨ New Story ✨\nDescribe your first scene!"
209
+ status_msg = "<p class='processing_text status_text'>πŸ“œ Story Cleared.</p>"
210
+ return (new_story, cleared_gallery, None, gr.Markdown(initial_narrative), gr.HTML(status_msg), "Log Cleared.", "")
211
 
212
  def surprise_me_func():
213
+ # ... (Same surprise_me_func as before)
214
+ themes = ["Cosmic Horror", "Solarpunk Utopia"]; actions = ["unearths an artifact", "negotiates with a being"]; 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
215
+
 
 
 
 
216
 
217
  # --- Gradio UI Definition ---
218
+ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨") as story_weaver_demo:
219
+ # --- Define all UI components that will be inputs or outputs first ---
220
+ # This helps Gradio correctly map them when using `yield` with component variables as keys.
221
  story_state_output = gr.State(Story())
222
+ scene_prompt_input = gr.Textbox()
223
+ image_style_input = gr.Dropdown()
224
+ artist_style_input = gr.Textbox()
225
+ negative_prompt_input = gr.Textbox()
226
+ text_model_dropdown = gr.Dropdown()
227
+ image_provider_dropdown = gr.Dropdown()
228
+ narrative_length_dropdown = gr.Dropdown()
229
+ image_quality_dropdown = gr.Dropdown()
230
+ output_gallery = gr.Gallery()
231
+ output_latest_scene_image = gr.Image()
232
+ output_latest_scene_narrative = gr.Markdown()
233
+ output_status_bar = gr.HTML()
234
+ output_interaction_log_markdown = gr.Markdown()
235
+ engage_button = gr.Button()
236
+ surprise_button = gr.Button()
237
+ clear_story_button = gr.Button() # Defined here, though not in outputs of add_scene
238
 
239
+ # --- Layout UI ---
240
  gr.Markdown("<div align='center'><h1>✨ StoryVerse Omega ✨</h1>\n<h3>Craft Immersive Multimodal Worlds with AI</h3></div>")
241
+ gr.HTML("<div class='important-note'><strong>Welcome, Worldsmith!</strong> ... Ensure API keys ...</div>")
242
 
243
  with gr.Accordion("πŸ”§ AI Services Status & Info", open=False):
244
+ # ... (API status HTML generation as before)
245
+ 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)
246
  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>")
247
  else:
248
+ if text_llm_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Text Generation Ready.</p>")
249
+ else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Text Generation NOT Ready.</p>")
250
+ if image_gen_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Image Generation Ready.</p>")
251
+ else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Image Generation NOT Ready.</p>")
252
  gr.HTML("".join(status_text_list))
253
 
254
  with gr.Row(equal_height=False, variant="panel"):
255
  with gr.Column(scale=7, min_width=450):
256
  gr.Markdown("### πŸ’‘ **Craft Your Scene**", elem_classes="input-section-header")
257
+ with gr.Group(): # Redefine components here to bind to the variables
258
+ scene_prompt_input = gr.Textbox(lines=7, label="Scene Vision (Description, Dialogue, Action):", placeholder="e.g., Amidst swirling cosmic dust...")
 
259
  with gr.Row(elem_classes=["compact-row"]):
260
  with gr.Column(scale=2):
261
  image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style Preset")
262
  with gr.Column(scale=2):
263
+ artist_style_input = gr.Textbox(label="Artistic Inspiration (Optional):", placeholder="e.g., Moebius...")
264
+ negative_prompt_input = gr.Textbox(lines=2, label="Exclude from Image (Negative Prompt):", value=COMMON_NEGATIVE_PROMPTS)
 
 
265
  with gr.Accordion("βš™οΈ Advanced AI Configuration", open=False):
266
  with gr.Group():
267
  text_model_dropdown = gr.Dropdown(choices=list(TEXT_MODELS.keys()), value=UI_DEFAULT_TEXT_MODEL_KEY, label="Narrative AI Engine")
 
269
  with gr.Row():
270
  narrative_length_dropdown = gr.Dropdown(["Short (1 paragraph)", "Medium (2-3 paragraphs)", "Detailed (4+ paragraphs)"], value="Medium (2-3 paragraphs)", label="Narrative Detail")
271
  image_quality_dropdown = gr.Dropdown(["Standard", "High Detail", "Sketch Concept"], value="Standard", label="Image Detail/Style")
272
+ with gr.Row(elem_classes=["compact-row"], equal_height=True): # Redefine buttons
 
273
  engage_button = gr.Button("🌌 Weave This Scene!", variant="primary", scale=3, icon="✨")
274
  surprise_button = gr.Button("🎲 Surprise Me!", variant="secondary", scale=1, icon="🎁")
275
  clear_story_button = gr.Button("πŸ—‘οΈ New Story", variant="stop", scale=1, icon="♻️")
 
276
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave your first masterpiece!</p>")
277
 
278
  with gr.Column(scale=10, min_width=700):
279
  gr.Markdown("### πŸ–ΌοΈ **Your Evolving StoryVerse**", elem_classes="output-section-header")
280
  with gr.Tabs():
281
+ with gr.TabItem("🌠 Latest Scene", id="latest_scene_tab"): # Redefine components
282
  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"])
283
  output_latest_scene_narrative = gr.Markdown()
 
284
  with gr.TabItem("πŸ“š Story Scroll", id="story_scroll_tab"):
285
  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"])
 
286
  with gr.TabItem("βš™οΈ Interaction Log", id="log_tab"):
287
  with gr.Accordion(label="Developer Interaction Log", open=False):
288
  output_interaction_log_markdown = gr.Markdown("Log will appear here...")
 
295
  text_model_dropdown, image_provider_dropdown,
296
  narrative_length_dropdown, image_quality_dropdown
297
  ],
298
+ outputs=[ # This list should match the components updated by the *final return* or *last yield*
299
  story_state_output,
300
  output_gallery,
301
  output_latest_scene_image,
302
  output_latest_scene_narrative,
303
  output_status_bar,
304
  output_interaction_log_markdown
305
+ # The buttons `engage_button`, `surprise_button` are updated via yield dicts,
306
+ # so they don't strictly need to be in this `outputs` list if the last yield
307
+ # doesn't include them AND the function has a specific `return` for these outputs.
308
+ # However, for robustness, if a yield dict is the last thing the generator does,
309
+ # make sure its keys cover these.
310
  ]
311
  )
312
  clear_story_button.click(
 
324
  inputs=[],
325
  outputs=[scene_prompt_input, image_style_input, artist_style_input]
326
  )
327
+ gr.Examples( # ... (Examples as before)
328
+ examples=[["A lone traveler...", "Sci-Fi Western", "Moebius", "greenery"]],
329
+ inputs=[scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input],
 
 
 
 
 
 
330
  label="🌌 Example Universes to Weave 🌌",
331
  )
332
+ 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>")
333
 
334
  # --- Entry Point ---
335
  if __name__ == "__main__":
336
+ # ... (Startup print messages as before)
337
+ print("="*80); print("✨ StoryVerse Omegaβ„’ Launching... ✨")
338
+ print(f" Gemini Text Ready: {GEMINI_TEXT_IS_READY}"); print(f" HF Text Ready: {HF_TEXT_IS_READY}")
339
+ print(f" Stability AI Ready: {STABILITY_API_IS_READY}"); print(f" DALL-E Ready: {OPENAI_DALLE_IS_READY}")
340
+ 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.")
341
+ print(f" Default Text Model: {UI_DEFAULT_TEXT_MODEL_KEY}"); print(f" Default Image Provider: {UI_DEFAULT_IMAGE_PROVIDER_KEY}")
342
  print("="*80)
 
 
 
 
 
 
 
 
 
 
 
343
  story_weaver_demo.launch(debug=True, server_name="0.0.0.0", share=False)