Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import subprocess
|
| 2 |
import sys
|
| 3 |
|
| 4 |
# Install local mediagallery package at runtime (for HF Spaces)
|
|
@@ -22,15 +22,15 @@ import shutil
|
|
| 22 |
|
| 23 |
# Supported models configuration
|
| 24 |
MODELS = {
|
| 25 |
-
"
|
| 26 |
"base_url": "https://router.huggingface.co/v1",
|
| 27 |
"env_key": "HF_TOKEN",
|
| 28 |
-
"model_name": "
|
| 29 |
},
|
| 30 |
-
"
|
| 31 |
"base_url": "https://router.huggingface.co/v1",
|
| 32 |
"env_key": "HF_TOKEN",
|
| 33 |
-
"model_name": "
|
| 34 |
},
|
| 35 |
}
|
| 36 |
|
|
@@ -170,44 +170,34 @@ def get_completion(
|
|
| 170 |
|
| 171 |
# Build the user message with optional error feedback
|
| 172 |
user_content = f"""## AVAILABLE ASSETS
|
| 173 |
-
|
| 174 |
{files_info_string}
|
| 175 |
-
|
| 176 |
## TASK
|
| 177 |
{prompt}
|
| 178 |
-
|
| 179 |
## REQUIREMENTS
|
| 180 |
- Output format: MP4 video saved as "output.mp4"
|
| 181 |
- Generate a single, complete FFmpeg command
|
| 182 |
- Command must work with the exact filenames listed above
|
| 183 |
-
|
| 184 |
Think briefly about the approach, then output the FFmpeg command in a ```bash code block."""
|
| 185 |
|
| 186 |
# Add error feedback if this is a retry
|
| 187 |
if previous_error and previous_command:
|
| 188 |
user_content += f"""
|
| 189 |
-
|
| 190 |
IMPORTANT: This is a retry attempt. The previous command failed with the following error:
|
| 191 |
-
|
| 192 |
PREVIOUS COMMAND (FAILED):
|
| 193 |
{previous_command}
|
| 194 |
-
|
| 195 |
ERROR MESSAGE:
|
| 196 |
{previous_error}
|
| 197 |
-
|
| 198 |
Please analyze the error and generate a corrected command that addresses the specific issue.
|
| 199 |
-
|
| 200 |
COMMON ERROR FIXES:
|
| 201 |
-
- If you see "do not match the corresponding output link"
|
| 202 |
-
- If you see "Padded dimensions cannot be smaller than input dimensions"
|
| 203 |
-
- If you see "Failed to configure input pad"
|
| 204 |
-
- If you see "Invalid argument" in filters
|
| 205 |
-
- If you see "No option name near" with showwaves
|
| 206 |
-
|
| 207 |
FORMAT DETECTION KEYWORDS:
|
| 208 |
-
- "vertical", "portrait", "9:16", "TikTok", "Instagram Stories", "phone"
|
| 209 |
-
- "horizontal", "landscape", "16:9", "YouTube", "TV"
|
| 210 |
-
- "square", "1:1", "Instagram post"
|
| 211 |
|
| 212 |
user_content += "\n\nYOUR RESPONSE:"
|
| 213 |
|
|
@@ -217,18 +207,15 @@ FORMAT DETECTION KEYWORDS:
|
|
| 217 |
{
|
| 218 |
"role": "system",
|
| 219 |
"content": """You are an expert FFmpeg engineer. Generate precise, working FFmpeg commands.
|
| 220 |
-
|
| 221 |
## OUTPUT FORMAT
|
| 222 |
1. Brief analysis (2-3 sentences max)
|
| 223 |
2. Single FFmpeg command in a ```bash code block
|
| 224 |
3. Output file must be "output.mp4"
|
| 225 |
-
|
| 226 |
## CORE RULES
|
| 227 |
- ONE command only, no chaining (no && or ;)
|
| 228 |
- Use exact filenames from the asset list
|
| 229 |
- Keep commands as simple as possible
|
| 230 |
- Always use: -c:v libx264 -pix_fmt yuv420p -movflags +faststart
|
| 231 |
-
|
| 232 |
## SLIDESHOW PATTERN (for multiple images)
|
| 233 |
When combining images with different dimensions:
|
| 234 |
```bash
|
|
@@ -237,7 +224,6 @@ ffmpeg -loop 1 -t 3 -i img1.jpg -loop 1 -t 3 -i img2.jpg -filter_complex "[0]sca
|
|
| 237 |
- Default: 1920x1080, 3 seconds per image
|
| 238 |
- Vertical/portrait/TikTok: use 1080x1920
|
| 239 |
- Always scale+pad to normalize dimensions
|
| 240 |
-
|
| 241 |
## AUDIO WAVEFORM
|
| 242 |
For full-width waveform visualization (waveform width = video width):
|
| 243 |
```bash
|
|
@@ -247,13 +233,12 @@ CRITICAL:
|
|
| 247 |
- showwaves size uses 'x' separator: s=WIDTHxHEIGHT (NOT s=WIDTH:HEIGHT)
|
| 248 |
- For full-width: set waveform width = video width (e.g., s=1920x200 for 1920px wide video)
|
| 249 |
- overlay=0:(H-h)/2 positions at x=0 (full width) and centers vertically
|
| 250 |
-
|
| 251 |
## WITH BACKGROUND MUSIC
|
| 252 |
Add audio to video/slideshow:
|
| 253 |
```bash
|
| 254 |
ffmpeg ... -i music.mp3 -map "[vout]" -map N:a -shortest -c:a aac output.mp4
|
| 255 |
```
|
| 256 |
-
|
| 257 |
},
|
| 258 |
{
|
| 259 |
"role": "user",
|
|
@@ -279,24 +264,19 @@ ffmpeg ... -i music.mp3 -map "[vout]" -map N:a -shortest -c:a aac output.mp4
|
|
| 279 |
{
|
| 280 |
"role": "user",
|
| 281 |
"content": f"""The command failed with the following error:
|
| 282 |
-
|
| 283 |
ERROR MESSAGE:
|
| 284 |
{previous_error}
|
| 285 |
-
|
| 286 |
Please analyze the error and generate a corrected command that addresses the specific issue.
|
| 287 |
-
|
| 288 |
COMMON ERROR FIXES:
|
| 289 |
-
- If you see "do not match the corresponding output link"
|
| 290 |
-
- If you see "Padded dimensions cannot be smaller than input dimensions"
|
| 291 |
-
- If you see "Failed to configure input pad"
|
| 292 |
-
- If you see "Invalid argument" in filters
|
| 293 |
-
- If you see "No option name near" with showwaves
|
| 294 |
-
|
| 295 |
FORMAT DETECTION KEYWORDS:
|
| 296 |
-
- "vertical", "portrait", "9:16", "TikTok", "Instagram Stories", "phone"
|
| 297 |
-
- "horizontal", "landscape", "16:9", "YouTube", "TV"
|
| 298 |
-
- "square", "1:1", "Instagram post"
|
| 299 |
-
|
| 300 |
Please provide a corrected FFmpeg command.""",
|
| 301 |
}
|
| 302 |
)
|
|
@@ -407,7 +387,7 @@ Please provide a corrected FFmpeg command.""",
|
|
| 407 |
raise Exception("API Error")
|
| 408 |
|
| 409 |
|
| 410 |
-
@spaces.GPU(duration=
|
| 411 |
def execute_ffmpeg_command(args, temp_dir, output_file_path):
|
| 412 |
"""Execute FFmpeg command with GPU acceleration"""
|
| 413 |
final_command = args + ["-y", output_file_path]
|
|
@@ -425,21 +405,17 @@ def compose_video(
|
|
| 425 |
) -> str:
|
| 426 |
"""
|
| 427 |
Compose videos from existing media assets using natural language instructions.
|
| 428 |
-
|
| 429 |
This tool is NOT for AI video generation. Instead, it uses AI to generate FFmpeg
|
| 430 |
commands that combine, edit, and transform your uploaded images, videos, and audio
|
| 431 |
files based on natural language descriptions.
|
| 432 |
-
|
| 433 |
Args:
|
| 434 |
prompt (str): Natural language instructions for video composition (e.g., "Create a slideshow with background music")
|
| 435 |
files (list, optional): List of media files (images, videos, audio) to use
|
| 436 |
top_p (float): Top-p sampling parameter for AI model (0.0-1.0, default: 0.95)
|
| 437 |
temperature (float): Temperature parameter for AI model creativity (0.0-5.0, default: 0.1)
|
| 438 |
model_choice (str): AI model to use for command generation (default: "zai-org/GLM-4.7-Flash")
|
| 439 |
-
|
| 440 |
Returns:
|
| 441 |
str: Path to the generated video file
|
| 442 |
-
|
| 443 |
Example:
|
| 444 |
compose_video("Create a 10-second slideshow from the images with fade transitions", files=[img1, img2, img3])
|
| 445 |
"""
|
|
@@ -492,7 +468,7 @@ def update(
|
|
| 492 |
try:
|
| 493 |
# Show generating status
|
| 494 |
attempt_label = f" (retry {attempts})" if attempts > 0 else ""
|
| 495 |
-
yield None, f" Generating command{attempt_label}...\n"
|
| 496 |
|
| 497 |
# We need to stream the response - using a thread to allow yielding
|
| 498 |
import threading
|
|
@@ -568,7 +544,7 @@ def update(
|
|
| 568 |
command_attempts.append(
|
| 569 |
{
|
| 570 |
"command": command_for_display,
|
| 571 |
-
"status": " Valid",
|
| 572 |
"attempt": attempts + 1,
|
| 573 |
}
|
| 574 |
)
|
|
@@ -580,7 +556,7 @@ def update(
|
|
| 580 |
command_attempts.append(
|
| 581 |
{
|
| 582 |
"command": command_for_display,
|
| 583 |
-
"status": " Invalid",
|
| 584 |
"error": ffmpeg_dry_run.stderr,
|
| 585 |
"attempt": attempts + 1,
|
| 586 |
}
|
|
@@ -590,7 +566,7 @@ def update(
|
|
| 590 |
previous_error = ffmpeg_dry_run.stderr
|
| 591 |
previous_command = command_for_display
|
| 592 |
|
| 593 |
-
yield None, f" Command invalid, retrying..."
|
| 594 |
raise Exception(
|
| 595 |
f"FFMPEG command validation failed: {ffmpeg_dry_run.stderr}"
|
| 596 |
)
|
|
@@ -599,11 +575,11 @@ def update(
|
|
| 599 |
output_file_path = str((Path(temp_dir) / output_file_name).resolve())
|
| 600 |
|
| 601 |
# Show status before executing
|
| 602 |
-
yield None, get_last_lines(stream_state["text"] + "\n\n Executing FFmpeg...")
|
| 603 |
execute_ffmpeg_command(args, temp_dir, output_file_path)
|
| 604 |
|
| 605 |
# Generate command display with all attempts
|
| 606 |
-
final_output = get_last_lines(stream_state["text"]) + "\n\n Done!"
|
| 607 |
yield output_file_path, final_output
|
| 608 |
return
|
| 609 |
|
|
@@ -612,7 +588,7 @@ def update(
|
|
| 612 |
if attempts >= 2:
|
| 613 |
print("FROM UPDATE", e)
|
| 614 |
# Show model output with error (last 5 lines)
|
| 615 |
-
error_output = get_last_lines(stream_state["text"]) + f"\n\n Failed: {str(e)}"
|
| 616 |
yield None, error_output
|
| 617 |
return
|
| 618 |
|
|
@@ -628,8 +604,8 @@ def generate_command_display(command_attempts):
|
|
| 628 |
display += f"**Attempt {attempt['attempt']}** {attempt['status']}\n"
|
| 629 |
display += f"```bash\n{attempt['command']}\n```\n"
|
| 630 |
|
| 631 |
-
if attempt["status"] == " Invalid" and "error" in attempt:
|
| 632 |
-
display += f"<details>\n<summary> Error Details</summary>\n\n```\n{attempt['error']}\n```\n</details>\n\n"
|
| 633 |
else:
|
| 634 |
display += "\n"
|
| 635 |
|
|
@@ -642,43 +618,43 @@ mcp_interface = gr.Interface(
|
|
| 642 |
inputs=[
|
| 643 |
gr.Textbox(
|
| 644 |
value="Create a slideshow with background music",
|
| 645 |
-
label="Video Composition
|
| 646 |
),
|
| 647 |
gr.File(file_count="multiple", label="Media Files", file_types=allowed_medias),
|
| 648 |
-
gr.Slider(0.0, 1.0, value=0.95, label="
|
| 649 |
-
gr.Slider(0.0, 5.0, value=0.1, label="
|
| 650 |
gr.Radio(
|
| 651 |
choices=list(MODELS.keys()), value=list(MODELS.keys())[0], label="Model"
|
| 652 |
),
|
| 653 |
],
|
| 654 |
outputs=gr.Video(label="Generated Video"),
|
| 655 |
-
title="
|
| 656 |
description="Compose videos from media assets using natural language",
|
| 657 |
-
|
| 658 |
|
| 659 |
-
with gr.Blocks(
|
| 660 |
gr.Markdown(
|
| 661 |
-
|
| 662 |
-
#
|
| 663 |
-
|
| 664 |
""",
|
| 665 |
elem_id="header",
|
| 666 |
)
|
| 667 |
with gr.Row():
|
| 668 |
with gr.Column():
|
| 669 |
-
user_prompt = gr.Textbox(
|
| 670 |
-
placeholder="eg: Remove the 3 first seconds of the video",
|
| 671 |
-
label="Guidance",
|
| 672 |
-
lines=3,
|
| 673 |
-
)
|
| 674 |
user_files = MediaGallery(
|
| 675 |
file_types=allowed_medias,
|
| 676 |
label="Media Assets",
|
| 677 |
columns=3,
|
| 678 |
-
interactive=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 679 |
)
|
| 680 |
-
btn = gr.Button("
|
| 681 |
-
with gr.Accordion("
|
| 682 |
model_choice = gr.Radio(
|
| 683 |
choices=list(MODELS.keys()),
|
| 684 |
value=list(MODELS.keys())[0],
|
|
@@ -690,8 +666,7 @@ with gr.Blocks(css="footer {display:none !important}") as demo:
|
|
| 690 |
value=0.95,
|
| 691 |
step=0.05,
|
| 692 |
interactive=True,
|
| 693 |
-
|
| 694 |
-
label="Intensity",
|
| 695 |
)
|
| 696 |
temperature = gr.Slider(
|
| 697 |
minimum=-0,
|
|
@@ -699,52 +674,37 @@ with gr.Blocks(css="footer {display:none !important}") as demo:
|
|
| 699 |
value=0.1,
|
| 700 |
step=0.1,
|
| 701 |
interactive=True,
|
| 702 |
-
|
| 703 |
-
label="Probability",
|
| 704 |
)
|
| 705 |
with gr.Column():
|
|
|
|
|
|
|
|
|
|
| 706 |
generated_command = gr.Textbox(
|
| 707 |
label="Model Output",
|
| 708 |
lines=5,
|
| 709 |
max_lines=5,
|
| 710 |
-
interactive=
|
| 711 |
-
)
|
| 712 |
-
generated_video = gr.Video(
|
| 713 |
-
interactive=False, label="Generated Video", include_audio=True
|
| 714 |
)
|
| 715 |
|
| 716 |
-
|
| 717 |
fn=update,
|
| 718 |
inputs=[user_files, user_prompt, top_p, temperature, model_choice],
|
| 719 |
-
outputs=[
|
| 720 |
-
|
| 721 |
with gr.Row():
|
| 722 |
gr.Examples(
|
| 723 |
examples=[
|
| 724 |
[
|
| 725 |
-
["./examples/
|
| 726 |
-
"
|
| 727 |
-
0.95,
|
| 728 |
-
0.1,
|
| 729 |
-
list(MODELS.keys())[0],
|
| 730 |
-
],
|
| 731 |
-
[
|
| 732 |
-
["./examples/five.mp4"],
|
| 733 |
-
"Cut the video to extract only the middle 5 seconds (starting at 00:02 and ending at 00:07).",
|
| 734 |
-
0.95,
|
| 735 |
-
0.1,
|
| 736 |
-
list(MODELS.keys())[0],
|
| 737 |
-
],
|
| 738 |
-
[
|
| 739 |
-
["./examples/five.mp4"],
|
| 740 |
-
"Convert the video to black and white (grayscale) while maintaining the original audio..",
|
| 741 |
0.95,
|
| 742 |
0.1,
|
| 743 |
list(MODELS.keys())[0],
|
| 744 |
],
|
| 745 |
[
|
| 746 |
["./examples/ai_talk.wav", "./examples/bg-image.png"],
|
| 747 |
-
"Use the image as the background with a full-width waveform visualization for the audio.",
|
| 748 |
0.95,
|
| 749 |
0.1,
|
| 750 |
list(MODELS.keys())[0],
|
|
@@ -759,24 +719,30 @@ with gr.Blocks(css="footer {display:none !important}") as demo:
|
|
| 759 |
"./examples/cat6.jpeg",
|
| 760 |
"./examples/heat-wave.mp3",
|
| 761 |
],
|
| 762 |
-
"Create a
|
| 763 |
0.95,
|
| 764 |
0.1,
|
| 765 |
list(MODELS.keys())[0],
|
| 766 |
],
|
| 767 |
],
|
| 768 |
inputs=[user_files, user_prompt, top_p, temperature, model_choice],
|
| 769 |
-
outputs=[
|
| 770 |
-
fn=update,
|
| 771 |
-
|
|
|
|
| 772 |
)
|
| 773 |
|
| 774 |
with gr.Row():
|
| 775 |
-
gr.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 776 |
|
| 777 |
# Launch MCP interface for tool access
|
| 778 |
-
mcp_interface.queue(default_concurrency_limit=
|
| 779 |
|
| 780 |
# Launch main demo
|
| 781 |
-
demo.queue(default_concurrency_limit=
|
| 782 |
demo.launch(show_api=False, ssr_mode=False, mcp_server=True)
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
import sys
|
| 3 |
|
| 4 |
# Install local mediagallery package at runtime (for HF Spaces)
|
|
|
|
| 22 |
|
| 23 |
# Supported models configuration
|
| 24 |
MODELS = {
|
| 25 |
+
"moonshotai/Kimi-K2-Instruct": {
|
| 26 |
"base_url": "https://router.huggingface.co/v1",
|
| 27 |
"env_key": "HF_TOKEN",
|
| 28 |
+
"model_name": "moonshotai/Kimi-K2-Instruct-0905:groq",
|
| 29 |
},
|
| 30 |
+
"zai-org/GLM-4.7-Flash": {
|
| 31 |
"base_url": "https://router.huggingface.co/v1",
|
| 32 |
"env_key": "HF_TOKEN",
|
| 33 |
+
"model_name": "zai-org/GLM-4.7-Flash:novita",
|
| 34 |
},
|
| 35 |
}
|
| 36 |
|
|
|
|
| 170 |
|
| 171 |
# Build the user message with optional error feedback
|
| 172 |
user_content = f"""## AVAILABLE ASSETS
|
|
|
|
| 173 |
{files_info_string}
|
|
|
|
| 174 |
## TASK
|
| 175 |
{prompt}
|
|
|
|
| 176 |
## REQUIREMENTS
|
| 177 |
- Output format: MP4 video saved as "output.mp4"
|
| 178 |
- Generate a single, complete FFmpeg command
|
| 179 |
- Command must work with the exact filenames listed above
|
|
|
|
| 180 |
Think briefly about the approach, then output the FFmpeg command in a ```bash code block."""
|
| 181 |
|
| 182 |
# Add error feedback if this is a retry
|
| 183 |
if previous_error and previous_command:
|
| 184 |
user_content += f"""
|
|
|
|
| 185 |
IMPORTANT: This is a retry attempt. The previous command failed with the following error:
|
|
|
|
| 186 |
PREVIOUS COMMAND (FAILED):
|
| 187 |
{previous_command}
|
|
|
|
| 188 |
ERROR MESSAGE:
|
| 189 |
{previous_error}
|
|
|
|
| 190 |
Please analyze the error and generate a corrected command that addresses the specific issue.
|
|
|
|
| 191 |
COMMON ERROR FIXES:
|
| 192 |
+
- If you see "do not match the corresponding output link" → Images have different dimensions, use scale+pad approach
|
| 193 |
+
- If you see "Padded dimensions cannot be smaller than input dimensions" → Fix pad calculation or use standard resolution (1920x1080 or 1080x1920)
|
| 194 |
+
- If you see "Failed to configure input pad" → Check scale and pad syntax, ensure proper filter chain
|
| 195 |
+
- If you see "Invalid argument" in filters → Simplify filter_complex syntax and check parentheses
|
| 196 |
+
- If you see "No option name near" with showwaves → Use 'x' for size: s=1920x200 (NOT s=1920:200)
|
|
|
|
| 197 |
FORMAT DETECTION KEYWORDS:
|
| 198 |
+
- "vertical", "portrait", "9:16", "TikTok", "Instagram Stories", "phone" → Use 1080x1920
|
| 199 |
+
- "horizontal", "landscape", "16:9", "YouTube", "TV" → Use 1920x1080 (default)
|
| 200 |
+
- "square", "1:1", "Instagram post" → Use 1080x1080"""
|
| 201 |
|
| 202 |
user_content += "\n\nYOUR RESPONSE:"
|
| 203 |
|
|
|
|
| 207 |
{
|
| 208 |
"role": "system",
|
| 209 |
"content": """You are an expert FFmpeg engineer. Generate precise, working FFmpeg commands.
|
|
|
|
| 210 |
## OUTPUT FORMAT
|
| 211 |
1. Brief analysis (2-3 sentences max)
|
| 212 |
2. Single FFmpeg command in a ```bash code block
|
| 213 |
3. Output file must be "output.mp4"
|
|
|
|
| 214 |
## CORE RULES
|
| 215 |
- ONE command only, no chaining (no && or ;)
|
| 216 |
- Use exact filenames from the asset list
|
| 217 |
- Keep commands as simple as possible
|
| 218 |
- Always use: -c:v libx264 -pix_fmt yuv420p -movflags +faststart
|
|
|
|
| 219 |
## SLIDESHOW PATTERN (for multiple images)
|
| 220 |
When combining images with different dimensions:
|
| 221 |
```bash
|
|
|
|
| 224 |
- Default: 1920x1080, 3 seconds per image
|
| 225 |
- Vertical/portrait/TikTok: use 1080x1920
|
| 226 |
- Always scale+pad to normalize dimensions
|
|
|
|
| 227 |
## AUDIO WAVEFORM
|
| 228 |
For full-width waveform visualization (waveform width = video width):
|
| 229 |
```bash
|
|
|
|
| 233 |
- showwaves size uses 'x' separator: s=WIDTHxHEIGHT (NOT s=WIDTH:HEIGHT)
|
| 234 |
- For full-width: set waveform width = video width (e.g., s=1920x200 for 1920px wide video)
|
| 235 |
- overlay=0:(H-h)/2 positions at x=0 (full width) and centers vertically
|
|
|
|
| 236 |
## WITH BACKGROUND MUSIC
|
| 237 |
Add audio to video/slideshow:
|
| 238 |
```bash
|
| 239 |
ffmpeg ... -i music.mp3 -map "[vout]" -map N:a -shortest -c:a aac output.mp4
|
| 240 |
```
|
| 241 |
+
Where N is the audio input index.""",
|
| 242 |
},
|
| 243 |
{
|
| 244 |
"role": "user",
|
|
|
|
| 264 |
{
|
| 265 |
"role": "user",
|
| 266 |
"content": f"""The command failed with the following error:
|
|
|
|
| 267 |
ERROR MESSAGE:
|
| 268 |
{previous_error}
|
|
|
|
| 269 |
Please analyze the error and generate a corrected command that addresses the specific issue.
|
|
|
|
| 270 |
COMMON ERROR FIXES:
|
| 271 |
+
- If you see "do not match the corresponding output link" → Images have different dimensions, use scale+pad approach
|
| 272 |
+
- If you see "Padded dimensions cannot be smaller than input dimensions" → Fix pad calculation or use standard resolution (1920x1080 or 1080x1920)
|
| 273 |
+
- If you see "Failed to configure input pad" → Check scale and pad syntax, ensure proper filter chain
|
| 274 |
+
- If you see "Invalid argument" in filters → Simplify filter_complex syntax and check parentheses
|
| 275 |
+
- If you see "No option name near" with showwaves → Use 'x' for size: s=1920x200 (NOT s=1920:200)
|
|
|
|
| 276 |
FORMAT DETECTION KEYWORDS:
|
| 277 |
+
- "vertical", "portrait", "9:16", "TikTok", "Instagram Stories", "phone" → Use 1080x1920
|
| 278 |
+
- "horizontal", "landscape", "16:9", "YouTube", "TV" → Use 1920x1080 (default)
|
| 279 |
+
- "square", "1:1", "Instagram post" → Use 1080x1080
|
|
|
|
| 280 |
Please provide a corrected FFmpeg command.""",
|
| 281 |
}
|
| 282 |
)
|
|
|
|
| 387 |
raise Exception("API Error")
|
| 388 |
|
| 389 |
|
| 390 |
+
@spaces.GPU(duration=120)
|
| 391 |
def execute_ffmpeg_command(args, temp_dir, output_file_path):
|
| 392 |
"""Execute FFmpeg command with GPU acceleration"""
|
| 393 |
final_command = args + ["-y", output_file_path]
|
|
|
|
| 405 |
) -> str:
|
| 406 |
"""
|
| 407 |
Compose videos from existing media assets using natural language instructions.
|
|
|
|
| 408 |
This tool is NOT for AI video generation. Instead, it uses AI to generate FFmpeg
|
| 409 |
commands that combine, edit, and transform your uploaded images, videos, and audio
|
| 410 |
files based on natural language descriptions.
|
|
|
|
| 411 |
Args:
|
| 412 |
prompt (str): Natural language instructions for video composition (e.g., "Create a slideshow with background music")
|
| 413 |
files (list, optional): List of media files (images, videos, audio) to use
|
| 414 |
top_p (float): Top-p sampling parameter for AI model (0.0-1.0, default: 0.95)
|
| 415 |
temperature (float): Temperature parameter for AI model creativity (0.0-5.0, default: 0.1)
|
| 416 |
model_choice (str): AI model to use for command generation (default: "zai-org/GLM-4.7-Flash")
|
|
|
|
| 417 |
Returns:
|
| 418 |
str: Path to the generated video file
|
|
|
|
| 419 |
Example:
|
| 420 |
compose_video("Create a 10-second slideshow from the images with fade transitions", files=[img1, img2, img3])
|
| 421 |
"""
|
|
|
|
| 468 |
try:
|
| 469 |
# Show generating status
|
| 470 |
attempt_label = f" (retry {attempts})" if attempts > 0 else ""
|
| 471 |
+
yield None, f"🤖 Generating command{attempt_label}...\n"
|
| 472 |
|
| 473 |
# We need to stream the response - using a thread to allow yielding
|
| 474 |
import threading
|
|
|
|
| 544 |
command_attempts.append(
|
| 545 |
{
|
| 546 |
"command": command_for_display,
|
| 547 |
+
"status": "✅ Valid",
|
| 548 |
"attempt": attempts + 1,
|
| 549 |
}
|
| 550 |
)
|
|
|
|
| 556 |
command_attempts.append(
|
| 557 |
{
|
| 558 |
"command": command_for_display,
|
| 559 |
+
"status": "❌ Invalid",
|
| 560 |
"error": ffmpeg_dry_run.stderr,
|
| 561 |
"attempt": attempts + 1,
|
| 562 |
}
|
|
|
|
| 566 |
previous_error = ffmpeg_dry_run.stderr
|
| 567 |
previous_command = command_for_display
|
| 568 |
|
| 569 |
+
yield None, f"❌ Command invalid, retrying..."
|
| 570 |
raise Exception(
|
| 571 |
f"FFMPEG command validation failed: {ffmpeg_dry_run.stderr}"
|
| 572 |
)
|
|
|
|
| 575 |
output_file_path = str((Path(temp_dir) / output_file_name).resolve())
|
| 576 |
|
| 577 |
# Show status before executing
|
| 578 |
+
yield None, get_last_lines(stream_state["text"] + "\n\n⚙️ Executing FFmpeg...")
|
| 579 |
execute_ffmpeg_command(args, temp_dir, output_file_path)
|
| 580 |
|
| 581 |
# Generate command display with all attempts
|
| 582 |
+
final_output = get_last_lines(stream_state["text"]) + "\n\n✅ Done!"
|
| 583 |
yield output_file_path, final_output
|
| 584 |
return
|
| 585 |
|
|
|
|
| 588 |
if attempts >= 2:
|
| 589 |
print("FROM UPDATE", e)
|
| 590 |
# Show model output with error (last 5 lines)
|
| 591 |
+
error_output = get_last_lines(stream_state["text"]) + f"\n\n❌ Failed: {str(e)}"
|
| 592 |
yield None, error_output
|
| 593 |
return
|
| 594 |
|
|
|
|
| 604 |
display += f"**Attempt {attempt['attempt']}** {attempt['status']}\n"
|
| 605 |
display += f"```bash\n{attempt['command']}\n```\n"
|
| 606 |
|
| 607 |
+
if attempt["status"] == "❌ Invalid" and "error" in attempt:
|
| 608 |
+
display += f"<details>\n<summary>🔍 Error Details</summary>\n\n```\n{attempt['error']}\n```\n</details>\n\n"
|
| 609 |
else:
|
| 610 |
display += "\n"
|
| 611 |
|
|
|
|
| 618 |
inputs=[
|
| 619 |
gr.Textbox(
|
| 620 |
value="Create a slideshow with background music",
|
| 621 |
+
label="Video Composition Instructions",
|
| 622 |
),
|
| 623 |
gr.File(file_count="multiple", label="Media Files", file_types=allowed_medias),
|
| 624 |
+
gr.Slider(0.0, 1.0, value=0.95, label="Top-p"),
|
| 625 |
+
gr.Slider(0.0, 5.0, value=0.1, label="Temperature"),
|
| 626 |
gr.Radio(
|
| 627 |
choices=list(MODELS.keys()), value=list(MODELS.keys())[0], label="Model"
|
| 628 |
),
|
| 629 |
],
|
| 630 |
outputs=gr.Video(label="Generated Video"),
|
| 631 |
+
title="AI Video Composer MCP Tool",
|
| 632 |
description="Compose videos from media assets using natural language",
|
| 633 |
+
)
|
| 634 |
|
| 635 |
+
with gr.Blocks() as demo:
|
| 636 |
gr.Markdown(
|
| 637 |
+
"""
|
| 638 |
+
# 🏞 AI Video Composer: FFMPEG in Plain English
|
| 639 |
+
Upload your media files, describe what you want, and AI generates the FFMPEG command. Create slideshows from images, add background music, merge video clips, visualize audio waveforms, convert formats, adjust speed, and more.
|
| 640 |
""",
|
| 641 |
elem_id="header",
|
| 642 |
)
|
| 643 |
with gr.Row():
|
| 644 |
with gr.Column():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 645 |
user_files = MediaGallery(
|
| 646 |
file_types=allowed_medias,
|
| 647 |
label="Media Assets",
|
| 648 |
columns=3,
|
| 649 |
+
interactive=True,
|
| 650 |
+
)
|
| 651 |
+
user_prompt = gr.Textbox(
|
| 652 |
+
placeholder="eg: Remove the 3 first seconds of the video",
|
| 653 |
+
label="Instructions",
|
| 654 |
+
lines=3,
|
| 655 |
)
|
| 656 |
+
btn = gr.Button("Run")
|
| 657 |
+
with gr.Accordion("Parameters", open=False):
|
| 658 |
model_choice = gr.Radio(
|
| 659 |
choices=list(MODELS.keys()),
|
| 660 |
value=list(MODELS.keys())[0],
|
|
|
|
| 666 |
value=0.95,
|
| 667 |
step=0.05,
|
| 668 |
interactive=True,
|
| 669 |
+
label="Top-p (nucleus sampling)",
|
|
|
|
| 670 |
)
|
| 671 |
temperature = gr.Slider(
|
| 672 |
minimum=-0,
|
|
|
|
| 674 |
value=0.1,
|
| 675 |
step=0.1,
|
| 676 |
interactive=True,
|
| 677 |
+
label="Temperature",
|
|
|
|
| 678 |
)
|
| 679 |
with gr.Column():
|
| 680 |
+
generated_video = gr.Video(
|
| 681 |
+
interactive=False, label="Generated Video", include_audio=True
|
| 682 |
+
)
|
| 683 |
generated_command = gr.Textbox(
|
| 684 |
label="Model Output",
|
| 685 |
lines=5,
|
| 686 |
max_lines=5,
|
| 687 |
+
interactive=False,
|
|
|
|
|
|
|
|
|
|
| 688 |
)
|
| 689 |
|
| 690 |
+
btn.click(
|
| 691 |
fn=update,
|
| 692 |
inputs=[user_files, user_prompt, top_p, temperature, model_choice],
|
| 693 |
+
outputs=[generated_video, generated_command],
|
| 694 |
+
)
|
| 695 |
with gr.Row():
|
| 696 |
gr.Examples(
|
| 697 |
examples=[
|
| 698 |
[
|
| 699 |
+
["./examples/ai_talk.wav", "./examples/bg-image.png"],
|
| 700 |
+
"Use the image as the background with a full-width waveform visualization for the audio.",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 701 |
0.95,
|
| 702 |
0.1,
|
| 703 |
list(MODELS.keys())[0],
|
| 704 |
],
|
| 705 |
[
|
| 706 |
["./examples/ai_talk.wav", "./examples/bg-image.png"],
|
| 707 |
+
"Use the image as the background with a full-width waveform visualization for the audio. Make the waveform 250 pixels tall.",
|
| 708 |
0.95,
|
| 709 |
0.1,
|
| 710 |
list(MODELS.keys())[0],
|
|
|
|
| 719 |
"./examples/cat6.jpeg",
|
| 720 |
"./examples/heat-wave.mp3",
|
| 721 |
],
|
| 722 |
+
"Create a 3x2 grid of the cat images with the audio as background music. Make the video duration match the audio duration.",
|
| 723 |
0.95,
|
| 724 |
0.1,
|
| 725 |
list(MODELS.keys())[0],
|
| 726 |
],
|
| 727 |
],
|
| 728 |
inputs=[user_files, user_prompt, top_p, temperature, model_choice],
|
| 729 |
+
outputs=[generated_video, generated_command],
|
| 730 |
+
fn=update,
|
| 731 |
+
run_on_click=True,
|
| 732 |
+
cache_examples=False,
|
| 733 |
)
|
| 734 |
|
| 735 |
with gr.Row():
|
| 736 |
+
gr.Markdown(
|
| 737 |
+
"""
|
| 738 |
+
If you have idea to improve this please open a PR:
|
| 739 |
+
[](https://huggingface.co/spaces/huggingface-projects/video-composer-gpt4/discussions)
|
| 740 |
+
""",
|
| 741 |
+
)
|
| 742 |
|
| 743 |
# Launch MCP interface for tool access
|
| 744 |
+
mcp_interface.queue(default_concurrency_limit=200)
|
| 745 |
|
| 746 |
# Launch main demo
|
| 747 |
+
demo.queue(default_concurrency_limit=200)
|
| 748 |
demo.launch(show_api=False, ssr_mode=False, mcp_server=True)
|