Nick021402 commited on
Commit
2424bf7
Β·
verified Β·
1 Parent(s): 507a71d

Create App.py

Browse files
Files changed (1) hide show
  1. App.py +444 -0
App.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
4
+ from transformers import pipeline
5
+ import numpy as np
6
+ from PIL import Image, ImageDraw, ImageFont
7
+ import io
8
+ import base64
9
+ import json
10
+ import re
11
+ import time
12
+ import os
13
+ from typing import List, Dict, Tuple, Optional
14
+ import warnings
15
+ warnings.filterwarnings("ignore")
16
+
17
+ # Global variables for models
18
+ sd_pipe = None
19
+ tts_pipe = None
20
+
21
+ def initialize_models():
22
+ """Initialize AI models on first use"""
23
+ global sd_pipe, tts_pipe
24
+
25
+ if sd_pipe is None:
26
+ print("Loading Stable Diffusion model...")
27
+ sd_pipe = StableDiffusionPipeline.from_pretrained(
28
+ "runwayml/stable-diffusion-v1-5",
29
+ torch_dtype=torch.float32, # Use float32 for CPU
30
+ safety_checker=None,
31
+ requires_safety_checker=False
32
+ )
33
+ sd_pipe.scheduler = DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config)
34
+ sd_pipe = sd_pipe.to("cpu")
35
+ sd_pipe.enable_attention_slicing()
36
+
37
+ if tts_pipe is None:
38
+ try:
39
+ print("Loading TTS model...")
40
+ tts_pipe = pipeline("text-to-speech", model="microsoft/speecht5_tts", device=-1)
41
+ except:
42
+ print("TTS model not available, continuing without audio...")
43
+ tts_pipe = None
44
+
45
+ class StorySegmenter:
46
+ """Handles story segmentation and prompt enhancement"""
47
+
48
+ @staticmethod
49
+ def split_story(story: str, max_segments: int = 15) -> List[str]:
50
+ """Split story into segments suitable for 10-second videos"""
51
+ # Split by sentences first
52
+ sentences = re.split(r'[.!?]+', story)
53
+ sentences = [s.strip() for s in sentences if s.strip()]
54
+
55
+ segments = []
56
+ current_segment = ""
57
+
58
+ for sentence in sentences:
59
+ # If adding this sentence would make segment too long, start new segment
60
+ if len(current_segment + " " + sentence) > 200 or len(segments) >= max_segments:
61
+ if current_segment:
62
+ segments.append(current_segment.strip())
63
+ current_segment = sentence
64
+ else:
65
+ segments.append(sentence)
66
+ else:
67
+ current_segment += (" " + sentence if current_segment else sentence)
68
+
69
+ # Add final segment
70
+ if current_segment:
71
+ segments.append(current_segment.strip())
72
+
73
+ return segments[:max_segments]
74
+
75
+ @staticmethod
76
+ def enhance_prompt(segment: str, character_name: str, character_traits: str,
77
+ style: str, scene_context: str = "") -> str:
78
+ """Enhance segment prompt with character and style information"""
79
+ enhanced = f"{segment}. "
80
+ enhanced += f"Character: {character_name} ({character_traits}). "
81
+ enhanced += f"Style: {style}, high quality, detailed. "
82
+ if scene_context:
83
+ enhanced += f"Scene context: {scene_context}. "
84
+
85
+ # Add negative prompts
86
+ enhanced += "NEGATIVE: blurry, low quality, distorted, bad anatomy"
87
+
88
+ return enhanced
89
+
90
+ class ConsistencyManager:
91
+ """Manages visual consistency across segments"""
92
+
93
+ def __init__(self, base_seed: int = 42):
94
+ self.base_seed = base_seed
95
+ self.character_prompt = ""
96
+ self.scene_context = ""
97
+ self.last_scene_elements = []
98
+
99
+ def get_segment_seed(self, segment_index: int) -> int:
100
+ """Get consistent seed for segment"""
101
+ return self.base_seed + segment_index
102
+
103
+ def update_context(self, segment: str):
104
+ """Update scene context based on current segment"""
105
+ # Simple context extraction - in production would use NLP
106
+ if any(word in segment.lower() for word in ['house', 'home', 'room', 'kitchen']):
107
+ self.scene_context = "indoor domestic setting"
108
+ elif any(word in segment.lower() for word in ['forest', 'tree', 'nature', 'outdoor']):
109
+ self.scene_context = "outdoor natural setting"
110
+ elif any(word in segment.lower() for word in ['city', 'street', 'building']):
111
+ self.scene_context = "urban setting"
112
+
113
+ class VideoGenerator:
114
+ """Handles video/image generation for each segment"""
115
+
116
+ def __init__(self):
117
+ self.consistency_manager = ConsistencyManager()
118
+
119
+ def generate_segment_image(self, enhanced_prompt: str, seed: int,
120
+ width: int = 512, height: int = 512) -> Image.Image:
121
+ """Generate image for a story segment"""
122
+ initialize_models()
123
+
124
+ if sd_pipe is None:
125
+ # Fallback: create a placeholder image
126
+ return self.create_placeholder_image(enhanced_prompt, width, height)
127
+
128
+ try:
129
+ generator = torch.Generator().manual_seed(seed)
130
+
131
+ # Generate image
132
+ with torch.no_grad():
133
+ result = sd_pipe(
134
+ prompt=enhanced_prompt,
135
+ negative_prompt="blurry, low quality, distorted, bad anatomy, ugly",
136
+ num_inference_steps=20, # Reduced for faster generation
137
+ guidance_scale=7.5,
138
+ width=width,
139
+ height=height,
140
+ generator=generator
141
+ )
142
+
143
+ return result.images[0]
144
+
145
+ except Exception as e:
146
+ print(f"Error generating image: {e}")
147
+ return self.create_placeholder_image(enhanced_prompt, width, height)
148
+
149
+ def create_placeholder_image(self, prompt: str, width: int, height: int) -> Image.Image:
150
+ """Create a placeholder image when generation fails"""
151
+ img = Image.new('RGB', (width, height), color='lightblue')
152
+ draw = ImageDraw.Draw(img)
153
+
154
+ # Try to load a font, fallback to default if not available
155
+ try:
156
+ font = ImageFont.truetype("arial.ttf", 20)
157
+ except:
158
+ font = ImageFont.load_default()
159
+
160
+ # Wrap text
161
+ words = prompt[:100].split()
162
+ lines = []
163
+ current_line = ""
164
+
165
+ for word in words:
166
+ if len(current_line + word) < 40:
167
+ current_line += word + " "
168
+ else:
169
+ lines.append(current_line)
170
+ current_line = word + " "
171
+ if current_line:
172
+ lines.append(current_line)
173
+
174
+ # Draw text
175
+ y_offset = height // 2 - (len(lines) * 25) // 2
176
+ for line in lines:
177
+ bbox = draw.textbbox((0, 0), line, font=font)
178
+ text_width = bbox[2] - bbox[0]
179
+ x_offset = (width - text_width) // 2
180
+ draw.text((x_offset, y_offset), line, fill='black', font=font)
181
+ y_offset += 25
182
+
183
+ return img
184
+
185
+ class AudioGenerator:
186
+ """Handles audio generation for segments"""
187
+
188
+ @staticmethod
189
+ def generate_segment_audio(text: str, speaker_id: int = 0) -> Optional[bytes]:
190
+ """Generate audio for a text segment"""
191
+ initialize_models()
192
+
193
+ if tts_pipe is None:
194
+ return None
195
+
196
+ try:
197
+ # Generate audio
198
+ audio_data = tts_pipe(text)
199
+
200
+ # Convert to bytes (simplified - in production would handle proper audio format)
201
+ if 'audio' in audio_data:
202
+ # Convert audio array to bytes representation
203
+ audio_array = np.array(audio_data['audio'])
204
+ return audio_array.tobytes()
205
+
206
+ except Exception as e:
207
+ print(f"Error generating audio: {e}")
208
+
209
+ return None
210
+
211
+ def process_story(story_text: str, character_name: str, character_traits: str,
212
+ style: str, enable_voiceover: bool, reference_image: Optional[Image.Image] = None,
213
+ progress=gr.Progress()) -> Tuple[List[Image.Image], List[str], str]:
214
+ """Main processing function"""
215
+
216
+ if not story_text.strip():
217
+ return [], [], "Please enter a story to generate."
218
+
219
+ if not character_name.strip():
220
+ character_name = "Main Character"
221
+
222
+ if not character_traits.strip():
223
+ character_traits = "detailed character design"
224
+
225
+ # Initialize components
226
+ segmenter = StorySegmenter()
227
+ video_gen = VideoGenerator()
228
+ audio_gen = AudioGenerator()
229
+
230
+ # Step 1: Split story into segments
231
+ progress(0.1, "Splitting story into segments...")
232
+ segments = segmenter.split_story(story_text)
233
+
234
+ if not segments:
235
+ return [], [], "Could not create segments from the story."
236
+
237
+ progress(0.2, f"Created {len(segments)} segments")
238
+
239
+ # Step 2: Generate content for each segment
240
+ generated_images = []
241
+ generated_audio_info = []
242
+
243
+ for i, segment in enumerate(segments):
244
+ progress((0.2 + 0.7 * (i / len(segments))), f"Generating segment {i+1}/{len(segments)}")
245
+
246
+ # Update consistency context
247
+ video_gen.consistency_manager.update_context(segment)
248
+
249
+ # Enhance prompt
250
+ enhanced_prompt = segmenter.enhance_prompt(
251
+ segment, character_name, character_traits, style,
252
+ video_gen.consistency_manager.scene_context
253
+ )
254
+
255
+ # Generate image
256
+ seed = video_gen.consistency_manager.get_segment_seed(i)
257
+ image = video_gen.generate_segment_image(enhanced_prompt, seed)
258
+ generated_images.append(image)
259
+
260
+ # Generate audio if enabled
261
+ if enable_voiceover:
262
+ audio_bytes = audio_gen.generate_segment_audio(segment)
263
+ audio_info = f"Audio generated for segment {i+1}" if audio_bytes else f"Audio generation failed for segment {i+1}"
264
+ else:
265
+ audio_info = f"No audio (voiceover disabled)"
266
+
267
+ generated_audio_info.append(audio_info)
268
+
269
+ # Small delay to prevent overwhelming the system
270
+ time.sleep(0.1)
271
+
272
+ progress(1.0, "Generation complete!")
273
+
274
+ # Create summary
275
+ summary = f"""
276
+ ## Generation Summary
277
+
278
+ **Story Segments**: {len(segments)}
279
+ **Character**: {character_name} ({character_traits})
280
+ **Style**: {style}
281
+ **Voiceover**: {'Enabled' if enable_voiceover else 'Disabled'}
282
+
283
+ ### Segments Generated:
284
+ """
285
+
286
+ for i, segment in enumerate(segments):
287
+ summary += f"\n**Segment {i+1}**: {segment[:100]}{'...' if len(segment) > 100 else ''}"
288
+
289
+ return generated_images, generated_audio_info, summary
290
+
291
+ def create_interface():
292
+ """Create the Gradio interface"""
293
+
294
+ with gr.Blocks(title="AI Video Story Generator", theme=gr.themes.Soft()) as interface:
295
+
296
+ gr.Markdown("""
297
+ # 🎬 AI Video Story Generator
298
+
299
+ Generate animated story segments with consistent characters and scenes.
300
+ Running on free CPU tier - generates 10-15 segments of ~10 seconds each.
301
+ """)
302
+
303
+ with gr.Row():
304
+ with gr.Column(scale=2):
305
+ story_input = gr.Textbox(
306
+ label="πŸ“– Story Text",
307
+ placeholder="Enter your story here (up to 50,000 characters)...",
308
+ lines=10,
309
+ max_lines=20
310
+ )
311
+
312
+ with gr.Row():
313
+ character_name = gr.Textbox(
314
+ label="πŸ‘€ Character Name",
315
+ placeholder="e.g., Alice, Hero, The Detective",
316
+ value="Main Character"
317
+ )
318
+ character_traits = gr.Textbox(
319
+ label="✨ Character Traits",
320
+ placeholder="e.g., young woman, brown hair, blue dress",
321
+ value="detailed character design"
322
+ )
323
+
324
+ with gr.Row():
325
+ style = gr.Dropdown(
326
+ label="🎨 Visual Style",
327
+ choices=[
328
+ "anime style",
329
+ "realistic",
330
+ "cartoon style",
331
+ "fantasy art",
332
+ "sci-fi concept art",
333
+ "children's book illustration",
334
+ "comic book style"
335
+ ],
336
+ value="anime style"
337
+ )
338
+ enable_voiceover = gr.Checkbox(
339
+ label="πŸ”Š Enable Voiceover",
340
+ value=False
341
+ )
342
+
343
+ reference_image = gr.Image(
344
+ label="πŸ–ΌοΈ Reference Image (Optional)",
345
+ type="pil"
346
+ )
347
+
348
+ with gr.Column(scale=1):
349
+ generate_btn = gr.Button(
350
+ "🎬 Generate Story Video",
351
+ variant="primary",
352
+ size="lg"
353
+ )
354
+
355
+ gr.Markdown("""
356
+ ### πŸ“‹ Instructions:
357
+ 1. Enter your story text
358
+ 2. Define your main character
359
+ 3. Choose visual style
360
+ 4. Enable voiceover if desired
361
+ 5. Click Generate!
362
+
363
+ ### ⚑ Free Tier Limits:
364
+ - Max 15 segments (~3 minutes)
365
+ - CPU processing (slower)
366
+ - Sequential generation
367
+ """)
368
+
369
+ # Results section
370
+ with gr.Row():
371
+ summary_output = gr.Markdown(label="πŸ“Š Generation Summary")
372
+
373
+ # Generated content gallery
374
+ with gr.Row():
375
+ generated_gallery = gr.Gallery(
376
+ label="πŸ–ΌοΈ Generated Segments",
377
+ show_label=True,
378
+ elem_id="gallery",
379
+ columns=3,
380
+ rows=2,
381
+ height="auto"
382
+ )
383
+
384
+ with gr.Row():
385
+ audio_info = gr.Textbox(
386
+ label="πŸ”Š Audio Information",
387
+ lines=5,
388
+ interactive=False
389
+ )
390
+
391
+ # Download section
392
+ gr.Markdown("""
393
+ ### πŸ“₯ Download Instructions:
394
+ 1. Right-click on any image to save individual segments
395
+ 2. Use external tools to combine segments into final video
396
+ 3. Audio files (if generated) can be downloaded separately
397
+
398
+ ### πŸ”§ Recommended Tools for Combining:
399
+ - **Free**: OpenShot, DaVinci Resolve, Blender
400
+ - **Online**: Kapwing, Canva Video Editor
401
+ - **Command Line**: FFmpeg
402
+ """)
403
+
404
+ # Event handlers
405
+ generate_btn.click(
406
+ fn=process_story,
407
+ inputs=[
408
+ story_input,
409
+ character_name,
410
+ character_traits,
411
+ style,
412
+ enable_voiceover,
413
+ reference_image
414
+ ],
415
+ outputs=[
416
+ generated_gallery,
417
+ audio_info,
418
+ summary_output
419
+ ],
420
+ show_progress=True
421
+ )
422
+
423
+ # Example stories
424
+ gr.Markdown("""
425
+ ### πŸ“š Example Stories to Try:
426
+
427
+ **Fantasy Adventure**: "A brave knight discovers a magical forest where the trees whisper ancient secrets. She meets a wise dragon who offers to teach her the old magic. Together they must stop an evil sorcerer from destroying the realm."
428
+
429
+ **Sci-Fi Mystery**: "On a space station orbiting Mars, Detective Chen investigates strange disappearances. The security cameras show nothing, but she notices the artificial gravity fluctuating. Her investigation leads to a discovery that changes everything."
430
+
431
+ **Children's Tale**: "Little Bear couldn't sleep because of the thunder. He decided to visit his friend Owl, who lived in the big oak tree. Owl taught him that storms bring rain for flowers, and showed him how lightning dances across the sky."
432
+ """)
433
+
434
+ return interface
435
+
436
+ # Create and launch the interface
437
+ if __name__ == "__main__":
438
+ interface = create_interface()
439
+ interface.launch(
440
+ share=True,
441
+ server_name="0.0.0.0",
442
+ server_port=7860,
443
+ show_error=True
444
+ )