aarsh28 commited on
Commit
dec2cf0
·
verified ·
1 Parent(s): 3c004c9

Update pipeline/main_pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline/main_pipeline.py +125 -99
pipeline/main_pipeline.py CHANGED
@@ -1,7 +1,9 @@
 
1
  import os
2
  import time
3
  import uuid
4
  import shutil
 
5
  from moviepy.editor import AudioFileClip
6
  import gradio as gr
7
 
@@ -13,107 +15,131 @@ from pipeline import (
13
  module4_postproduction
14
  )
15
 
 
16
  def create_story_video(prompt: str, language: str = "English", tone: str = "Default", progress=gr.Progress(track_tqdm=True)):
17
  """
18
  Main pipeline for generating an AI animated story with audio, images, and video.
19
  Returns the path to the final video and the full story text.
 
20
  """
21
- print("\n--- Starting New Story Generation ---")
22
- pipeline_start = time.time()
23
-
24
- # --- Step 0: Unique folder per request ---
25
- request_id = uuid.uuid4().hex[:8]
26
- project_name = f"generated_story_{request_id}"
27
- os.makedirs(project_name, exist_ok=True)
28
-
29
- temp_folder = os.path.join(project_name, "temp")
30
- os.makedirs(temp_folder, exist_ok=True)
31
-
32
- temp_audio_files = []
33
- temp_image_files = []
34
-
35
- # --- Step 1: Enrich Prompt and Create Cast List ---
36
- rich_concept, cast_list = module0_casting.enrich_prompt(simple_prompt=prompt, story_tone=tone)
37
-
38
- # --- Step 2: Generate Story Text and Scene List ---
39
- story_text = module1_screenwriting.generate_story_text(rich_concept, cast_list)
40
- scene_list = module1_screenwriting.generate_scene_list_from_story(story_text, cast_list, rich_concept)
41
-
42
- if not scene_list:
43
- return None, "Failed to generate story content. Please try a different prompt."
44
-
45
- video_clips = []
46
- full_story_text = " ".join([scene.get("sentence", "") for scene in scene_list])
47
-
48
- # --- Step 3: Loop Through Scenes ---
49
- for i, scene_data in enumerate(scene_list):
50
- sentence = scene_data.get("sentence")
51
- updated_cast = scene_data.get("characters", [])
52
- shot = scene_data.get("shot", [])
53
- shot_type = scene_data.get("shot_type", [])
54
-
55
- if not sentence or not shot or not updated_cast:
56
- print(f"Scene {i+1} missing critical data. Skipping.")
57
- continue
58
-
59
- print(f"\n--- Processing Scene {i+1}/{len(scene_list)}: {sentence} ---")
60
-
61
- # --- Generate Scene Audio ---
62
- audio_path = os.path.join(temp_folder, f"scene_{i+1:02d}.mp3")
63
- audio_success = module2_voiceover.generate_audio(
64
- text=sentence, lang=language, filename=audio_path, story_tone=tone
65
- )
66
- if not audio_success:
67
- print(f"Audio generation failed. Skipping scene.")
68
- continue
69
- temp_audio_files.append(audio_path)
70
-
71
- if isinstance(shot, str):
72
- shot = [shot]
73
-
74
- with AudioFileClip(audio_path) as main_audio_clip:
75
- audio_duration = main_audio_clip.duration
76
- duration_per_shot = audio_duration / len(shot)
77
-
78
- for j, visual_prompt in enumerate(shot):
79
- shot_path_base = os.path.join(temp_folder, f"scene_{i+1:02d}_shot_{j+1:02d}")
80
- image_path = f"{shot_path_base}.png"
81
- sub_audio_path = f"{shot_path_base}.mp3"
82
-
83
- # --- Generate Image ---
84
- module3_image_generation.generate_image(
85
- shot_type=shot_type,
86
- visual_prompt=visual_prompt,
87
- updated_cast=updated_cast,
88
- filename=image_path
89
- )
90
- temp_image_files.append(image_path)
91
-
92
- # --- Split Audio ---
93
- sub_audio_clip = main_audio_clip.subclip(j * duration_per_shot, (j + 1) * duration_per_shot)
94
- sub_audio_clip.write_audiofile(sub_audio_path, logger=None)
95
- temp_audio_files.append(sub_audio_path)
96
-
97
- # --- Create Scene Clip ---
98
- final_audio_clip = AudioFileClip(sub_audio_path)
99
- scene_clip = module4_postproduction.create_scene_clip(
100
- image_path=image_path,
101
- audio_clip=final_audio_clip,
102
- subtitle_text=sentence
103
- )
104
- video_clips.append(scene_clip)
105
-
106
- if not video_clips:
107
- return None, "Video generation failed. No valid scenes created."
108
-
109
- # --- Step 4: Assemble Final Video ---
110
- final_video_path = os.path.join(project_name, "final_story.mp4")
111
- module4_postproduction.assemble_video(video_clips, output_filename=final_video_path)
112
-
113
- # --- Optional: Clean up temp files ---
114
- shutil.rmtree(temp_folder)
115
-
116
- pipeline_end = time.time()
117
- print(f"\n[Main] Pipeline complete in {(pipeline_end - pipeline_start)/60:.2f} minutes.")
118
-
119
- return final_video_path, full_story_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pipeline/main_pipeline.py
2
  import os
3
  import time
4
  import uuid
5
  import shutil
6
+ import traceback
7
  from moviepy.editor import AudioFileClip
8
  import gradio as gr
9
 
 
15
  module4_postproduction
16
  )
17
 
18
+
19
  def create_story_video(prompt: str, language: str = "English", tone: str = "Default", progress=gr.Progress(track_tqdm=True)):
20
  """
21
  Main pipeline for generating an AI animated story with audio, images, and video.
22
  Returns the path to the final video and the full story text.
23
+ Emits progress updates via the provided Gradio Progress object.
24
  """
25
+ start_time = time.time()
26
+ try:
27
+ print("\n--- Starting New Story Generation ---", flush=True)
28
+ progress(0.02, desc="Initializing...")
29
+
30
+ # --- Step 0: Unique folder per request ---
31
+ request_id = uuid.uuid4().hex[:8]
32
+ project_name = f"generated_story_{request_id}"
33
+ os.makedirs(project_name, exist_ok=True)
34
+
35
+ temp_folder = os.path.join(project_name, "temp")
36
+ os.makedirs(temp_folder, exist_ok=True)
37
+
38
+ temp_audio_files = []
39
+ temp_image_files = []
40
+
41
+ # --- Step 1: Enrich Prompt and Create Cast List ---
42
+ progress(0.06, desc="Enriching prompt & choosing cast...")
43
+ rich_concept, cast_list = module0_casting.enrich_prompt(simple_prompt=prompt, story_tone=tone)
44
+
45
+ # --- Step 2: Generate Story Text and Scene List ---
46
+ progress(0.12, desc="Generating story text...")
47
+ story_text = module1_screenwriting.generate_story_text(rich_concept, cast_list)
48
+ progress(0.18, desc="Generating scene list...")
49
+ scene_list = module1_screenwriting.generate_scene_list_from_story(story_text, cast_list, rich_concept)
50
+
51
+ if not scene_list:
52
+ return None, "Failed to generate story content. Please try a different prompt."
53
+
54
+ video_clips = []
55
+ full_story_text = " ".join([scene.get("sentence", "") for scene in scene_list])
56
+
57
+ # --- Step 3: Loop Through Scenes ---
58
+ total_scenes = len(scene_list)
59
+ for i, scene_data in enumerate(scene_list):
60
+ sentence = scene_data.get("sentence")
61
+ updated_cast = scene_data.get("characters", [])
62
+ shot = scene_data.get("shot", [])
63
+ shot_type = scene_data.get("shot_type", [])
64
+
65
+ if not sentence or not shot or not updated_cast:
66
+ print(f"Scene {i+1} missing critical data. Skipping.", flush=True)
67
+ continue
68
+
69
+ print(f"\n--- Processing Scene {i+1}/{len(scene_list)}: {sentence} ---", flush=True)
70
+ # update progress roughly proportional to scene index
71
+ progress(0.20 + 0.60 * (i / max(1, total_scenes)), desc=f"Processing scene {i+1}/{total_scenes}...")
72
+
73
+ # --- Generate Scene Audio ---
74
+ audio_path = os.path.join(temp_folder, f"scene_{i+1:02d}.mp3")
75
+ progress(0.22 + 0.60 * (i / max(1, total_scenes)), desc=f"Generating audio for scene {i+1}...")
76
+ audio_success = module2_voiceover.generate_audio(
77
+ text=sentence, lang=language, filename=audio_path, story_tone=tone
78
+ )
79
+ if not audio_success:
80
+ print(f"Audio generation failed. Skipping scene {i+1}.", flush=True)
81
+ continue
82
+ temp_audio_files.append(audio_path)
83
+
84
+ if isinstance(shot, str):
85
+ shot = [shot]
86
+
87
+ with AudioFileClip(audio_path) as main_audio_clip:
88
+ audio_duration = main_audio_clip.duration
89
+ duration_per_shot = audio_duration / len(shot)
90
+
91
+ for j, visual_prompt in enumerate(shot):
92
+ shot_path_base = os.path.join(temp_folder, f"scene_{i+1:02d}")
93
+ image_path = f"{shot_path_base}.png"
94
+ sub_audio_path = f"{shot_path_base}.mp3"
95
+
96
+ # --- Generate Image ---
97
+ progress(0.30 + 0.60 * (i / max(1, total_scenes)) + (0.02 * j), desc=f"Generating image S{i+1}x{j+1}...")
98
+ module3_image_generation.generate_image(
99
+ shot_type=shot_type,
100
+ visual_prompt=visual_prompt,
101
+ updated_cast=updated_cast,
102
+ filename=image_path
103
+ )
104
+ temp_image_files.append(image_path)
105
+
106
+ # --- Split Audio ---
107
+ sub_audio_clip = main_audio_clip.subclip(j * duration_per_shot, (j + 1) * duration_per_shot)
108
+ progress(0.33 + 0.60 * (i / max(1, total_scenes)) + (0.02 * j), desc=f"Preparing audio S{i+1}x{j+1}...")
109
+ sub_audio_clip.write_audiofile(sub_audio_path, logger=None)
110
+ temp_audio_files.append(sub_audio_path)
111
+
112
+ # --- Create Scene Clip ---
113
+ final_audio_clip = AudioFileClip(sub_audio_path)
114
+ scene_clip = module4_postproduction.create_scene_clip(
115
+ image_path=image_path,
116
+ audio_clip=final_audio_clip,
117
+ subtitle_text=sentence
118
+ )
119
+ video_clips.append(scene_clip)
120
+
121
+ if not video_clips:
122
+ return None, "Video generation failed. No valid scenes created."
123
+
124
+ # --- Step 4: Assemble Final Video ---
125
+ progress(0.85, desc="Assembling final video...")
126
+ final_video_path = os.path.join(project_name, "final_story.mp4")
127
+ module4_postproduction.assemble_video(video_clips, output_filename=final_video_path)
128
+
129
+ # --- Optional: Clean up temp files ---
130
+ progress(0.95, desc="Cleaning up temporary files...")
131
+ try:
132
+ shutil.rmtree(temp_folder)
133
+ except Exception:
134
+ print("Failed to remove temp folder; continuing.", flush=True)
135
+
136
+ pipeline_end = time.time()
137
+ print(f"\n[Main] Pipeline complete in {(pipeline_end - start_time)/60:.2f} minutes. Output: {final_video_path}", flush=True)
138
+ progress(1.0, desc="Done")
139
+
140
+ return final_video_path, full_story_text
141
+
142
+ except Exception as e:
143
+ print("!!! Unhandled exception in pipeline:", flush=True)
144
+ traceback.print_exc()
145
+ return None, f"Unhandled pipeline error: {e}"