ismdrobiul489 commited on
Commit
5257b31
·
1 Parent(s): a7c6f3a

fix: Sync audio with message timing using CompositeAudioClip

Browse files
modules/text_story/services/video_composer.py CHANGED
@@ -8,8 +8,8 @@ import logging
8
  from typing import List, Dict, Optional
9
  from moviepy.editor import (
10
  VideoFileClip, ImageClip, AudioFileClip,
11
- CompositeVideoClip, concatenate_videoclips,
12
- ColorClip, TextClip
13
  )
14
  from moviepy.video.fx.all import fadein, fadeout
15
  import numpy as np
@@ -101,27 +101,10 @@ class VideoComposer:
101
  """
102
  logger.info(f"VideoComposer: Starting composition with {len(messages)} messages")
103
 
104
- # Calculate total duration
105
  total_duration = 0
106
- for i, msg in enumerate(messages):
107
- total_duration += self._calculate_typing_duration(msg["text"])
108
- total_duration += TIMING["voice_delay"]
109
- total_duration += msg["duration"]
110
- total_duration += TIMING["micro_silence"]
111
-
112
- total_duration += TIMING["last_msg_pause"]
113
-
114
- if ending_text:
115
- total_duration += TIMING["ending_duration"]
116
-
117
- logger.info(f"VideoComposer: Total duration: {total_duration:.1f}s")
118
-
119
- # Load background
120
- background = self.bg_handler.load_and_process(total_duration)
121
-
122
- # Create message sequence
123
- clips = []
124
- current_time = 0
125
  displayed_messages = []
126
 
127
  for i, msg in enumerate(messages):
@@ -130,60 +113,76 @@ class VideoComposer:
130
  # 1. Typing indicator phase
131
  typing_duration = self._calculate_typing_duration(msg["text"])
132
  typing_frame = self.renderer.render_frame(displayed_messages, show_typing=True)
133
- typing_clip = self._pil_to_moviepy(typing_frame, typing_duration)
134
- typing_clip = typing_clip.set_start(current_time)
135
- clips.append(typing_clip)
136
- current_time += typing_duration
137
 
138
- # 2. Add message (with voice delay)
139
  displayed_messages.append(msg_dict)
140
 
141
- # Message appears (voice delay gap)
142
  msg_frame = self.renderer.render_frame(displayed_messages)
143
- voice_delay_clip = self._pil_to_moviepy(msg_frame, TIMING["voice_delay"])
144
- voice_delay_clip = voice_delay_clip.set_start(current_time)
145
- clips.append(voice_delay_clip)
146
- current_time += TIMING["voice_delay"]
147
 
148
- # 3. Message with audio
149
- msg_clip = self._pil_to_moviepy(msg_frame, msg["duration"])
150
- msg_clip = msg_clip.set_start(current_time)
151
 
152
- # Add audio
153
  audio = AudioFileClip(msg["path"])
154
- msg_clip = msg_clip.set_audio(audio.set_start(0))
155
- clips.append(msg_clip)
156
- current_time += msg["duration"]
157
 
158
- # 4. Micro silence
159
- silence_clip = self._pil_to_moviepy(msg_frame, TIMING["micro_silence"])
160
- silence_clip = silence_clip.set_start(current_time)
161
- clips.append(silence_clip)
162
- current_time += TIMING["micro_silence"]
163
 
164
- logger.info(f"VideoComposer: Message {i+1}/{len(messages)} at {current_time:.1f}s")
 
 
165
 
166
  # Last message pause
167
  final_frame = self.renderer.render_frame(displayed_messages)
168
- pause_clip = self._pil_to_moviepy(final_frame, TIMING["last_msg_pause"])
169
- pause_clip = pause_clip.set_start(current_time)
170
- clips.append(pause_clip)
171
- current_time += TIMING["last_msg_pause"]
172
 
173
  # Ending text
174
  if ending_text:
175
- ending_clip = self._create_ending_clip(ending_text, displayed_messages)
176
- ending_clip = ending_clip.set_start(current_time)
177
- clips.append(ending_clip)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- # Composite all clips over background
180
- final = CompositeVideoClip([background] + clips, size=(CANVAS_WIDTH, CANVAS_HEIGHT))
181
- final = final.set_duration(total_duration)
 
182
 
183
  # Export
184
  output_path = os.path.join(output_dir, "text_story_output.mp4")
185
 
186
- final.write_videofile(
 
 
187
  output_path,
188
  fps=30,
189
  codec="libx264",
@@ -194,16 +193,16 @@ class VideoComposer:
194
  )
195
 
196
  # Cleanup
197
- final.close()
198
  background.close()
199
- for clip in clips:
200
- clip.close()
201
 
202
  logger.info(f"VideoComposer: Saved to {output_path}")
203
  return output_path
204
 
205
- def _create_ending_clip(self, text: str, messages: List[dict]) -> ImageClip:
206
- """Create ending text overlay."""
207
  # Render current state
208
  frame = self.renderer.render_frame(messages)
209
 
@@ -229,8 +228,4 @@ class VideoComposer:
229
  draw.text((x + 2, y + 2), text, fill=(0, 0, 0, 200), font=font)
230
  draw.text((x, y), text, fill=(255, 255, 255, 255), font=font)
231
 
232
- # Convert to clip with fade
233
- clip = self._pil_to_moviepy(frame, TIMING["ending_duration"])
234
- clip = clip.fx(fadein, TIMING["ending_fade"])
235
-
236
- return clip
 
8
  from typing import List, Dict, Optional
9
  from moviepy.editor import (
10
  VideoFileClip, ImageClip, AudioFileClip,
11
+ CompositeVideoClip, CompositeAudioClip, concatenate_videoclips,
12
+ ColorClip, TextClip, afx
13
  )
14
  from moviepy.video.fx.all import fadein, fadeout
15
  import numpy as np
 
101
  """
102
  logger.info(f"VideoComposer: Starting composition with {len(messages)} messages")
103
 
104
+ # Calculate total duration and audio start times
105
  total_duration = 0
106
+ audio_clips = [] # List of (audio_clip, start_time)
107
+ frame_sequence = [] # List of (frame, duration, start_time)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  displayed_messages = []
109
 
110
  for i, msg in enumerate(messages):
 
113
  # 1. Typing indicator phase
114
  typing_duration = self._calculate_typing_duration(msg["text"])
115
  typing_frame = self.renderer.render_frame(displayed_messages, show_typing=True)
116
+ frame_sequence.append((typing_frame, typing_duration, total_duration))
117
+ total_duration += typing_duration
 
 
118
 
119
+ # 2. Add message to display
120
  displayed_messages.append(msg_dict)
121
 
122
+ # 3. Voice delay (message appears, but audio hasn't started)
123
  msg_frame = self.renderer.render_frame(displayed_messages)
124
+ frame_sequence.append((msg_frame, TIMING["voice_delay"], total_duration))
125
+ total_duration += TIMING["voice_delay"]
 
 
126
 
127
+ # 4. Audio starts HERE - sync point!
128
+ audio_start_time = total_duration
129
+ logger.info(f"VideoComposer: Message {i+1} audio starts at {audio_start_time:.2f}s")
130
 
131
+ # Load audio and add to list with start time
132
  audio = AudioFileClip(msg["path"])
133
+ audio_clips.append((audio, audio_start_time))
 
 
134
 
135
+ # Message display during audio
136
+ frame_sequence.append((msg_frame, msg["duration"], total_duration))
137
+ total_duration += msg["duration"]
 
 
138
 
139
+ # 5. Micro silence after message
140
+ frame_sequence.append((msg_frame, TIMING["micro_silence"], total_duration))
141
+ total_duration += TIMING["micro_silence"]
142
 
143
  # Last message pause
144
  final_frame = self.renderer.render_frame(displayed_messages)
145
+ frame_sequence.append((final_frame, TIMING["last_msg_pause"], total_duration))
146
+ total_duration += TIMING["last_msg_pause"]
 
 
147
 
148
  # Ending text
149
  if ending_text:
150
+ ending_frame = self._create_ending_frame(ending_text, displayed_messages)
151
+ frame_sequence.append((ending_frame, TIMING["ending_duration"], total_duration))
152
+ total_duration += TIMING["ending_duration"]
153
+
154
+ logger.info(f"VideoComposer: Total duration: {total_duration:.1f}s")
155
+
156
+ # Load background for full duration
157
+ background = self.bg_handler.load_and_process(total_duration)
158
+
159
+ # Create video clips from frames
160
+ video_clips = [background]
161
+ for frame, duration, start_time in frame_sequence:
162
+ clip = self._pil_to_moviepy(frame, duration)
163
+ clip = clip.set_start(start_time)
164
+ video_clips.append(clip)
165
+
166
+ # Create composite audio with correct start times
167
+ audio_with_timing = []
168
+ for audio, start_time in audio_clips:
169
+ audio_with_timing.append(audio.set_start(start_time))
170
+
171
+ # Composite video
172
+ video = CompositeVideoClip(video_clips, size=(CANVAS_WIDTH, CANVAS_HEIGHT))
173
+ video = video.set_duration(total_duration)
174
 
175
+ # Composite audio
176
+ if audio_with_timing:
177
+ final_audio = CompositeAudioClip(audio_with_timing)
178
+ video = video.set_audio(final_audio)
179
 
180
  # Export
181
  output_path = os.path.join(output_dir, "text_story_output.mp4")
182
 
183
+ logger.info(f"VideoComposer: Writing video to {output_path}")
184
+
185
+ video.write_videofile(
186
  output_path,
187
  fps=30,
188
  codec="libx264",
 
193
  )
194
 
195
  # Cleanup
196
+ video.close()
197
  background.close()
198
+ for audio, _ in audio_clips:
199
+ audio.close()
200
 
201
  logger.info(f"VideoComposer: Saved to {output_path}")
202
  return output_path
203
 
204
+ def _create_ending_frame(self, text: str, messages: List[dict]) -> Image.Image:
205
+ """Create ending text overlay frame."""
206
  # Render current state
207
  frame = self.renderer.render_frame(messages)
208
 
 
228
  draw.text((x + 2, y + 2), text, fill=(0, 0, 0, 200), font=font)
229
  draw.text((x, y), text, fill=(255, 255, 255, 255), font=font)
230
 
231
+ return frame