Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
from fastapi import FastAPI, UploadFile, File, Form
|
| 2 |
-
from fastapi.responses import FileResponse
|
| 3 |
import tempfile
|
| 4 |
import shutil
|
| 5 |
import os
|
|
@@ -18,19 +18,16 @@ import numpy as np
|
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
|
|
|
| 21 |
def safe_audio_clip(path):
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
clip.
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
if clip.reader is None or clip.duration is None or clip.duration <= 0:
|
| 31 |
-
clip.close()
|
| 32 |
-
raise ValueError(f"Invalid or empty video file: {os.path.basename(path)}")
|
| 33 |
-
return clip
|
| 34 |
|
| 35 |
def merge_videos_and_audios(
|
| 36 |
video_files, audio_files, orig_vol=1.0, music_vol=0.5, temp_dir=None
|
|
@@ -39,53 +36,74 @@ def merge_videos_and_audios(
|
|
| 39 |
output_path = os.path.join(
|
| 40 |
temp_dir, "merged_output.mp4" if video_files else "merged_output.mp3"
|
| 41 |
)
|
| 42 |
-
|
| 43 |
# If no videos, just concatenate audios
|
| 44 |
if not video_files and audio_files:
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
final_audio = concatenate_audioclips(audio_clips)
|
| 48 |
final_audio.write_audiofile(output_path)
|
| 49 |
for clip in audio_clips:
|
| 50 |
clip.close()
|
| 51 |
final_audio.close()
|
| 52 |
-
logger.info(f"Audio merge complete: {output_path}")
|
| 53 |
return output_path
|
| 54 |
|
| 55 |
# If videos are present:
|
| 56 |
-
|
| 57 |
-
video_clips = [safe_video_clip(v) for v in video_files]
|
| 58 |
final_video = concatenate_videoclips(video_clips, method="compose")
|
| 59 |
-
|
| 60 |
if audio_files:
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
if
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
else:
|
| 72 |
-
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
final_video = final_video.set_audio(composite_audio)
|
| 75 |
-
for clip in audio_clips:
|
| 76 |
-
clip.close()
|
| 77 |
else:
|
| 78 |
-
# No audio
|
| 79 |
if final_video.audio is not None:
|
| 80 |
final_video = final_video.volumex(orig_vol)
|
| 81 |
-
# else → no audio at all
|
| 82 |
|
| 83 |
-
# Final video output
|
| 84 |
final_video.write_videofile(output_path, codec="libx264", audio_codec="aac")
|
|
|
|
| 85 |
for clip in video_clips:
|
| 86 |
clip.close()
|
| 87 |
final_video.close()
|
| 88 |
-
|
| 89 |
return output_path
|
| 90 |
|
| 91 |
except Exception as e:
|
|
@@ -93,7 +111,6 @@ def merge_videos_and_audios(
|
|
| 93 |
logger.error(error_msg)
|
| 94 |
return error_msg
|
| 95 |
|
| 96 |
-
# FastAPI app
|
| 97 |
app = FastAPI()
|
| 98 |
|
| 99 |
@app.post("/merge")
|
|
@@ -104,7 +121,6 @@ async def merge_endpoint(
|
|
| 104 |
):
|
| 105 |
temp_dir = tempfile.mkdtemp()
|
| 106 |
try:
|
| 107 |
-
# Save all uploaded files
|
| 108 |
saved_files = []
|
| 109 |
for uploaded_file in files:
|
| 110 |
file_path = os.path.join(temp_dir, uploaded_file.filename)
|
|
@@ -112,42 +128,35 @@ async def merge_endpoint(
|
|
| 112 |
content = await uploaded_file.read()
|
| 113 |
out_file.write(content)
|
| 114 |
saved_files.append(file_path)
|
| 115 |
-
logger.info(f"Saved file: {uploaded_file.filename}")
|
| 116 |
|
| 117 |
-
# Separate video and audio files
|
| 118 |
video_files = [f for f in saved_files if f.lower().endswith(".mp4")]
|
| 119 |
-
audio_files = [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
# Require at least 2 files
|
| 122 |
if len(saved_files) < 2:
|
| 123 |
-
return
|
| 124 |
-
status_code=400,
|
| 125 |
-
content={"error": "Please upload at least 2 files (videos or audios)."},
|
| 126 |
-
)
|
| 127 |
|
| 128 |
-
# Perform merge
|
| 129 |
result_path = merge_videos_and_audios(
|
| 130 |
video_files, audio_files, orig_vol, music_vol, temp_dir
|
| 131 |
)
|
| 132 |
|
| 133 |
-
# If error occurred
|
| 134 |
if isinstance(result_path, str) and result_path.startswith("Error"):
|
| 135 |
-
return
|
| 136 |
-
status_code=500,
|
| 137 |
-
content={"error": result_path},
|
| 138 |
-
)
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
|
|
|
| 142 |
filename = os.path.basename(result_path)
|
|
|
|
| 143 |
return FileResponse(result_path, media_type=media_type, filename=filename)
|
| 144 |
|
| 145 |
finally:
|
| 146 |
-
# Clean up temp dir
|
| 147 |
shutil.rmtree(temp_dir)
|
| 148 |
-
logger.info("Temporary files cleaned up.")
|
| 149 |
|
| 150 |
-
#
|
| 151 |
def log_api_url():
|
| 152 |
url = os.getenv("SPACE_PUBLIC_URL")
|
| 153 |
if url:
|
|
|
|
| 1 |
from fastapi import FastAPI, UploadFile, File, Form
|
| 2 |
+
from fastapi.responses import FileResponse
|
| 3 |
import tempfile
|
| 4 |
import shutil
|
| 5 |
import os
|
|
|
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
| 21 |
+
# Safe audio clip loader
|
| 22 |
def safe_audio_clip(path):
|
| 23 |
+
try:
|
| 24 |
+
clip = AudioFileClip(path)
|
| 25 |
+
if clip.reader is None or clip.duration is None or clip.duration <= 0:
|
| 26 |
+
clip.close()
|
| 27 |
+
raise ValueError(f"Invalid or empty audio file: {os.path.basename(path)}")
|
| 28 |
+
return clip
|
| 29 |
+
except Exception as e:
|
| 30 |
+
raise ValueError(f"Failed to load audio file '{os.path.basename(path)}': {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
def merge_videos_and_audios(
|
| 33 |
video_files, audio_files, orig_vol=1.0, music_vol=0.5, temp_dir=None
|
|
|
|
| 36 |
output_path = os.path.join(
|
| 37 |
temp_dir, "merged_output.mp4" if video_files else "merged_output.mp3"
|
| 38 |
)
|
| 39 |
+
|
| 40 |
# If no videos, just concatenate audios
|
| 41 |
if not video_files and audio_files:
|
| 42 |
+
audio_clips = []
|
| 43 |
+
for a in audio_files:
|
| 44 |
+
try:
|
| 45 |
+
audio_clip = safe_audio_clip(a)
|
| 46 |
+
audio_clips.append(audio_clip)
|
| 47 |
+
except Exception as e:
|
| 48 |
+
logger.warning(f"Skipping invalid audio file: {a} → {str(e)}")
|
| 49 |
+
|
| 50 |
+
if not audio_clips:
|
| 51 |
+
raise ValueError("No valid audio files to merge.")
|
| 52 |
+
|
| 53 |
final_audio = concatenate_audioclips(audio_clips)
|
| 54 |
final_audio.write_audiofile(output_path)
|
| 55 |
for clip in audio_clips:
|
| 56 |
clip.close()
|
| 57 |
final_audio.close()
|
|
|
|
| 58 |
return output_path
|
| 59 |
|
| 60 |
# If videos are present:
|
| 61 |
+
video_clips = [VideoFileClip(v) for v in video_files]
|
|
|
|
| 62 |
final_video = concatenate_videoclips(video_clips, method="compose")
|
| 63 |
+
|
| 64 |
if audio_files:
|
| 65 |
+
audio_clips = []
|
| 66 |
+
for a in audio_files:
|
| 67 |
+
try:
|
| 68 |
+
audio_clip = safe_audio_clip(a)
|
| 69 |
+
audio_clips.append(audio_clip)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
logger.warning(f"Skipping invalid audio file: {a} → {str(e)}")
|
| 72 |
+
|
| 73 |
+
if audio_clips:
|
| 74 |
+
final_audio = concatenate_audioclips(audio_clips).volumex(music_vol)
|
| 75 |
+
|
| 76 |
+
original_audio = (
|
| 77 |
+
final_video.audio.volumex(orig_vol)
|
| 78 |
+
if final_video.audio is not None
|
| 79 |
+
else None
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
if original_audio:
|
| 83 |
+
composite_audio = CompositeAudioClip([original_audio, final_audio])
|
| 84 |
+
else:
|
| 85 |
+
composite_audio = final_audio
|
| 86 |
+
|
| 87 |
+
final_video = final_video.set_audio(composite_audio)
|
| 88 |
+
|
| 89 |
+
for clip in audio_clips:
|
| 90 |
+
clip.close()
|
| 91 |
else:
|
| 92 |
+
logger.warning("No valid audio files found. Using only video audio (if present).")
|
| 93 |
+
if final_video.audio is not None:
|
| 94 |
+
final_video = final_video.volumex(orig_vol)
|
| 95 |
|
|
|
|
|
|
|
|
|
|
| 96 |
else:
|
| 97 |
+
# No audio files provided
|
| 98 |
if final_video.audio is not None:
|
| 99 |
final_video = final_video.volumex(orig_vol)
|
|
|
|
| 100 |
|
|
|
|
| 101 |
final_video.write_videofile(output_path, codec="libx264", audio_codec="aac")
|
| 102 |
+
|
| 103 |
for clip in video_clips:
|
| 104 |
clip.close()
|
| 105 |
final_video.close()
|
| 106 |
+
|
| 107 |
return output_path
|
| 108 |
|
| 109 |
except Exception as e:
|
|
|
|
| 111 |
logger.error(error_msg)
|
| 112 |
return error_msg
|
| 113 |
|
|
|
|
| 114 |
app = FastAPI()
|
| 115 |
|
| 116 |
@app.post("/merge")
|
|
|
|
| 121 |
):
|
| 122 |
temp_dir = tempfile.mkdtemp()
|
| 123 |
try:
|
|
|
|
| 124 |
saved_files = []
|
| 125 |
for uploaded_file in files:
|
| 126 |
file_path = os.path.join(temp_dir, uploaded_file.filename)
|
|
|
|
| 128 |
content = await uploaded_file.read()
|
| 129 |
out_file.write(content)
|
| 130 |
saved_files.append(file_path)
|
|
|
|
| 131 |
|
|
|
|
| 132 |
video_files = [f for f in saved_files if f.lower().endswith(".mp4")]
|
| 133 |
+
audio_files = [
|
| 134 |
+
f
|
| 135 |
+
for f in saved_files
|
| 136 |
+
if f.lower().endswith((".mp3", ".wav", ".aac", ".m4a", ".ogg"))
|
| 137 |
+
]
|
| 138 |
|
|
|
|
| 139 |
if len(saved_files) < 2:
|
| 140 |
+
return {"error": "Please upload at least 2 files (videos or audios)."}
|
|
|
|
|
|
|
|
|
|
| 141 |
|
|
|
|
| 142 |
result_path = merge_videos_and_audios(
|
| 143 |
video_files, audio_files, orig_vol, music_vol, temp_dir
|
| 144 |
)
|
| 145 |
|
|
|
|
| 146 |
if isinstance(result_path, str) and result_path.startswith("Error"):
|
| 147 |
+
return {"error": result_path}
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
+
media_type = (
|
| 150 |
+
"video/mp4" if result_path.lower().endswith(".mp4") else "audio/mpeg"
|
| 151 |
+
)
|
| 152 |
filename = os.path.basename(result_path)
|
| 153 |
+
|
| 154 |
return FileResponse(result_path, media_type=media_type, filename=filename)
|
| 155 |
|
| 156 |
finally:
|
|
|
|
| 157 |
shutil.rmtree(temp_dir)
|
|
|
|
| 158 |
|
| 159 |
+
# Optional: log space public URL
|
| 160 |
def log_api_url():
|
| 161 |
url = os.getenv("SPACE_PUBLIC_URL")
|
| 162 |
if url:
|