-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperfect_sync_motion_examples.py
More file actions
361 lines (290 loc) Β· 13 KB
/
perfect_sync_motion_examples.py
File metadata and controls
361 lines (290 loc) Β· 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#!/usr/bin/env python3
"""
Perfect Sync Motion Video Generation Examples
This script demonstrates the enhanced audio-video synchronization and motion capabilities:
- Voice scripts that match EXACT video duration
- Motion-synchronized audio generation
- Enhanced dynamic motion generation
- Precise timing down to milliseconds
"""
import json
import requests
import time
from typing import Dict, Any
def test_perfect_audio_video_sync():
"""Test perfect audio-video synchronization with motion intensity."""
print("π¬ποΈ Perfect Audio-Video Synchronization Test")
print("=" * 60)
print()
# Test scenarios with different durations and motion intensities
sync_test_scenarios = [
{
"name": "Short Ocean Scene - Dynamic Motion + Custom Voice",
"image_prompt": "A dramatic ocean scene with powerful waves crashing against rocky cliffs",
"motion_intensity": "dynamic",
"duration": 5,
"voice_type": "onyx",
"voice_script": "Watch as powerful waves surge against ancient cliffs, their rhythmic energy creating a mesmerizing dance of water and stone. Feel the raw power of nature's eternal rhythm.",
"merge_audio": True
},
{
"name": "Forest Scene - Cinematic Motion + Generated Narration",
"image_prompt": "A mystical forest with towering ancient trees and magical sunbeams",
"motion_intensity": "cinematic",
"duration": 8,
"voice_type": "nova",
"style": "dramatic",
"merge_audio": True
},
{
"name": "Mountain Landscape - Subtle Motion + Long Duration",
"image_prompt": "A serene mountain lake reflecting snow-capped peaks at dawn",
"motion_intensity": "subtle",
"duration": 10,
"voice_type": "shimmer",
"style": "meditative",
"voice_script": "In the stillness of dawn, mountain peaks mirror themselves in crystal waters. This peaceful moment captures the essence of nature's perfect balance, where earth meets sky in harmonious reflection. Let this tranquil scene wash over you with its gentle, timeless beauty.",
"merge_audio": True
}
]
results = []
for i, scenario in enumerate(sync_test_scenarios, 1):
print(f"π― Test {i}: {scenario['name']}")
print(f" Duration: {scenario['duration']}s")
print(f" Motion: {scenario['motion_intensity']}")
print(f" Voice: {scenario['voice_type']}")
if 'voice_script' in scenario:
words = len(scenario['voice_script'].split())
print(f" Custom Script: {words} words")
print(f" Script: \"{scenario['voice_script'][:100]}...\"")
else:
print(f" Generated Style: {scenario['style']}")
print()
# Test with preview mode first
print(" π Testing with preview mode...")
preview_result = test_sync_preview(scenario)
if preview_result:
print(" β
Preview generated successfully")
# Show the motion prompt that will be used
if 'prompts' in preview_result:
video_prompt = preview_result['prompts'].get('2_video_generation', {}).get('sanitized_prompt', '')
print(f" π¬ Video Motion Prompt: {video_prompt[:80]}...")
audio_info = preview_result['prompts'].get('3_audio_generation', {})
if audio_info:
print(f" ποΈ Audio Speed: {audio_info.get('speech_speed', 'N/A')}x")
print(f" π Estimated Words: {audio_info.get('estimated_words', 'N/A')}")
else:
print(" β Preview failed")
results.append({
"scenario": scenario,
"preview_result": preview_result
})
print()
print("-" * 60)
print()
# Save results
timestamp = int(time.time())
results_file = f"perfect_sync_test_results_{timestamp}.json"
with open(results_file, 'w') as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print(f"π Results saved to: {results_file}")
return results
def test_sync_preview(scenario: Dict[str, Any]) -> Dict[Any, Any]:
"""Test the sync preview for a specific scenario."""
try:
payload = {
"image_prompt": scenario["image_prompt"],
"motion_intensity": scenario["motion_intensity"],
"duration": scenario["duration"],
"voice_type": scenario["voice_type"],
"merge_audio": scenario.get("merge_audio", True),
"preview_only": True
}
# Add voice script or style
if "voice_script" in scenario:
payload["voice_script_preview"] = scenario["voice_script"]
else:
payload["style"] = scenario["style"]
response = requests.post("http://localhost:8000/generate-video-from-prompt", json=payload)
if response.status_code == 200:
return response.json()
else:
print(f" β API request failed: {response.status_code}")
return None
except Exception as e:
print(f" β Request failed: {e}")
return None
def test_motion_intensity_comparison():
"""Compare motion generation across different intensity levels."""
print("\nπ Motion Intensity Comparison Test")
print("=" * 60)
base_scenario = {
"image_prompt": "A beautiful waterfall cascading down moss-covered rocks in a lush forest",
"duration": 6,
"voice_type": "alloy",
"style": "descriptive"
}
intensities = ["subtle", "moderate", "dynamic", "cinematic"]
print(f"Base Scene: {base_scenario['image_prompt']}")
print(f"Duration: {base_scenario['duration']}s")
print()
motion_results = {}
for intensity in intensities:
print(f"π¬ Testing {intensity.upper()} Motion:")
test_payload = {
**base_scenario,
"motion_intensity": intensity,
"preview_only": True
}
try:
response = requests.post("http://localhost:8000/generate-video-from-prompt", json=test_payload)
if response.status_code == 200:
result = response.json()
# Extract the motion prompt
if 'prompts' in result:
video_gen = result['prompts'].get('2_video_generation', {})
motion_prompt = video_gen.get('sanitized_prompt', '')
print(f" Motion Prompt: {motion_prompt}")
motion_results[intensity] = motion_prompt
print(" β
Success")
else:
print(" β οΈ No prompt data in response")
else:
print(f" β Failed: {response.status_code}")
except Exception as e:
print(f" β Error: {e}")
print()
# Analyze motion keyword differences
print("π Motion Keyword Analysis:")
print("-" * 40)
for intensity, prompt in motion_results.items():
keywords = extract_motion_keywords(prompt)
print(f"{intensity.upper()}: {', '.join(keywords[:5])}...") # Show first 5 keywords
return motion_results
def extract_motion_keywords(prompt: str) -> list:
"""Extract motion-related keywords from a prompt."""
motion_keywords = [
"dynamic", "cinematic", "epic", "dramatic", "flowing", "sweeping",
"gentle", "smooth", "energetic", "rhythmic", "cascading", "dancing",
"swaying", "drifting", "racing", "billowing", "streaming", "camera",
"movement", "motion", "animation", "particles", "shifting", "revealing"
]
found_keywords = []
prompt_lower = prompt.lower()
for keyword in motion_keywords:
if keyword in prompt_lower:
found_keywords.append(keyword)
return found_keywords
def test_duration_precision():
"""Test duration precision capabilities."""
print("\nβ±οΈ Duration Precision Test")
print("=" * 60)
# Test different duration scenarios
precision_tests = [
{"duration": 3, "description": "Short video precision"},
{"duration": 5, "description": "Standard duration"},
{"duration": 7.5, "description": "Non-integer duration"},
{"duration": 10, "description": "Maximum duration"}
]
base_prompt = "A peaceful garden with blooming flowers and gentle butterflies"
for test in precision_tests:
duration = test["duration"]
print(f"π― {test['description']}: {duration}s")
payload = {
"image_prompt": base_prompt,
"motion_intensity": "moderate",
"duration": int(duration), # API expects int
"voice_type": "nova",
"style": "descriptive",
"preview_only": True
}
try:
response = requests.post("http://localhost:8000/generate-video-from-prompt", json=payload)
if response.status_code == 200:
result = response.json()
# Check audio optimization
if 'prompts' in result:
audio_info = result['prompts'].get('3_audio_generation', {})
if audio_info:
speed = audio_info.get('speech_speed', 1.0)
words = audio_info.get('estimated_words', 0)
print(f" Audio: {words} words at {speed}x speed")
print(" β
Precision optimized")
else:
print(" β οΈ No audio optimization data")
else:
print(" β οΈ No optimization data available")
else:
print(f" β Failed: {response.status_code}")
except Exception as e:
print(f" β Error: {e}")
print()
def demonstrate_new_features():
"""Demonstrate the new synchronization and motion features."""
print("\n⨠New Features Demonstration")
print("=" * 60)
features = [
"π― Exact video duration detection and audio matching",
"π¬ Motion-synchronized audio generation",
"π Enhanced motion intensity levels (subtle β cinematic)",
"β±οΈ Precise timing down to milliseconds (Β±0.05s tolerance)",
"ποΈ Motion-aware speech rhythm adjustments",
"π Multiple retry attempts for duration detection",
"π΅ Audio fade effects for extended content",
"π Motion-specific script optimization",
"π¨ Enhanced scene detection (50+ keywords)",
"π Dramatic motion enhancers for cinematic content"
]
for feature in features:
print(f" {feature}")
print()
print("π οΈ Technical Improvements:")
print(" β’ Tighter synchronization tolerance (0.1s β 0.05s)")
print(" β’ Enhanced FFmpeg commands with precise timing")
print(" β’ Motion-adjusted speaking rates for different intensities")
print(" β’ Automatic video duration detection with retry logic")
print(" β’ Motion-specific padding phrases for script extension")
print(" β’ Speech speed fine-tuning for short/long videos")
if __name__ == "__main__":
print("π Perfect Sync Motion Video Generation Tests")
print("=" * 60)
# Check API health
try:
response = requests.get("http://localhost:8000/health")
if response.status_code == 200:
print("β
API server is healthy")
else:
print(f"β οΈ API server status: {response.status_code}")
exit(1)
except:
print("β Cannot connect to API server")
print(" Please start with: python run_api.py")
exit(1)
print()
# Demonstrate new features
demonstrate_new_features()
# Run sync tests
print()
results = test_perfect_audio_video_sync()
# Test motion comparison
motion_results = test_motion_intensity_comparison()
# Test duration precision
test_duration_precision()
print("\nπ Perfect Sync Motion Testing Complete!")
print("\nπ‘ Key Synchronization Features:")
print("β’ Audio duration matches video EXACTLY (within 0.05s)")
print("β’ Motion intensity affects speech rhythm and pacing")
print("β’ Real-time video duration detection with retry logic")
print("β’ Enhanced motion generation with cinematic quality")
print("β’ Precise FFmpeg merging with fade effects")
print("\n㪠Motion Enhancements:")
print("β’ 4 intensity levels: subtle β moderate β dynamic β cinematic")
print("β’ Motion-synchronized audio with rhythm matching")
print("β’ Enhanced scene detection with 50+ keywords")
print("β’ Dramatic motion enhancers for epic content")
print("β’ Motion-specific script optimization")
print("\nπ― Perfect Use Cases:")
print("β’ Educational videos: moderate motion + clear narration")
print("β’ Social media: dynamic motion + energetic audio")
print("β’ Meditation content: subtle motion + calm narration")
print("β’ Professional videos: cinematic motion + dramatic audio")