mgbam commited on
Commit
8e26c00
Β·
verified Β·
1 Parent(s): e6e5425

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -371
app.py CHANGED
@@ -9,7 +9,6 @@ import traceback
9
 
10
  # --- Core Logic Imports ---
11
  from core.llm_services import initialize_text_llms, is_gemini_text_ready, is_hf_text_ready, generate_text_gemini, generate_text_hf
12
- # MODIFIED Import for image_services to reflect DALL-E priority
13
  from core.image_services import initialize_image_llms, is_dalle_ready, is_hf_image_api_ready, generate_image_dalle, generate_image_hf_model, ImageGenResponse
14
  from core.story_engine import Story, Scene
15
  from prompts.narrative_prompts import get_narrative_system_prompt, format_narrative_user_prompt
@@ -23,113 +22,98 @@ initialize_image_llms()
23
  # --- Get API Readiness Status ---
24
  GEMINI_TEXT_IS_READY = is_gemini_text_ready()
25
  HF_TEXT_IS_READY = is_hf_text_ready()
26
- DALLE_IMAGE_IS_READY = is_dalle_ready() # For DALL-E
27
- HF_IMAGE_IS_READY = is_hf_image_api_ready() # For HF Image fallback
28
 
29
  # --- Application Configuration (Models, Defaults) ---
30
  TEXT_MODELS = {}
31
  UI_DEFAULT_TEXT_MODEL_KEY = None
32
- # ... (TEXT_MODELS and UI_DEFAULT_TEXT_MODEL_KEY population as before,Great prioritizing Gemini then HF) ...
33
  if GEMINI_TEXT_IS_READY:
34
- TEXT_MODELS["✨ Gemini! Now that `core/image_services.py` is updated to prioritize D 1.5 Flash (Narrate)"] = {"id": "gemini-1.5-flash-latest", "type": "gemini"}
35
- TEXT_MODELS["Legacy Gemini 1.0 Pro (ALL-E and use Hugging Face models as a fallback, we need to ensure `app.py` correctly reflects these changes inNarrate)"] = {"id": "gemini-1.0-pro-latest", "type": "gemini"}
36
  if HF_TEXT_IS_READY:
37
- TEXT_MODELS["Mistral 7 its configuration and logic.
38
-
39
- Here's the **full `app.py`** rewritten to align with the updated `image_services.py`.
40
-
41
- **Key changes in this `app.py`:**
42
 
43
- 1. **APIB (Narrate via HF)"] = {"id": "mistralai/Mistral-7B-Instruct-v0.2", "type": "hf_text"}
44
- TEXT_MODELS["Gemma 2B (Narrate via HF)"] = {"id": "google/gemma-2b-it", Readiness Checks:** Imports and uses `is_dalle_ready()` and `is_hf_image_api_ready()` from `image_services.py`.
45
- 2. **`IMAGE_PROVIDERS` Configuration:** Prioritizes DALL-E options if `DALLE_IMAGE_IS_READY` is true, then falls back to HF image models "type": "hf_text"}
46
  if TEXT_MODELS:
47
- if GEMINI_TEXT_IS_READY and "✨ Gemini 1.5 Flash (Narrate)" in TEXT_MODELS: UI_DEFAULT_TEXT_MODEL_KEY = "✨ Gemini 1.5 Flash (Narrate)"
48
- elif HF_TEXT_IS_READY and "Mistral 7B (Narrate via HF)" in TEXT_MODELS: UI_DEFAULT_TEXT_MODEL_KEY = "Mistral 7B (Narrate via HF)"
49
- else: UI if `HF_IMAGE_IS_READY` is true.
50
- 3. **Orchestrator Logic (`add_scene_to_story_orchestrator`):**
51
- * Correctly identifies the selected image provider type (DALL-E or specific HF model).
52
- * Calls `generate_image_dalle()`_DEFAULT_TEXT_MODEL_KEY = list(TEXT_MODELS.keys())[0]
53
  else:
54
- TEXT_MODELS["No Text Models Configured"] = {"id": "dummy_text_error", or `generate_image_hf_model()` accordingly.
55
- 4. **UI Labels and Info:** Updated to reflect the DALL-E and HF image options.
56
-
57
- ```python
58
- # storyverse_weaver/app.py
59
- import "type": "none"}
60
  UI_DEFAULT_TEXT_MODEL_KEY = "No Text Models Configured"
61
 
62
 
63
- IMAGE_PROVIDERS = {} # Reset and rebuild
64
  UI_DEFAULT_IMAGE_PROVIDER_KEY = None
65
-
66
- if DALLE_IMAGE_IS_READY: # Prioritize DALL-E
67
- IMAGE_PROVIDERS["πŸ–ΌοΈ OpenAI gradio as gr
68
- import os
69
- import time
70
- import json
71
- from PIL import Image, ImageDraw, ImageFont
72
- import random
73
- import traceback
74
-
75
- # --- Core Logic Imports ---
76
- from core.llm_services import initialize_text_llms, is_gemini_text_ready, is_hf_text_ready, generate_text_gemini, generate_text_hf
77
- # Updated import from image_services
78
- from core.image DALL-E 3"] = "dalle_3"
79
  IMAGE_PROVIDERS["πŸ–ΌοΈ OpenAI DALL-E 2 (Legacy)"] = "dalle_2"
80
  UI_DEFAULT_IMAGE_PROVIDER_KEY = "πŸ–ΌοΈ OpenAI DALL-E 3"
81
- elif HF_IMAGE_IS_READY: # Fallback to HF if DALL-E not ready
82
  IMAGE_PROVIDERS["🎑 HF - Stable Diffusion XL Base (Fallback)"] = "hf_sdxl_base"
83
- IMAGE_PROVIDERS["🎠 HF - Open_services import initialize_image_llms, is_dalle_ready, is_hf_image_api_ready, generate_image_dalle, generate_image_hf_model, ImageGenResponse
84
- from core.story_engine import Story, Scene
85
- from prompts.narrative_prompts import get_narrative_system_prompt, format_narrative_user_prompt
86
- from prompts.image_style_prompts import STYLE_PRESETS, COMMON_NEGATIVE_PROMPTS, format_image_generation_prompt
87
- from core.utils import basic_text_cleanup
88
-
89
- # --- Initialize Services ---
90
- initialize_text_llms()
91
- initialize_imageJourney (Fallback)"] = "hf_openjourney"
92
  IMAGE_PROVIDERS["🌌 HF - Stable Diffusion v1.5 (Fallback)"] = "hf_sd_1_5"
93
  UI_DEFAULT_IMAGE_PROVIDER_KEY = "🎑 HF - Stable Diffusion XL Base (Fallback)"
94
 
95
- if not IMAGE_PROVIDERS: # If neither is ready
96
  IMAGE_PROVIDERS["No Image Providers Configured"] = "none"
97
- _llms()
98
-
99
- # --- Get API Readiness Status ---
100
- GEMINI_TEXT_IS_READY = is_gemini_text_ready()
101
- HF_TEXT_IS_READY = is_hf_text_ready()
102
- DALLE_IMAGE_IS_READY = is_dalle_ready() # For DALL-E
103
- HF_IMAGE_IS_READY = is_hf_image_api_ready() # For HF image models
104
-
105
- # --- Application Configuration (Models, Defaults) ---
106
- TEXT_MODELS = {}
107
- UI_DEFAULT_TEXTUI_DEFAULT_IMAGE_PROVIDER_KEY = "No Image Providers Configured"
108
- elif not UI_DEFAULT_IMAGE_PROVIDER_KEY and IMAGE_PROVIDERS : # Should not happen if logic above is correct
109
  UI_DEFAULT_IMAGE_PROVIDER_KEY = list(IMAGE_PROVIDERS.keys())[0]
110
 
111
 
112
  # --- Gradio UI Theme and CSS ---
113
- # (omega_theme and omega_css definitions remain THE SAME as the last full app.py version)
114
- omega_theme = gr.themes.Base(font=[gr.themes.GoogleFont("Lexend Deca_MODEL_KEY = None
115
- # ... (TEXT_MODELS and UI_DEFAULT_TEXT_MODEL_KEY population logic remains the same as previous full app.py)
116
- if GEMINI_TEXT_IS_READY:
117
- TEXT_MODELS["✨ Gemini 1.5 Flash (Narrate)"] = {"id": "gemini-1.5-flash-latest", "type": "gemini"}
118
- TEXT_MODELS["Legacy Gemini 1.0 Pro (Narrate)"] = {"id": "gemini-1.0-pro-latest", "type": "gemini"}
119
- if HF_TEXT_IS_READY:
120
- TEXT_MODELS["Mistral 7B (Narrate via HF)"] = {"id": "mistralai/Mistral-7")], primary_hue=gr.themes.colors.purple).set(body_background_fill="#0F0F1A", block_background_fill="#1A1A2E", slider_color="#A020F0")
121
- omega_css = "body, .gradio-container { background-color: #0F0F1A !important; color: #D0D0E0 !important; } /* Paste your full omega_css here */"
122
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  # --- Helper: Placeholder Image Creation ---
125
  def create_placeholder_image(text="Processing...", size=(512, 512), color="#23233A", text_color="#E0E0FF"):
126
- # ... (Full implementation as before)
127
- img = Image.new('RGB', size,B-Instruct-v0.2", "type": "hf_text"}
128
- TEXT_MODELS["Gemma 2B (Narrate via HF)"] = {"id": "google/gemma-2b-it", "type": "hf_text"}
129
- if TEXT_MODELS:
130
- if GEMINI_TEXT_IS_READY and "✨ Gemini 1.5 Flash (Narrate)" in TEXT_MODELS: UI_DEFAULT_TEXT_MODEL_KEY = "✨ Gemini 1.5 Flash (Narrate)"
131
- elif HF_TEXT_IS_READY and "Mistral 7B (Narrate via HF)" in TEXT_MODELS: UI_DEFAULT_TEXT_MODEL_KEY = "Mistral 7B (Narrate via HF)"
132
- else: UI_DEFAULT_TEXT_MODEL_KEY = list(TEXT_MODELS.keys())[0 color=color); draw = ImageDraw.Draw(img)
133
  try: font_path = "arial.ttf" if os.path.exists("arial.ttf") else None
134
  except: font_path = None
135
  try: font = ImageFont.truetype(font_path, 40) if font_path else ImageFont.load_default()
@@ -138,86 +122,7 @@ if TEXT_MODELS:
138
  else: tw, th = draw.textsize(text, font=font)
139
  draw.text(((size[0]-tw)/2, (size[1]-th)/2), text, font=font, fill=text_color); return img
140
 
141
- # --- StoryVerse Weaver Orchestrator (MODIFIED image generation part) ---
142
- def add_scene_to_story_orchestrator(
143
- current_story_obj: Story, scene_prompt_text: str, image_style_dropdown: str, artist_style_text: str,
144
- negative_]
145
- else:
146
- TEXT_MODELS["No Text Models Configured"] = {"id": "dummy_text_error", "type": "none"}
147
- UI_DEFAULT_TEXT_MODEL_KEY = "No Text Models Configured"
148
-
149
-
150
- IMAGE_PROVIDERS = {} # Rebuild this based on new priorities
151
- UI_DEFAULT_IMAGE_PROVIDER_KEY = None
152
-
153
- if DALLE_IMAGE_IS_READY:
154
- IMAGE_PROVIDERS["πŸ–ΌοΈ OpenAI DALL-E 3"] = "dalle_3" # This key will map to model="dall-e-3"
155
- IMAGE_PROVIDERS["πŸ–ΌοΈ OpenAI DALL-E 2 (Legacy)"] = "dalle_2"
156
- UI_DEFAULT_IMAGE_PROVIDER_KEY = "πŸ–ΌοΈ OpenAI DALL-E 3"
157
-
158
- if HF_IMAGE_IS_READY:
159
- IMAGE_PROVIDERS["🎑 HF - Stable Diffusion XL Base"] = "hf_sdxl_base"
160
- IMAGE_PROVIDERS["🎠 HF - OpenJourney (Midjourney-like)"] = "hf_openjourney"
161
- IMAGE_PROVIDERSprompt_text: str, text_model_key: str, image_provider_key: str,
162
- narrative_length: str, image_quality: str,
163
- progress=gr.Progress(track_tqdm=True)
164
- ):
165
- start_time = time.time()
166
- if not current_story_obj: current_story_obj = Story()
167
- log_accumulator = [f"**πŸš€ Scene {current_story_obj.current_scene_number + 1} - {time.strftime('%H:%M:%S')}**"]
168
- # ... (Initialize ret_... placeholders as before) ...
169
- ret_story_state, ret_gallery, ret_latest_image, ret_latest_narrative_md_obj, ret_status_bar_html_obj, ret_log_md = \
170
- current_story_obj, current_story_obj.get_all_scenes_for_gallery_display(), None, gr.Markdown("Processing..."), gr.HTML("<p>Processing...</p>"), gr.Markdown("\n".join(log_accumulator))
171
-
172
- # Initial yield (buttons handled by .then() chain)
173
- yield {
174
- output_status_bar: gr.HTML(["🌌 HF - Stable Diffusion v1.5"] = "hf_sd_1_5"
175
- if not UI_DEFAULT_IMAGE_PROVIDER_KEY: # If DALL-E wasn't ready, default to HF
176
- UI_DEFAULT_IMAGE_PROVIDER_KEY = "🎑 HF - Stable Diffusion XL Base"
177
-
178
- if not IMAGE_PROVIDERS: # If neither DALL-E nor HF images are ready
179
- IMAGE_PROVIDERS["No Image Providers Configured"] = "none"
180
- UI_DEFAULT_IMAGE_PROVIDER_KEY = "No Image Providers Configured"
181
-
182
-
183
- # --- Gradio UI Theme and CSS ---
184
- # (omega_theme and omega_css definitions remain the same as the last full app.py)
185
- omega_theme = gr.themes.Base(font=[gr.themes.GoogleFont("Lexend Deca")], primary_hue=gr.themes.colors.purple).set(body_background_fill="#0F0F1A", block_background_fill="#1A1A2E", slider_color="#A020F0")
186
- omega_css = """ /* ... Paste your full omega_css string here ... */ """
187
-
188
- # --- Helper: Placeholder Image Creation ---
189
- def create_placeholder_image(text="Processing...", size=(512, 512), color="#23233A", text_color="#value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
190
- output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals...")),
191
- output_latest_scene_narrative: gr.Markdown(value=" Musing narrative..."),
192
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator))
193
- }
194
-
195
- try:
196
- if not scene_prompt_text.strip(): raise ValueError("Scene prompt cannot be empty!")
197
-
198
- # --- 1. Generate Narrative Text (No change here, uses Gemini or HF) ---
199
- progress(0.1, desc="✍️ Crafting narrative...")
200
- # ... (Full narrative generation logic - PASTE FROM PREVIOUS WORKING VERSION) ...
201
- # Example:
202
- narrative_text_generated = "Simulated Narrative: " + scene_prompt_text[:30] # Placeholder
203
- text_model_info = TEXT_MODELS.get(text_model_key) # Get full model info
204
- if text_model_info and text_model_info["type"] != "none":
205
- # ... call generate_text_gemini or generate_text_hf ...
206
- log_accumulator.append(f" Narrative: Using {text_model_key} (simulated).")
207
- else:
208
- narrative_text_generated = "**Narrative Error:** Text model not available."
209
- E0E0FF"):
210
- # ... (Full implementation as before) ...
211
- img = Image.new('RGB', size, color=color); draw = ImageDraw.Draw(img); #... (full implementation)
212
- try: font_path = "arial.ttf" if os.path.exists("arial.ttf") else None
213
- except: font_path = None
214
- try: font = ImageFont.truetype(font_path, 40) if font_path else ImageFont.load_default()
215
- except IOError: font = ImageFont.load_default()
216
- if hasattr(draw, 'textbbox'): bbox = draw.textbbox((0,0), text, font=font); tw, th = bbox[2]-bbox[0], bbox[3]-bbox[1]
217
- else: tw, th = draw.textsize(text, font=font)
218
- draw.text(((size[0]-tw)/2, (size[1]-th)/2), text, font=font, fill=text_color); return img
219
-
220
- # --- StoryVerse Weaver Orchestrator (MODIFIED image generation part) ---
221
  def add_scene_to_story_orchestrator(
222
  current_story_obj: Story, scene_prompt_text: str, image_style_dropdown: str, artist_style_text: str,
223
  negative_prompt_text: str, text_model_key: str, image_provider_key: str,
@@ -226,30 +131,17 @@ def add_scene_to_story_orchestrator(
226
  ):
227
  start_time = time.time()
228
  if not current_story_obj: current_story_obj = Story()
229
- log_accumulator = [f"**πŸš€ Scene {current_story_obj.current_scene_number + 1} - {log_accumulator.append(f" Narrative: FAILED - Model '{text_model_key}' not available.")
230
- ret_latest_narrative_str_content = f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}"
231
- ret_latest_narrative_md_obj = gr.Markdown(value=ret_latest_narrative_str_content)
232
- yield { output_latest_scene_narrative: ret_latest_narrative_md_obj,
233
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
234
-
235
-
236
- # --- 2. Generate Image (NOW PRIORITIZING DALL-E, THEN HF) ---
237
- progress(0.5, desc="🎨 Conjuring visuals...")
238
- image_generated_pil = None
239
- image_generation_error_message = None
240
- selected_image_provider_actual_type = IMAGE_PROVIDERS.get(image_provider_key) # e.g., "dalle_3", "hf_sdxl_base"
241
-
242
- image_content_prompt_for_gen = narrative_text_generated if narrative_text_generated and "Error" not in narrative_text_generated else scene_prompt_text
243
- quality_keyword = "detailed, high quality, cinematic lighting, " if image_quality == "High Detail" else ""
244
- full_image_prompt = format_image_generation_prompt(quality_keyword + image_content_prompt_for_gen[:350], image_style_dropdown, artist_style_text)
245
- log_accumulator.append(f" Image: Attempting with provider key '{image_provider_key}' (maps to type '{selected_image_provider_actual_type}'). Style: {image_style_dropdown}.")
246
-
247
- if selected_image_provider_actual_type and selected_image_provider_actualtime.strftime('%H:%M:%S')}**"]
248
- # ... (Initialize ret_... placeholders as before) ...
249
- ret_story_state, ret_gallery, ret_latest_image, ret_latest_narrative_md_obj, ret_status_bar_html_obj, ret_log_md = \
250
- current_story_obj, current_story_obj.get_all_scenes_for_gallery_display(), None, gr.Markdown("Processing..."), gr.HTML("<p>Processing...</p>"), gr.Markdown("\n".join(log_accumulator))
251
-
252
- # Initial yield for UI updates (buttons handled by .then() chain)
253
  yield {
254
  output_status_bar: gr.HTML(value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
255
  output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals...")),
@@ -258,174 +150,139 @@ def add_scene_to_story_orchestrator(
258
  }
259
 
260
  try:
261
- if not scene_prompt_text.strip(): raise ValueError("Scene prompt cannot be empty!")
 
262
 
263
- # --- 1. Generate Narrative Text (Gemini or HF fallback) ---
264
  progress(0.1, desc="✍️ Crafting narrative...")
265
- # ... (Full narrative generation logic from previous app.py) ...
266
- # ... (This part should be copied from your last working version, it already handles Gemini/HF choice) ...
267
- narrative_text_generated = "Simulated Narrative." # Placeholder
268
  text_model_info = TEXT_MODELS.get(text_model_key)
269
  if text_model_info and text_model_info["type"] != "none":
270
- 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)
271
- log_accumulator_type != "none":
272
- image_response = None
273
- if selected_image_provider_actual_type.startswith("dalle_"): # Catches "dalle_3", "dalle_2"
274
- if DALLE_IMAGE_IS_READY:
275
- dalle_model_version = "dall-e-3" if selected_image_provider_actual_type == "dalle_3" else "dall-e-2"
276
- dalle_size = "1024x1024" # DALL-E 3 supports more, DALL-E 2 has fixed
277
- if dalle_model_version == "dall-e-3" and image_quality == "High Detail": dalle_quality = "hd"
278
- else: dalle_quality = "standard"
279
- image_response = generate_image_dalle(full_image_prompt, model=dalle_model_version, size=dalle_size, quality=dalle_quality)
280
- else:
281
- image_generation_error_message = "**Image Error:** DALL-E selected but API not ready (check STORYVERSE_OPENAI_API_KEY)."
282
- elif selected_image_provider_actual_type.startswith("hf_"):
283
- if HF_IMAGE_IS_READY:
284
- hf_model_id_to_call = "stabilityai/stable-diffusion-xl-base-1.0" # Default HF
285
- img_width, img_height = 768, 768
286
- if selected_image_provider_actual_type == "hf_openjourney": hf_model_id_to_call = "prompthero/openjourney"; img_width,img_height = 512,512
287
- elif selected_image_provider_actual_type == "hf_sd_1_5": hf_model_id_to_call = "runwayml/stable-diffusion-v1-5"; img_width,img_height = 512,512
288
- image_response = generate_image_hf_model(full_image_prompt, model_id=hf_model_id_to_call, negative_prompt=negative_prompt_text or COMMON_NEGATIVE_PROMPTS, width=img_width, height=img.append(f" Narrative: Using {text_model_key} ({text_model_info['id']}).")
289
  text_response = None
290
  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)
291
  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)
292
  if text_response and text_response.success: narrative_text_generated = basic_text_cleanup(text_response.text); log_accumulator.append(f" Narrative: Success.")
293
  elif text_response: narrative_text_generated = f"**Narrative Error ({text_model_key}):** {text_response.error}"; log_accumulator.append(f" Narrative: FAILED - {text_response.error}")
294
  else: log_accumulator.append(f" Narrative: FAILED - No response from {text_model_key}.")
295
- else: narrative_text_generated = "**Narrative Error:** Text model unavailable."; log_accumulator.append(f" Narrative: FAILED - Model '{text_model_key}' unavailable.")
 
296
  ret_latest_narrative_str_content = f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}"
297
  ret_latest_narrative_md_obj = gr.Markdown(value=ret_latest_narrative_str_content)
298
- yield { output_latest_scene_narrative: ret_latest_narrative_md_obj, output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
299
-
300
 
301
- # --- 2. Generate Image (NOW USING DALL-E primary, HF fallback) ---
302
  progress(0.5, desc="🎨 Conjuring visuals...")
303
  image_generated_pil = None
304
  image_generation_error_message = None
305
- # `image_provider_key` is the UI display string, e.g., "πŸ–ΌοΈ OpenAI DALL-E 3"
306
- _height)
307
- else:
308
- image_generation_error_message = "**Image Error:** HF Image Model selected but API not ready (check STORYVERSE_HF_TOKEN)."
309
- else:
310
- image_generation_error_message = f"**Image Error:** Provider type '{selected_image_provider_actual_type}' is not handled."
311
-
312
- if image_response and image_response.success:
313
- image_generated_pil = image_response.image
314
- log_accumulator.append(f" Image: Success from {image_response.provider} (Model: {image_response.model_id_used}).")
315
- elif image_response:
316
- image_generation_error_message = f"**Image Error ({image_response.provider} - {image_response.model_id_used}):** {image_response.error}"
317
- log_accumulator.append(f" Image: FAILED - {image_response.error}")
318
- elif not image_generation_error_message: # If no response and no specific error set yet
319
- image_generation_error_message = f"**Image Error:** No response/unknown issue with {image_provider_key}."
320
-
321
- if not image_generated_pil and not image_generation_error_message: # If no provider matched or was ready
322
- image_generation_error_message = "**Image Error:** No valid image provider configured or selected for this request."
323
- log_accumulator.append(f" Image: FAILED - {image_generation_error_message}")
324
-
325
- ret_latest_image = image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010")
326
- yield { output_latest_scene_image: gr.Image(value=ret_latest_image),
327
- output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
328
-
329
- # --- 3. Add Scene to Story Object & 4. Prepare Final Return Values ---
330
- # ... (This part remains largely the same as the previous full app.py) ...
331
- final_scene_error=None; # ... (set based on narrative/image errors) ...
332
- if image_generation_error_message and "**Narrative Error**" in narrative_text_generated : final_scene_error = f"{narrative_text_generated}\n{image_generation_error_message}"
333
- elif "**Narrative Error**" in narrative_text_generated: final_scene_error = narrative_text_generated
334
- elif image_generation_error_message: final_scene_error = image_generation_error_message
335
- current_story_obj.add_scene_from_elements(user_prompt=scene_prompt_text # `selected_image_provider_type` is the internal type, e.g., "dalle_3"
336
- selected_image_provider_type = IMAGE_PROVIDERS.get(image_provider_key)
337
 
338
  image_content_prompt_for_gen = narrative_text_generated if narrative_text_generated and "Error" not in narrative_text_generated else scene_prompt_text
339
- quality_keyword = "detailed, high quality, vivid colors, " if image_quality == "High Detail" else ""
340
  full_image_prompt = format_image_generation_prompt(quality_keyword + image_content_prompt_for_gen[:350], image_style_dropdown, artist_style_text)
341
- log_accumulator.append(f" Image: Attempting with provider key '{image_provider_key}' (maps to type '{selected_image_provider_type}'). Style: {image_style_dropdown}.")
342
 
343
  if selected_image_provider_type and selected_image_provider_type != "none":
344
  image_response = None
345
- if selected_image_provider_type == "dalle_3":
346
  if DALLE_IMAGE_IS_READY:
347
- image_response = generate_image_dalle(full_image_prompt, model="dall-e-3", quality="hd" if image_quality=="High Detail" else "standard")
348
- else: image_generation_error_message = "**Image Error:** DALL-E 3 selected but API not ready (check STORYVERSE_OPENAI_API_KEY)."
349
- elif selected_image_provider_type == "dalle_2":
350
- if DALLE_IMAGE_IS_READY:
351
- image_response = generate_image_dalle(full_image_prompt, model="dall-e-2", size="1024x1024")
352
- else: image_generation_error_message = "**Image Error:** DALL-E 2 selected but API not ready."
353
- # Fallback to HF models
354
  elif selected_image_provider_type.startswith("hf_"):
355
  if HF_IMAGE_IS_READY:
356
- hf_model_id_to_call = "stabilityai/stable-diffusion-xl-base-1.0" # Default HF
357
- img_width, img_height = 768, 768
358
  if selected_image_provider_type == "hf_openjourney": hf_model_id_to_call = "prompthero/openjourney"; img_width,img_height = 512,512
359
  elif selected_image_provider_type == "hf_sd_1_5": hf_model_id_to_call = "runwayml/stable-diffusion-v1-5"; img_width,img_height = 512,512
360
  image_response = generate_image_hf_model(full_image_prompt, model_id=hf_model_id_to_call, negative_prompt=negative_prompt_text or COMMON_NEGATIVE_PROMPTS, width=img_width, height=img_height)
361
- else: image_generation_error_message = "**Image Error:** HF Image Model selected but API not ready (check STORY, narrative_text=narrative_text_generated, image=image_generated_pil, image_style_prompt=f"{image_style_dropdown} by {artist_style_text}", image_provider=image_provider_key, error_message=final_scene_error)
362
- ret_story_state = current_story_obj; log_accumulator.append(f" Scene {current_story_obj.current_scene_number} processed.")
363
- ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
364
- _ , latest_narr_for_display_final_str_temp = current_story_obj.get_latest_scene_details_for_display()
365
- ret_latest_narrative_md_obj = gr.Markdown(value=latest_narr_for_display_final_str_temp)
366
- status_html_str_temp = f"<p class='error_text'>Scene added with errors.</p>" if final_scene_error else f"<p class='success_text'>🌌 Scene woven!</p>"
367
- ret_status_bar_html_obj = gr.HTML(value=status_html_str_temp)
368
- progress(1.0, desc="Scene Complete!")
369
-
370
-
371
- except ValueError as ve: # ... (Error handling as before) ...
372
- log_accumulator.append(f"\n**INPUT ERROR:** {ve}"); ret_status_bar_html_obj = gr.HTML(f"<p class='error_text'>ERROR: {ve}</p>"); ret_latest_narrative_md_obj = gr.Markdown(f"## Error\n{ve}")
373
- except Exception as e: # ... (Error handling as before) ...
374
- log_accumulator.append(f"\n**RUNTIME ERROR:** {e}\n{traceback.format_exc()}"); ret_status_bar_html_obj = gr.HTML(f"<p class='error_text'>UNEXPECTED ERROR: {e}</p>"); ret_latest_narrative_md_obj = gr.Markdown(f"## Unexpected Error\n{e}")
375
-
376
- current_total_time = time.time() - start_time
377
- log_accumulator.append(f" Cycle ended. Total time: {current_total_time:.2f}s")
378
- ret_log_md = gr.Markdown(value="\n".join(log_accumulator))
379
-
380
- return (ret_story_state, ret_gallery, ret_latest_image, ret_latest_narrative_md_obj, ret_status_bar_html_obj, ret_log_md)
381
-
382
- # --- clear_story_state_ui_wrapper, surprise_me_func, disable_buttons_for_processing, enable_buttons_after_processing ---
383
- # (These functions remain IDENTICAL to the ones in the last full app.py that fixed the ValueError)
384
- def clear_story_state_ui_wrapper(): new_story=Story(); ph_img=create_placeholder_image("Blank..."); return(new_story,[(ph_img,"New...")],None,gr.Markdown("## Cleared"),gr.HTML("<p>Cleared.</p>"),"Log Cleared","")
385
- def surprise_me_func(): themes = ["Cosmic Horror", "Solarpunk Utopia"]; actions = ["unearths an artifact", "negotiates"]; settings = ["on a rogue planet", "in a city in a tree"]; prompt = f"A protagonist {random.choice(actions)} {random.choice(settings)}. Theme: {random.choice(themes)}."; style = random.choice(list(STYLE_PRESETS.keys())); artist = random.choice(["H.R. Giger", "Moebius",VERSE_HF_TOKEN)."
386
  else: image_generation_error_message = f"**Image Error:** Provider type '{selected_image_provider_type}' not handled."
387
 
388
  if image_response and image_response.success: image_generated_pil = image_response.image; log_accumulator.append(f" Image: Success from {image_response.provider} (Model: {image_response.model_id_used}).")
389
  elif image_response: image_generation_error_message = f"**Image Error ({image_response.provider} - {image_response.model_id_used}):** {image_response.error}"; log_accumulator.append(f" Image: FAILED - {image_response.error}")
390
- elif not image_generation_error_message: image_generation_error_message = f"**Image Error:** No response/unknown issue with {image_provider_key}."; log_accumulator.append(f" Image: FAILED - No response object.")
391
 
392
  if not image_generated_pil and not image_generation_error_message:
393
- image_generation_error_message = "**Image Error:** No valid image provider configured or selected for the chosen option."
394
  log_accumulator.append(f" Image: FAILED - {image_generation_error_message}")
395
 
396
  ret_latest_image = image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010")
397
  yield { output_latest_scene_image: gr.Image(value=ret_latest_image),
398
  output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
399
 
400
- # --- 3. Add Scene to Story Object & 4. Prepare Final Return Values ---
401
- # ... (This part remains largely the same as the previous full app.py) ...
402
- final_scene_error=None; # ... (set based on narrative/image errors) ...
403
- current_story_obj.add_scene_from_elements(user_prompt=scene_prompt_text, narrative_text=narrative_text_generated, image=image_generated_pil, image_style_prompt=f"{image_style_dropdown} by {artist_style_text}", image_provider=image_provider_key, error_message=final_scene_error)
404
- ret_story_state = current_story_obj; log_accumulator.append(f" Scene {current_story_obj.current_scene_number} processed.")
 
 
 
 
 
 
 
 
 
 
 
 
 
405
  ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
406
  _ , latest_narr_for_display_final_str_temp = current_story_obj.get_latest_scene_details_for_display()
407
  ret_latest_narrative_md_obj = gr.Markdown(value=latest_narr_for_display_final_str_temp)
408
- status_html_str_temp = f"<p class='error_text'>Scene added with errors.</p>" if final_scene_error else f"<p class='success_text'>🌌 Scene woven!</p>"
 
409
  ret_status_bar_html_obj = gr.HTML(value=status_html_str_temp)
 
410
  progress(1.0, desc="Scene Complete!")
411
 
412
- except ValueError as ve: # ... (Error handling as before) ...
413
- log_accumulator.append(f"\n**INPUT ERROR:** {ve}"); ret_status_bar_html_obj = gr.HTML(f"<p class='error_text'>ERROR: {ve}</p>"); ret_latest_narrative_md_obj = gr.Markdown(f"## Error\n{ve}")
414
- except Exception as e: # ... (Error handling as before) ...
415
- log_accumulator.append(f"\n**RUNTIME ERROR:** {e}\n{traceback.format_exc()}"); ret_status_bar_html_obj = gr.HTML(f"<p class='error_text'>UNEXPECTED ERROR: {e}</p>"); ret_latest_narrative_md_obj = gr.Markdown(f"## Unexpected Error\n{e}")
416
- ""]*2); return prompt, style, artist
417
- def disable_buttons_for_processing(): return gr.Button(interactive=False), gr.Button(interactive=False)
418
- def enable_buttons_after_processing(): return gr.Button(interactive=True), gr.Button(interactive=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419
 
 
 
420
 
421
  # --- Gradio UI Definition ---
422
  with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨") as story_weaver_demo:
423
  story_state_output = gr.State(Story())
424
- # ... (Full UI layout from the "app.py in full with update" response where NameError for create_placeholder was fixed)
425
- # ... (This includes defining all component variables like scene_prompt_input, output_gallery, engage_button etc. IN THE LAYOUT)
426
- # Key change: Update the image_provider_dropdown choices and default value.
427
  gr.Markdown("<div align='center'><h1>✨ StoryVerse Omega ✨</h1>\n<h3>Craft Immersive Multimodal Worlds with AI</h3></div>")
428
- gr.HTML("<div class='important-note'><strong>Welcome, Worldsmith!</strong> ... API keys (<code>STORYVERSE_...</code>) ...</div>")
 
429
  with gr.Accordion("πŸ”§ AI Services Status & Info", open=False):
430
  status_text_list = []; text_llm_ok = (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY); image_gen_ok = (DALLE_IMAGE_IS_READY or HF_IMAGE_IS_READY)
431
  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>")
@@ -441,98 +298,64 @@ with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨
441
  gr.Markdown("### πŸ’‘ **Craft Your Scene**", elem_classes="input-section-header")
442
  with gr.Group(): scene_prompt_input = gr.Textbox(lines=7, label="Scene Vision:", placeholder="e.g., Amidst swirling cosmic dust...")
443
  with gr.Row(elem_classes=["compact-row"]):
444
- with gr.Column(scale=2): image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style Preset", allow_custom_value=True)
445
  with gr.Column(scale=2): artist_style_input = gr.Textbox(label="Artistic Inspiration (Optional):", placeholder="e.g., Moebius...")
446
  negative_prompt_input = gr.Textbox(lines=2, label="Exclude from Image:", value=COMMON_NEGATIVE_PROMPTS)
447
  with gr.Accordion("βš™οΈ Advanced AI Configuration", open=False):
448
  with gr.Group():
449
  text_model_dropdown = gr.Dropdown(choices=list(TEXT_MODELS.keys()), value=UI_DEFAULT_TEXT_MODEL_KEY, label="Narrative AI Engine")
450
- image_provider_dropdown = gr.Dropdown(choices=list(IMAGE_PROVIDERS.keys()), value=UI_DEFAULT_IMAGE_PROVIDER_KEY, label="Visual AI Engine (DALL-E/HF)") # UPDATED LABEL
451
  with gr.Row():
452
- narrative_length_dropdown = gr.Dropdown(["Short", "Medium", "Detailed"], value="Medium", label="Narrative Detail")
453
- image_quality_dropdown = gr.Dropdown(["Standard", "High Detail", "Sketch"], value="Standard", label="Image Detail")
454
  with gr.Row(elem_classes=["compact-row"], equal_height=True):
455
- engage_button = gr.Button("🌌 Weave Scene!", variant="primary", scale=3
456
- current_total_time = time.time() - start_time
457
- log_accumulator.append(f" Cycle ended. Total time: {current_total_time:.2f}s")
458
- ret_log_md = gr.Markdown(value="\n".join(log_accumulator))
459
-
460
- return (ret_story_state, ret_gallery, ret_latest_image, ret_latest_narrative_md_obj, ret_status_bar_html_obj, ret_log_md)
461
-
462
- # --- clear_story_state_ui_wrapper, surprise_me_func, disable_buttons_for_processing, enable_buttons_after_processing ---
463
- # (These functions remain IDENTICAL to the ones in the last full app.py)
464
- def clear_story_state_ui_wrapper(): new_story=Story(); ph_img=create_placeholder_image("Blank..."); return(new_story,[(ph_img,"New...")],None,gr.Markdown("## Cleared"),gr.HTML("<p>Cleared.</p>"),"Log Cleared","")
465
- def surprise_me_func(): themes = ["Cosmic Horror", "Solarpunk Utopia"]; actions = ["unearths an artifact", "negotiates"]; settings = ["on a rogue planet", "in a city in a tree"]; prompt = f"A protagonist {random.choice(actions)} {random.choice(settings)}. Theme: {random.choice(themes)}."; style = random.choice(list(STYLE_PRESETS.keys())); artist = random.choice(["H.R. Giger", "Moebius", ""]*2); return prompt, style, artist
466
- def disable_buttons_for_processing(): return gr.Button(interactive=False), gr.Button(interactive=False)
467
- def enable_buttons_after_processing(): return gr.Button(interactive=True), gr.Button(interactive=True)
468
-
469
- # --- Gradio UI Definition ---
470
- with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨") as story_weaver_demo:
471
- # Define Python variables for UI components
472
- story_state_output = gr.State(Story())
473
- scene_prompt_input = gr.Textbox()
474
- image_style_input = gr.Dropdown()
475
- artist_style_input = gr.Textbox()
476
- negative_prompt_input = gr.Textbox()
477
- text_model_dropdown = gr.Dropdown()
478
- image_provider_dropdown = gr.Dropdown()
479
- narrative_length_dropdown = gr.Dropdown()
480
- image_quality_dropdown = gr.Dropdown()
481
- output_gallery = gr.Gallery()
482
- output_latest_scene_image = gr.Image()
483
- output_latest_scene_narrative = gr.Markdown()
484
- output_status_bar = gr.HTML()
485
- output_interaction_log_markdown = gr.Markdown()
486
- engage_button = gr.Button()
487
- surprise_button = gr.Button()
488
- clear_story_button = gr.Button()
489
-
490
- # Layout UI
491
- gr.Markdown("<div align='center'><h1>✨ StoryVerse Omega ✨</h1>\n<h3>Craft Immersive Multimodal Worlds with AI</h3></div>")
492
- gr.HTML("<div class='important-note'><strong>Welcome, Worldsmith!</strong> ... API keys ...</div>")
493
-
494
- with gr.Accordion("πŸ”§ AI Services Status & Info", open=False): # Updated status check
495
- status_text_list = []; text_llm_ok = (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY); image_gen_ok = (DALLE_IMAGE_IS_READY or HF_IMAGE_IS_READY)
496
- 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>")
497
- else:
498
- if text_llm_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Text Generation Ready.</p>")
499
- else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Text Generation NOT Ready.</p>")
500
- if image_gen_ok: status_text_list.append("<p style='color:#A7F3D0;'>βœ… Image Generation Ready.</p>")
501
- else: status_text_list.append("<p style='color:#FCD34D;'>⚠️ Image Generation NOT Ready.</p>")
502
- gr.HTML("".join(status_text_list))
503
-
504
- with gr.Row(equal_height=False, variant="panel"):
505
- with gr.Column(scale=7, min_width=450):
506
- gr.Markdown("### πŸ’‘ **Craft Your Scene**", elem_classes="input-section-header")
507
- with gr.Group(): scene_prompt_input = gr.Textbox(lines=7, label="Scene Vision:", placeholder="e.g., Amidst swirling cosmic dust...")
508
- with gr.Row(elem_classes=["compact-row"]):
509
- with gr.Column(scale=2): image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style", allow_custom_, icon="✨")
510
  surprise_button = gr.Button("🎲 Surprise!", variant="secondary", scale=1, icon="🎁")
511
  clear_story_button = gr.Button("πŸ—‘οΈ New", variant="stop", scale=1, icon="♻️")
512
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave!</p>")
513
  with gr.Column(scale=10, min_width=700):
514
  gr.Markdown("### πŸ–ΌοΈ **Your StoryVerse**", elem_classes="output-section-header")
515
  with gr.Tabs():
516
- with gr.TabItem("🌠 Latest Scene"): output_latest_scene_image = gr.Image(label="Latest Image", type="pil", interactive=False, height=512, show_label=False); output_latest_scene_narrative = gr.Markdown()
517
- with gr.TabItem("πŸ“š Story Scroll"): output_gallery = gr.Gallery(label="Story Scroll", show_label=False, columns=4, object_fit="cover", height=700, preview=True)
 
 
 
518
  with gr.TabItem("βš™οΈ Log"):
519
- with gr.Accordion("Interaction Log", open=False): output_interaction_log_markdown = gr.Markdown("Log...")
 
520
 
521
- # Event Handlers (same .then() chain as before)
522
  engage_button.click(fn=disable_buttons_for_processing, outputs=[engage_button, surprise_button], queue=False)\
523
- .then(fn=add_scene_to_story_orchestrator, inputs=[story_state_output, scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input, text_model_dropdown, image_provider_dropdown, narrative_length_dropdown, image_quality_dropdown], outputs=[story_state_output, output_gallery, output_latest_scene_image, output_latest_scene_narrative, output_status_bar, output_interaction_log_markdown])\
 
 
524
  .then(fn=enable_buttons_after_processing, outputs=[engage_button, surprise_button], queue=False)
525
- clear_story_button.click(fn=clear_story_state_ui_wrapper, outputs=[story_state_output, output_gallery, output_latest_scene_image, output_latest_scene_narrative, output_status_bar, output_interaction_log_markdown, scene_prompt_input])
526
- surprise_button.click(fn=surprise_me_func, outputs=[scene_prompt_input, image_style_input, artist_style_input])
527
- gr.Examples(examples=[["Traveler in desert...", "Sci-Fi Western", "Moebius", "greenery"]], inputs=[scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input], label="🌌 Examples 🌌")
528
- gr.HTML("<p style='text-align:center; font-size:0.9em; color:#8080A0;'>✨ StoryVerse Omegaβ„’ ✨</p>")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
529
 
530
  # --- Entry Point ---
531
  if __name__ == "__main__":
532
- print("="*80); print("✨ StoryVerse Omega (DALL-E/Gemini Focus) Launching... ✨")
533
  print(f" Gemini Text Ready: {GEMINI_TEXT_IS_READY}"); print(f" HF Text Ready: {HF_TEXT_IS_READY}")
534
  print(f" DALL-E Image Ready: {DALLE_IMAGE_IS_READY}"); print(f" HF Image API Ready: {HF_IMAGE_IS_READY}")
535
- if not (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY) or not (DALLE_IMAGE_IS_READY or HF_IMAGE_IS_READY): print(" πŸ”΄ WARNING: Not all services configured.")
 
536
  print(f" Default Text Model: {UI_DEFAULT_TEXT_MODEL_KEY}"); print(f" Default Image Provider: {UI_DEFAULT_IMAGE_PROVIDER_KEY}")
537
  print("="*80)
538
  story_weaver_demo.launch(debug=True, server_name="0.0.0.0", share=False)
 
9
 
10
  # --- Core Logic Imports ---
11
  from core.llm_services import initialize_text_llms, is_gemini_text_ready, is_hf_text_ready, generate_text_gemini, generate_text_hf
 
12
  from core.image_services import initialize_image_llms, is_dalle_ready, is_hf_image_api_ready, generate_image_dalle, generate_image_hf_model, ImageGenResponse
13
  from core.story_engine import Story, Scene
14
  from prompts.narrative_prompts import get_narrative_system_prompt, format_narrative_user_prompt
 
22
  # --- Get API Readiness Status ---
23
  GEMINI_TEXT_IS_READY = is_gemini_text_ready()
24
  HF_TEXT_IS_READY = is_hf_text_ready()
25
+ DALLE_IMAGE_IS_READY = is_dalle_ready()
26
+ HF_IMAGE_IS_READY = is_hf_image_api_ready()
27
 
28
  # --- Application Configuration (Models, Defaults) ---
29
  TEXT_MODELS = {}
30
  UI_DEFAULT_TEXT_MODEL_KEY = None
 
31
  if GEMINI_TEXT_IS_READY:
32
+ TEXT_MODELS["✨ Gemini 1.5 Flash (Narrate)"] = {"id": "gemini-1.5-flash-latest", "type": "gemini"}
33
+ TEXT_MODELS["Legacy Gemini 1.0 Pro (Narrate)"] = {"id": "gemini-1.0-pro-latest", "type": "gemini"}
34
  if HF_TEXT_IS_READY:
35
+ # CORRECTED LINE from SyntaxError:
36
+ TEXT_MODELS["Mistral 7B (Narrate via HF)"] = {"id": "mistralai/Mistral-7B-Instruct-v0.2", "type": "hf_text"}
37
+ TEXT_MODELS["Gemma 2B (Narrate via HF)"] = {"id": "google/gemma-2b-it", "type": "hf_text"}
 
 
38
 
 
 
 
39
  if TEXT_MODELS:
40
+ if GEMINI_TEXT_IS_READY and "✨ Gemini 1.5 Flash (Narrate)" in TEXT_MODELS:
41
+ UI_DEFAULT_TEXT_MODEL_KEY = "✨ Gemini 1.5 Flash (Narrate)"
42
+ elif HF_TEXT_IS_READY and "Mistral 7B (Narrate via HF)" in TEXT_MODELS:
43
+ UI_DEFAULT_TEXT_MODEL_KEY = "Mistral 7B (Narrate via HF)"
44
+ elif TEXT_MODELS: # Fallback to first available if preferred ones are not ready or not in list
45
+ UI_DEFAULT_TEXT_MODEL_KEY = list(TEXT_MODELS.keys())[0]
46
  else:
47
+ TEXT_MODELS["No Text Models Configured"] = {"id": "dummy_text_error", "type": "none"}
 
 
 
 
 
48
  UI_DEFAULT_TEXT_MODEL_KEY = "No Text Models Configured"
49
 
50
 
51
+ IMAGE_PROVIDERS = {}
52
  UI_DEFAULT_IMAGE_PROVIDER_KEY = None
53
+ if DALLE_IMAGE_IS_READY:
54
+ IMAGE_PROVIDERS["πŸ–ΌοΈ OpenAI DALL-E 3"] = "dalle_3"
 
 
 
 
 
 
 
 
 
 
 
 
55
  IMAGE_PROVIDERS["πŸ–ΌοΈ OpenAI DALL-E 2 (Legacy)"] = "dalle_2"
56
  UI_DEFAULT_IMAGE_PROVIDER_KEY = "πŸ–ΌοΈ OpenAI DALL-E 3"
57
+ elif HF_IMAGE_IS_READY:
58
  IMAGE_PROVIDERS["🎑 HF - Stable Diffusion XL Base (Fallback)"] = "hf_sdxl_base"
59
+ IMAGE_PROVIDERS["🎠 HF - OpenJourney (Fallback)"] = "hf_openjourney"
 
 
 
 
 
 
 
 
60
  IMAGE_PROVIDERS["🌌 HF - Stable Diffusion v1.5 (Fallback)"] = "hf_sd_1_5"
61
  UI_DEFAULT_IMAGE_PROVIDER_KEY = "🎑 HF - Stable Diffusion XL Base (Fallback)"
62
 
63
+ if not IMAGE_PROVIDERS:
64
  IMAGE_PROVIDERS["No Image Providers Configured"] = "none"
65
+ UI_DEFAULT_IMAGE_PROVIDER_KEY = "No Image Providers Configured"
66
+ elif not UI_DEFAULT_IMAGE_PROVIDER_KEY and IMAGE_PROVIDERS :
 
 
 
 
 
 
 
 
 
 
67
  UI_DEFAULT_IMAGE_PROVIDER_KEY = list(IMAGE_PROVIDERS.keys())[0]
68
 
69
 
70
  # --- Gradio UI Theme and CSS ---
71
+ omega_theme = gr.themes.Base(
72
+ font=[gr.themes.GoogleFont("Lexend Deca"), "ui-sans-serif", "system-ui", "sans-serif"],
73
+ primary_hue=gr.themes.colors.purple, secondary_hue=gr.themes.colors.pink, neutral_hue=gr.themes.colors.slate
74
+ ).set(
75
+ body_background_fill="#0F0F1A", block_background_fill="#1A1A2E", block_border_width="1px",
76
+ block_border_color="#2A2A4A", block_label_background_fill="#2A2A4A", input_background_fill="#2A2A4A",
77
+ input_border_color="#4A4A6A", button_primary_background_fill="linear-gradient(135deg, #7F00FF 0%, #E100FF 100%)",
78
+ button_primary_text_color="white", button_secondary_background_fill="#4A4A6A",
79
+ button_secondary_text_color="#E0E0FF", slider_color="#A020F0"
80
+ )
81
+ omega_css = """
82
+ body, .gradio-container { background-color: #0F0F1A !important; color: #D0D0E0 !important; }
83
+ .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;}
84
+ .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);}
85
+ .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;}
86
+ .gr-markdown h3 { color: #C080F0 !important; text-align: center; font-weight: 400; margin-bottom: 25px !important;}
87
+ .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;}
88
+ .output-section-header { font-size: 1.8em; font-weight: 600; color: #D0D0FF; margin-top: 15px; margin-bottom: 12px;}
89
+ .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;}
90
+ .gr-button { border-radius: 8px !important; font-weight: 500 !important; transition: all 0.2s ease-in-out !important;}
91
+ .gr-button-primary { padding-top: 10px !important; padding-bottom: 10px !important; }
92
+ .gr-button-primary:hover { transform: scale(1.03) translateY(-1px) !important; box-shadow: 0 8px 16px rgba(127,0,255,0.3) !important; }
93
+ .panel_image { border-radius: 12px !important; overflow: hidden; box-shadow: 0 6px 15px rgba(0,0,0,0.25) !important; background-color: #23233A;}
94
+ .panel_image img { max-height: 600px !important; }
95
+ .gallery_output { background-color: transparent !important; border: none !important; }
96
+ .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;}
97
+ .gallery_output .thumbnail-item:hover { transform: scale(1.05); }
98
+ .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;}
99
+ .error_text { background-color: #401010 !important; color: #FFB0B0 !important; border-color: #802020 !important; }
100
+ .success_text { background-color: #104010 !important; color: #B0FFB0 !important; border-color: #208020 !important;}
101
+ .processing_text { background-color: #102040 !important; color: #B0D0FF !important; border-color: #204080 !important;}
102
+ .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;}
103
+ .gr-tabitem { background-color: #1A1A2E !important; border-radius: 0 0 12px 12px !important; padding: 15px !important;}
104
+ .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;}
105
+ .gr-tab-button { color: #A0A0C0 !important; border-radius: 8px 8px 0 0 !important;}
106
+ .gr-accordion > .gr-block { border-top: 1px solid #2A2A4A !important; }
107
+ .gr-markdown code { background-color: #2A2A4A !important; color: #C0C0E0 !important; padding: 0.2em 0.5em; border-radius: 4px; }
108
+ .gr-markdown pre { background-color: #23233A !important; padding: 1em !important; border-radius: 6px !important; border: 1px solid #2A2A4A !important;}
109
+ .gr-markdown pre > code { padding: 0 !important; background-color: transparent !important; }
110
+ #surprise_button { background: linear-gradient(135deg, #ff7e5f 0%, #feb47b 100%) !important; font-weight:600 !important;}
111
+ #surprise_button:hover { transform: scale(1.03) translateY(-1px) !important; box-shadow: 0 8px 16px rgba(255,126,95,0.3) !important; }
112
+ """
113
 
114
  # --- Helper: Placeholder Image Creation ---
115
  def create_placeholder_image(text="Processing...", size=(512, 512), color="#23233A", text_color="#E0E0FF"):
116
+ img = Image.new('RGB', size, color=color); draw = ImageDraw.Draw(img)
 
 
 
 
 
 
117
  try: font_path = "arial.ttf" if os.path.exists("arial.ttf") else None
118
  except: font_path = None
119
  try: font = ImageFont.truetype(font_path, 40) if font_path else ImageFont.load_default()
 
122
  else: tw, th = draw.textsize(text, font=font)
123
  draw.text(((size[0]-tw)/2, (size[1]-th)/2), text, font=font, fill=text_color); return img
124
 
125
+ # --- StoryVerse Weaver Orchestrator ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  def add_scene_to_story_orchestrator(
127
  current_story_obj: Story, scene_prompt_text: str, image_style_dropdown: str, artist_style_text: str,
128
  negative_prompt_text: str, text_model_key: str, image_provider_key: str,
 
131
  ):
132
  start_time = time.time()
133
  if not current_story_obj: current_story_obj = Story()
134
+
135
+ log_accumulator = [f"**πŸš€ Scene {current_story_obj.current_scene_number + 1} - {time.strftime('%H:%M:%S')}**"]
136
+
137
+ ret_story_state = current_story_obj
138
+ ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
139
+ ret_latest_image = None
140
+ ret_latest_narrative_md_obj = gr.Markdown(value="## Processing...\nNarrative being woven...")
141
+ ret_status_bar_html_obj = gr.HTML(value="<p class='processing_text status_text'>Processing...</p>")
142
+ # ret_log_md will be built up
143
+
144
+ # Initial yield for UI updates (buttons disabled by .then() chain)
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  yield {
146
  output_status_bar: gr.HTML(value=f"<p class='processing_text status_text'>🌌 Weaving Scene {current_story_obj.current_scene_number + 1}...</p>"),
147
  output_latest_scene_image: gr.Image(value=create_placeholder_image("🎨 Conjuring visuals...")),
 
150
  }
151
 
152
  try:
153
+ if not scene_prompt_text.strip():
154
+ raise ValueError("Scene prompt cannot be empty!")
155
 
156
+ # --- 1. Generate Narrative Text ---
157
  progress(0.1, desc="✍️ Crafting narrative...")
158
+ narrative_text_generated = f"Narrative Error: Init failed."
 
 
159
  text_model_info = TEXT_MODELS.get(text_model_key)
160
  if text_model_info and text_model_info["type"] != "none":
161
+ system_p = get_narrative_system_prompt("default")
162
+ prev_narrative = current_story_obj.get_last_scene_narrative()
163
+ user_p = format_narrative_user_prompt(scene_prompt_text, prev_narrative)
164
+ log_accumulator.append(f" Narrative: Using {text_model_key} ({text_model_info['id']}). Length: {narrative_length}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  text_response = None
166
  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)
167
  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)
168
  if text_response and text_response.success: narrative_text_generated = basic_text_cleanup(text_response.text); log_accumulator.append(f" Narrative: Success.")
169
  elif text_response: narrative_text_generated = f"**Narrative Error ({text_model_key}):** {text_response.error}"; log_accumulator.append(f" Narrative: FAILED - {text_response.error}")
170
  else: log_accumulator.append(f" Narrative: FAILED - No response from {text_model_key}.")
171
+ else: narrative_text_generated = "**Narrative Error:** Selected text model not available or misconfigured."; log_accumulator.append(f" Narrative: FAILED - Model '{text_model_key}' unavailable.")
172
+
173
  ret_latest_narrative_str_content = f"## Scene Idea: {scene_prompt_text}\n\n{narrative_text_generated}"
174
  ret_latest_narrative_md_obj = gr.Markdown(value=ret_latest_narrative_str_content)
175
+ yield { output_latest_scene_narrative: ret_latest_narrative_md_obj,
176
+ output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
177
 
178
+ # --- 2. Generate Image ---
179
  progress(0.5, desc="🎨 Conjuring visuals...")
180
  image_generated_pil = None
181
  image_generation_error_message = None
182
+ selected_image_provider_key_from_ui = image_provider_key
183
+ selected_image_provider_type = IMAGE_PROVIDERS.get(selected_image_provider_key_from_ui)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
  image_content_prompt_for_gen = narrative_text_generated if narrative_text_generated and "Error" not in narrative_text_generated else scene_prompt_text
186
+ quality_keyword = "ultra detailed, intricate, masterpiece, " if image_quality == "High Detail" else ("concept sketch, line art, " if image_quality == "Sketch Concept" else "")
187
  full_image_prompt = format_image_generation_prompt(quality_keyword + image_content_prompt_for_gen[:350], image_style_dropdown, artist_style_text)
188
+ log_accumulator.append(f" Image: Attempting with provider key '{selected_image_provider_key_from_ui}' (maps to type '{selected_image_provider_type}'). Style: {image_style_dropdown}.")
189
 
190
  if selected_image_provider_type and selected_image_provider_type != "none":
191
  image_response = None
192
+ if selected_image_provider_type.startswith("dalle_"):
193
  if DALLE_IMAGE_IS_READY:
194
+ dalle_model_version = "dall-e-3" if selected_image_provider_type == "dalle_3" else "dall-e-2"
195
+ dalle_size = "1024x1024"
196
+ dalle_quality_param = "hd" if image_quality=="High Detail" and dalle_model_version == "dall-e-3" else "standard"
197
+ image_response = generate_image_dalle(full_image_prompt, model=dalle_model_version, size=dalle_size, quality=dalle_quality_param)
198
+ else: image_generation_error_message = "**Image Error:** DALL-E selected but API not ready."
 
 
199
  elif selected_image_provider_type.startswith("hf_"):
200
  if HF_IMAGE_IS_READY:
201
+ hf_model_id_to_call = "stabilityai/stable-diffusion-xl-base-1.0"; img_width, img_height = 768, 768
 
202
  if selected_image_provider_type == "hf_openjourney": hf_model_id_to_call = "prompthero/openjourney"; img_width,img_height = 512,512
203
  elif selected_image_provider_type == "hf_sd_1_5": hf_model_id_to_call = "runwayml/stable-diffusion-v1-5"; img_width,img_height = 512,512
204
  image_response = generate_image_hf_model(full_image_prompt, model_id=hf_model_id_to_call, negative_prompt=negative_prompt_text or COMMON_NEGATIVE_PROMPTS, width=img_width, height=img_height)
205
+ else: image_generation_error_message = "**Image Error:** HF Image Model selected but API not ready."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  else: image_generation_error_message = f"**Image Error:** Provider type '{selected_image_provider_type}' not handled."
207
 
208
  if image_response and image_response.success: image_generated_pil = image_response.image; log_accumulator.append(f" Image: Success from {image_response.provider} (Model: {image_response.model_id_used}).")
209
  elif image_response: image_generation_error_message = f"**Image Error ({image_response.provider} - {image_response.model_id_used}):** {image_response.error}"; log_accumulator.append(f" Image: FAILED - {image_response.error}")
210
+ elif not image_generation_error_message: image_generation_error_message = f"**Image Error:** No response with {image_provider_key}."
211
 
212
  if not image_generated_pil and not image_generation_error_message:
213
+ image_generation_error_message = "**Image Error:** No valid image provider configured or selected."
214
  log_accumulator.append(f" Image: FAILED - {image_generation_error_message}")
215
 
216
  ret_latest_image = image_generated_pil if image_generated_pil else create_placeholder_image("Image Gen Failed", color="#401010")
217
  yield { output_latest_scene_image: gr.Image(value=ret_latest_image),
218
  output_interaction_log_markdown: gr.Markdown(value="\n".join(log_accumulator)) }
219
 
220
+ # --- 3. Add Scene to Story Object ---
221
+ final_scene_error = None
222
+ if image_generation_error_message and "**Narrative Error**" in narrative_text_generated : final_scene_error = f"{narrative_text_generated}\n{image_generation_error_message}"
223
+ elif "**Narrative Error**" in narrative_text_generated: final_scene_error = narrative_text_generated
224
+ elif image_generation_error_message: final_scene_error = image_generation_error_message
225
+
226
+ current_story_obj.add_scene_from_elements(
227
+ user_prompt=scene_prompt_text,
228
+ narrative_text=narrative_text_generated if "**Narrative Error**" not in narrative_text_generated else "(Narrative gen failed)",
229
+ image=image_generated_pil,
230
+ image_style_prompt=f"{image_style_dropdown}{f', by {artist_style_text}' if artist_style_text and artist_style_text.strip() else ''}",
231
+ image_provider=selected_image_provider_key_from_ui,
232
+ error_message=final_scene_error
233
+ )
234
+ ret_story_state = current_story_obj
235
+ log_accumulator.append(f" Scene {current_story_obj.current_scene_number} processed and added.")
236
+
237
+ # --- 4. Prepare Final Values for Return Tuple ---
238
  ret_gallery = current_story_obj.get_all_scenes_for_gallery_display()
239
  _ , latest_narr_for_display_final_str_temp = current_story_obj.get_latest_scene_details_for_display()
240
  ret_latest_narrative_md_obj = gr.Markdown(value=latest_narr_for_display_final_str_temp)
241
+
242
+ status_html_str_temp = f"<p class='error_text status_text'>Scene {current_story_obj.current_scene_number} added with errors.</p>" if final_scene_error else f"<p class='success_text status_text'>🌌 Scene {current_story_obj.current_scene_number} woven!</p>"
243
  ret_status_bar_html_obj = gr.HTML(value=status_html_str_temp)
244
+
245
  progress(1.0, desc="Scene Complete!")
246
 
247
+ except ValueError as ve:
248
+ log_accumulator.append(f"\n**INPUT/CONFIG ERROR:** {ve}")
249
+ ret_status_bar_html_obj = gr.HTML(value=f"<p class='error_text status_text'>❌ CONFIGURATION ERROR: {ve}</p>")
250
+ ret_latest_narrative_md_obj = gr.Markdown(value=f"## Error\n{ve}")
251
+ except Exception as e:
252
+ log_accumulator.append(f"\n**UNEXPECTED RUNTIME ERROR:** {type(e).__name__} - {e}\n{traceback.format_exc()}")
253
+ ret_status_bar_html_obj = gr.HTML(value=f"<p class='error_text status_text'>❌ UNEXPECTED ERROR: {type(e).__name__}. Check logs.</p>")
254
+ ret_latest_narrative_md_obj = gr.Markdown(value=f"## Unexpected Error\n{type(e).__name__}: {e}\nSee log for details.")
255
+
256
+ current_total_time = time.time() - start_time
257
+ log_accumulator.append(f" Cycle ended at {time.strftime('%H:%M:%S')}. Total time: {current_total_time:.2f}s")
258
+ ret_log_md = gr.Markdown(value="\n".join(log_accumulator))
259
+
260
+ # This is the FINAL return. It must be a tuple matching the `outputs` list of engage_button.click()
261
+ return (
262
+ ret_story_state, ret_gallery, ret_latest_image,
263
+ ret_latest_narrative_md_obj, ret_status_bar_html_obj, ret_log_md
264
+ )
265
+
266
+ def clear_story_state_ui_wrapper():
267
+ new_story = Story(); ph_img = create_placeholder_image("Blank canvas...", color="#1A1A2E", text_color="#A0A0C0")
268
+ return (new_story, [(ph_img,"New StoryVerse...")], None, gr.Markdown("## ✨ New Story ✨"), gr.HTML("<p class='processing_text status_text'>πŸ“œ Story Cleared.</p>"), "Log Cleared.", "")
269
+
270
+ def surprise_me_func():
271
+ themes = ["Cosmic Horror", "Solarpunk Utopia", "Mythic Fantasy", "Noir Detective"]; actions = ["unearths an artifact", "negotiates"]; settings = ["on a rogue planet", "in a city in a tree"]; prompt = f"A protagonist {random.choice(actions)} {random.choice(settings)}. Theme: {random.choice(themes)}."; style = random.choice(list(STYLE_PRESETS.keys())); artist = random.choice(["H.R. Giger", "Moebius", ""]*2); return prompt, style, artist
272
+
273
+ def disable_buttons_for_processing():
274
+ return gr.Button(interactive=False), gr.Button(interactive=False)
275
 
276
+ def enable_buttons_after_processing():
277
+ return gr.Button(interactive=True), gr.Button(interactive=True)
278
 
279
  # --- Gradio UI Definition ---
280
  with gr.Blocks(theme=omega_theme, css=omega_css, title="✨ StoryVerse Omega ✨") as story_weaver_demo:
281
  story_state_output = gr.State(Story())
282
+
 
 
283
  gr.Markdown("<div align='center'><h1>✨ StoryVerse Omega ✨</h1>\n<h3>Craft Immersive Multimodal Worlds with AI</h3></div>")
284
+ 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>")
285
+
286
  with gr.Accordion("πŸ”§ AI Services Status & Info", open=False):
287
  status_text_list = []; text_llm_ok = (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY); image_gen_ok = (DALLE_IMAGE_IS_READY or HF_IMAGE_IS_READY)
288
  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
  gr.Markdown("### πŸ’‘ **Craft Your Scene**", elem_classes="input-section-header")
299
  with gr.Group(): scene_prompt_input = gr.Textbox(lines=7, label="Scene Vision:", placeholder="e.g., Amidst swirling cosmic dust...")
300
  with gr.Row(elem_classes=["compact-row"]):
301
+ with gr.Column(scale=2): image_style_input = gr.Dropdown(choices=["Default (Cinematic Realism)"] + sorted(list(STYLE_PRESETS.keys())), value="Default (Cinematic Realism)", label="Visual Style", allow_custom_value=True)
302
  with gr.Column(scale=2): artist_style_input = gr.Textbox(label="Artistic Inspiration (Optional):", placeholder="e.g., Moebius...")
303
  negative_prompt_input = gr.Textbox(lines=2, label="Exclude from Image:", value=COMMON_NEGATIVE_PROMPTS)
304
  with gr.Accordion("βš™οΈ Advanced AI Configuration", open=False):
305
  with gr.Group():
306
  text_model_dropdown = gr.Dropdown(choices=list(TEXT_MODELS.keys()), value=UI_DEFAULT_TEXT_MODEL_KEY, label="Narrative AI Engine")
307
+ image_provider_dropdown = gr.Dropdown(choices=list(IMAGE_PROVIDERS.keys()), value=UI_DEFAULT_IMAGE_PROVIDER_KEY, label="Visual AI Engine")
308
  with gr.Row():
309
+ narrative_length_dropdown = gr.Dropdown(["Short (1 paragraph)", "Medium (2-3 paragraphs)", "Detailed (4+ paragraphs)"], value="Medium (2-3 paragraphs)", label="Narrative Detail")
310
+ image_quality_dropdown = gr.Dropdown(["Standard", "High Detail", "Sketch Concept"], value="Standard", label="Image Detail/Style")
311
  with gr.Row(elem_classes=["compact-row"], equal_height=True):
312
+ engage_button = gr.Button("🌌 Weave Scene!", variant="primary", scale=3, icon="✨")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  surprise_button = gr.Button("🎲 Surprise!", variant="secondary", scale=1, icon="🎁")
314
  clear_story_button = gr.Button("πŸ—‘οΈ New", variant="stop", scale=1, icon="♻️")
315
  output_status_bar = gr.HTML(value="<p class='processing_text status_text'>Ready to weave!</p>")
316
  with gr.Column(scale=10, min_width=700):
317
  gr.Markdown("### πŸ–ΌοΈ **Your StoryVerse**", elem_classes="output-section-header")
318
  with gr.Tabs():
319
+ with gr.TabItem("🌠 Latest Scene"):
320
+ output_latest_scene_image = gr.Image(label="Latest Image", type="pil", interactive=False, height=512, show_label=False, show_download_button=True, elem_classes=["panel_image"])
321
+ output_latest_scene_narrative = gr.Markdown()
322
+ with gr.TabItem("πŸ“š Story Scroll"):
323
+ 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"])
324
  with gr.TabItem("βš™οΈ Log"):
325
+ with gr.Accordion("Interaction Log", open=False):
326
+ output_interaction_log_markdown = gr.Markdown("Log...")
327
 
 
328
  engage_button.click(fn=disable_buttons_for_processing, outputs=[engage_button, surprise_button], queue=False)\
329
+ .then(fn=add_scene_to_story_orchestrator,
330
+ inputs=[story_state_output, scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input, text_model_dropdown, image_provider_dropdown, narrative_length_dropdown, image_quality_dropdown],
331
+ outputs=[story_state_output, output_gallery, output_latest_scene_image, output_latest_scene_narrative, output_status_bar, output_interaction_log_markdown])\
332
  .then(fn=enable_buttons_after_processing, outputs=[engage_button, surprise_button], queue=False)
333
+
334
+ clear_story_button.click(fn=clear_story_state_ui_wrapper,
335
+ outputs=[story_state_output, output_gallery, output_latest_scene_image, output_latest_scene_narrative, output_status_bar, output_interaction_log_markdown, scene_prompt_input])
336
+
337
+ surprise_button.click(fn=surprise_me_func,
338
+ outputs=[scene_prompt_input, image_style_input, artist_style_input])
339
+
340
+ gr.Examples(
341
+ examples=[
342
+ ["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"],
343
+ ["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"],
344
+ ["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"],
345
+ ["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"]
346
+ ],
347
+ inputs=[scene_prompt_input, image_style_input, artist_style_input, negative_prompt_input],
348
+ label="🌌 Example Universes to Weave 🌌",
349
+ )
350
+ 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>")
351
 
352
  # --- Entry Point ---
353
  if __name__ == "__main__":
354
+ print("="*80); print("✨ StoryVerse Omega (DALL-E/Gemini/HF Focus) Launching... ✨")
355
  print(f" Gemini Text Ready: {GEMINI_TEXT_IS_READY}"); print(f" HF Text Ready: {HF_TEXT_IS_READY}")
356
  print(f" DALL-E Image Ready: {DALLE_IMAGE_IS_READY}"); print(f" HF Image API Ready: {HF_IMAGE_IS_READY}")
357
+ if not (GEMINI_TEXT_IS_READY or HF_TEXT_IS_READY) or not (DALLE_IMAGE_IS_READY or HF_IMAGE_IS_READY):
358
+ print(" πŸ”΄ WARNING: Not all primary/fallback AI services configured.")
359
  print(f" Default Text Model: {UI_DEFAULT_TEXT_MODEL_KEY}"); print(f" Default Image Provider: {UI_DEFAULT_IMAGE_PROVIDER_KEY}")
360
  print("="*80)
361
  story_weaver_demo.launch(debug=True, server_name="0.0.0.0", share=False)