mgbam commited on
Commit
d7896b6
·
verified ·
1 Parent(s): 6bf2bd9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -95
app.py CHANGED
@@ -26,7 +26,6 @@ STABILITY_API_IS_READY = STABILITY_API_CONFIGURED
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,16 +56,51 @@ else:
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
@@ -88,20 +122,23 @@ def add_scene_to_story_orchestrator(
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,10 +147,11 @@ def add_scene_to_story_orchestrator(
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,20 +161,20 @@ def add_scene_to_story_orchestrator(
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,13 +184,12 @@ def add_scene_to_story_orchestrator(
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,103 +202,120 @@ def add_scene_to_story_orchestrator(
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,20 +323,24 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
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,18 +353,13 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
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,20 +377,31 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
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)
 
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
  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
 
122
 
123
  log_accumulator = [f"**🚀 Scene {current_story_obj.current_scene_number + 1} - {time.strftime('%H:%M:%S')}**"]
124
 
125
+ # Initialize placeholders for the final return tuple values
126
+ ret_story_state = current_story_obj
127
+ ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
128
+ ret_latest_image = None
129
+ ret_latest_narrative_str = "## Processing...\nNarrative generation in progress."
130
+ ret_status_bar_html = "<p class='processing_text status_text'>Processing...</p>"
131
+ ret_log_str = "\n".join(log_accumulator)
132
+
133
+ # Initial UI update by yielding a dictionary mapping component variables to their new configurations
134
+ yield {
135
  output_status_bar: gr.HTML(value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
136
  output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals..."), visible=True),
137
  output_latest_scene_narrative: gr.Markdown(value=" Musing narrative...", visible=True),
138
  engage_button: gr.Button(interactive=False),
139
  surprise_button: gr.Button(interactive=False),
140
+ output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator))
 
 
 
141
  }
 
142
 
143
  try:
144
  if not scene_prompt_text.strip():
 
147
  # --- 1. Generate Narrative Text ---
148
  progress(0.1, desc="✍️ Crafting narrative...")
149
  narrative_text_generated = f"Narrative Error: Init failed."
 
150
  text_model_info = TEXT_MODELS.get(text_model_key)
151
  if text_model_info and text_model_info["type"] != "none":
152
+ system_p = get_narrative_system_prompt("default")
153
+ prev_narrative = current_story_obj.get_last_scene_narrative()
154
+ user_p = format_narrative_user_prompt(scene_prompt_text, prev_narrative)
155
  log_accumulator.append(f" Narrative: Using {text_model_key} ({text_model_info['id']}). Length: {narrative_length}")
156
  text_response = None
157
  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)
 
161
  else: log_accumulator.append(f" Narrative: FAILED - No response from {text_model_key}.")
162
  else: narrative_text_generated = "**Narrative Error:** Text model unavailable."; log_accumulator.append(f" Narrative: FAILED - Model '{text_model_key}' unavailable.")
163
 
164
+ ret_latest_narrative_str = f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}"
165
+ yield { output_latest_scene_narrative: gr.Markdown(value=ret_latest_narrative_str),
166
+ output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
167
 
168
  # --- 2. Generate Image ---
169
  progress(0.5, desc="🎨 Conjuring visuals...")
170
  image_generated_pil = None
171
  image_generation_error_message = None
 
172
  selected_image_provider_type = IMAGE_PROVIDERS.get(image_provider_key)
173
  image_content_prompt_for_gen = narrative_text_generated if narrative_text_generated and "Error" not in narrative_text_generated else scene_prompt_text
174
+ quality_keyword = "ultra detailed, intricate, masterpiece, " if image_quality == "High Detail" else ("concept sketch, line art, " if image_quality == "Sketch Concept" else "")
175
  full_image_prompt = format_image_generation_prompt(quality_keyword + image_content_prompt_for_gen[:350], image_style_dropdown, artist_style_text)
176
  log_accumulator.append(f" Image: Using {image_provider_key}. Style: {image_style_dropdown}. Artist: {artist_style_text or 'N/A'}.")
177
+
178
  if selected_image_provider_type and selected_image_provider_type != "none":
179
  image_response = None
180
  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)
 
184
  else: image_generation_error_message = f"**Image Error:** No response from {image_provider_key}."; log_accumulator.append(f" Image: FAILED - No response.")
185
  else: image_generation_error_message = "**Image Error:** Image provider unavailable."; log_accumulator.append(f" Image: FAILED - Provider '{image_provider_key}' unavailable.")
186
 
187
+ ret_latest_image = image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010")
188
+ yield { output_latest_scene_image: gr.Image(value=ret_latest_image),
189
+ output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
190
 
191
  # --- 3. Add Scene to Story Object ---
192
  final_scene_error = None
 
193
  if image_generation_error_message and "**Narrative Error**" in narrative_text_generated : final_scene_error = f"{narrative_text_generated}\n{image_generation_error_message}"
194
  elif "**Narrative Error**" in narrative_text_generated: final_scene_error = narrative_text_generated
195
  elif image_generation_error_message: final_scene_error = image_generation_error_message
 
202
  image_provider=image_provider_key if selected_image_provider_type != "none" else "N/A",
203
  error_message=final_scene_error
204
  )
205
+ ret_story_state = current_story_obj
206
+ log_accumulator.append(f" Scene {current_story_obj.current_scene_number} processed and added.")
207
 
208
+ # --- 4. Prepare Final Values for Return Tuple ---
209
+ ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
210
+ _ , latest_narr_for_display_final_str_temp = current_story_obj.get_latest_scene_details_for_display()
211
+ ret_latest_narrative_str = latest_narr_for_display_final_str_temp
212
 
213
+ ret_status_bar_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>"
 
214
 
215
  progress(1.0, desc="Scene Complete!")
216
 
217
  except ValueError as ve:
218
  log_accumulator.append(f"\n**INPUT/CONFIG ERROR:** {ve}")
219
+ ret_status_bar_html = f"<p class='error_text status_text'>❌ CONFIGURATION ERROR: {ve}</p>"
220
+ ret_latest_narrative_str = f"## Error\n{ve}"
221
  except Exception as e:
222
  log_accumulator.append(f"\n**UNEXPECTED RUNTIME ERROR:** {type(e).__name__} - {e}\n{traceback.format_exc()}")
223
+ ret_status_bar_html = f"<p class='error_text status_text'>❌ UNEXPECTED ERROR: {type(e).__name__}. Check logs.</p>"
224
+ ret_latest_narrative_str = f"## Unexpected Error\n{type(e).__name__}: {e}\nSee log for details."
225
  finally:
226
  current_total_time = time.time() - start_time
227
  log_accumulator.append(f" Cycle ended at {time.strftime('%H:%M:%S')}. Total time: {current_total_time:.2f}s")
228
+ ret_log_str = "\n".join(log_accumulator)
 
 
229
 
230
+ # This final yield updates button states and the log just before the function returns.
231
+ # It does NOT provide values for the main `outputs` list of the click handler.
232
+ yield {
233
+ engage_button: gr.Button(interactive=True),
234
+ surprise_button: gr.Button(interactive=True),
235
+ output_interaction_log_markdown: gr.Markdown(value=ret_log_str) # Final log update via yield
236
+ }
237
 
238
+ # This `return` statement's tuple structure and order must match the `outputs` list
239
+ # of the `engage_button.click()` method.
240
+ return (
241
+ ret_story_state,
242
+ ret_gallery,
243
+ ret_latest_image,
244
+ gr.Markdown(value=ret_latest_narrative_str),
245
+ gr.HTML(value=ret_status_bar_html),
246
+ gr.Markdown(value=ret_log_str) # Log is also part of final return
247
+ )
248
 
249
 
250
  def clear_story_state_ui_wrapper():
251
+ new_story = Story()
252
+ placeholder_img = create_placeholder_image("Your StoryVerse is a blank canvas...", color="#1A1A2E", text_color="#A0A0C0")
253
+ cleared_gallery = [(placeholder_img, "Your StoryVerse is new and untold...")]
254
+ 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!"
255
+ status_msg = "<p class='processing_text status_text'>📜 Story Cleared. A fresh canvas awaits your imagination!</p>"
256
+ return (new_story, cleared_gallery, None, gr.Markdown(value=initial_narrative), gr.HTML(value=status_msg), "Log Cleared. Ready for a new adventure!", "")
257
 
258
  def surprise_me_func():
259
+ themes = ["Cosmic Horror", "Solarpunk Utopia", "Mythic Fantasy", "Noir Detective", "Silent Film Comedy", "Deep Sea Exploration", "Prehistoric Survival"]
260
+ 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"]
261
+ 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"]
262
+ prompt = f"A protagonist {random.choice(actions)} {random.choice(settings)}. The overall theme is {random.choice(themes)}."
263
+ style = random.choice(list(STYLE_PRESETS.keys()))
264
+ artist = random.choice(["H.R. Giger", "Moebius", "Eyvind Earle", " Remedios Varo", "Alphonse Mucha", ""]*2)
265
+ return prompt, style, artist
266
 
267
  # --- Gradio UI Definition ---
268
+ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨ - AI Story & World Weaver") as story_weaver_demo:
269
+ # --- Define Python variables for UI components that need to be updated by `yield` or `return` ---
270
+ # State
271
  story_state_output = gr.State(Story())
272
+
273
+ # Input Column (some inputs are also outputs for clear/surprise)
274
  scene_prompt_input = gr.Textbox()
275
  image_style_input = gr.Dropdown()
276
  artist_style_input = gr.Textbox()
277
+
278
+ # Output Column (and status bar from input column)
 
 
 
 
279
  output_latest_scene_image = gr.Image()
280
  output_latest_scene_narrative = gr.Markdown()
281
+ output_gallery = gr.Gallery()
282
  output_status_bar = gr.HTML()
283
  output_interaction_log_markdown = gr.Markdown()
284
+
285
+ # Buttons (interactivity updated by yield)
286
  engage_button = gr.Button()
287
  surprise_button = gr.Button()
288
+ # clear_story_button is not directly updated by the main orchestrator's yield typically
289
 
290
+ # --- Layout the UI ---
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, Captain Eva pilots her damaged starfighter towards a colossal, ringed gas giant. Alarms blare. 'Just a little further,' she mutters, gripping the controls.")
310
+
311
  with gr.Row(elem_classes=["compact-row"]):
312
  with gr.Column(scale=2):
313
  image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style Preset")
314
  with gr.Column(scale=2):
315
+ artist_style_input = gr.Textbox(label="Artistic Inspiration (Optional):", placeholder="e.g., Moebius, Zdzisław Beksiński")
316
+
317
+ 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)
318
+
319
  with gr.Accordion("⚙️ Advanced AI Configuration", open=False):
320
  with gr.Group():
321
  text_model_dropdown = gr.Dropdown(choices=list(TEXT_MODELS.keys()), value=UI_DEFAULT_TEXT_MODEL_KEY, label="Narrative AI Engine")
 
323
  with gr.Row():
324
  narrative_length_dropdown = gr.Dropdown(["Short (1 paragraph)", "Medium (2-3 paragraphs)", "Detailed (4+ paragraphs)"], value="Medium (2-3 paragraphs)", label="Narrative Detail")
325
  image_quality_dropdown = gr.Dropdown(["Standard", "High Detail", "Sketch Concept"], value="Standard", label="Image Detail/Style")
326
+
327
+ with gr.Row(elem_classes=["compact-row"], equal_height=True):
328
  engage_button = gr.Button("🌌 Weave This Scene!", variant="primary", scale=3, icon="✨")
329
  surprise_button = gr.Button("🎲 Surprise Me!", variant="secondary", scale=1, icon="🎁")
330
  clear_story_button = gr.Button("🗑️ New Story", variant="stop", scale=1, icon="♻️")
331
+
332
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave your first masterpiece!</p>")
333
 
334
  with gr.Column(scale=10, min_width=700):
335
  gr.Markdown("### 🖼️ **Your Evolving StoryVerse**", elem_classes="output-section-header")
336
  with gr.Tabs():
337
+ with gr.TabItem("🌠 Latest Scene", id="latest_scene_tab"):
338
  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"])
339
  output_latest_scene_narrative = gr.Markdown()
340
+
341
  with gr.TabItem("📚 Story Scroll", id="story_scroll_tab"):
342
  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"])
343
+
344
  with gr.TabItem("⚙️ Interaction Log", id="log_tab"):
345
  with gr.Accordion(label="Developer Interaction Log", open=False):
346
  output_interaction_log_markdown = gr.Markdown("Log will appear here...")
 
353
  text_model_dropdown, image_provider_dropdown,
354
  narrative_length_dropdown, image_quality_dropdown
355
  ],
356
+ outputs=[ # These components are updated by the FINAL return tuple of the orchestrator
357
  story_state_output,
358
  output_gallery,
359
  output_latest_scene_image,
360
  output_latest_scene_narrative,
361
  output_status_bar,
362
  output_interaction_log_markdown
 
 
 
 
 
363
  ]
364
  )
365
  clear_story_button.click(
 
377
  inputs=[],
378
  outputs=[scene_prompt_input, image_style_input, artist_style_input]
379
  )
380
+
381
+ gr.Examples(
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)