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,6 +18,20 @@ import numpy as np
|
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
def merge_videos_and_audios(
|
| 22 |
video_files, audio_files, orig_vol=1.0, music_vol=0.5, temp_dir=None
|
| 23 |
):
|
|
@@ -25,22 +39,30 @@ def merge_videos_and_audios(
|
|
| 25 |
output_path = os.path.join(
|
| 26 |
temp_dir, "merged_output.mp4" if video_files else "merged_output.mp3"
|
| 27 |
)
|
|
|
|
| 28 |
# If no videos, just concatenate audios
|
| 29 |
if not video_files and audio_files:
|
| 30 |
-
|
|
|
|
| 31 |
final_audio = concatenate_audioclips(audio_clips)
|
| 32 |
final_audio.write_audiofile(output_path)
|
| 33 |
for clip in audio_clips:
|
| 34 |
clip.close()
|
| 35 |
final_audio.close()
|
|
|
|
| 36 |
return output_path
|
|
|
|
| 37 |
# If videos are present:
|
| 38 |
-
|
|
|
|
| 39 |
final_video = concatenate_videoclips(video_clips, method="compose")
|
|
|
|
| 40 |
if audio_files:
|
| 41 |
-
|
|
|
|
| 42 |
final_audio = concatenate_audioclips(audio_clips).volumex(music_vol)
|
| 43 |
-
|
|
|
|
| 44 |
original_audio = (
|
| 45 |
final_video.audio.volumex(orig_vol) if final_video.audio is not None else None
|
| 46 |
)
|
|
@@ -48,24 +70,30 @@ def merge_videos_and_audios(
|
|
| 48 |
composite_audio = CompositeAudioClip([original_audio, final_audio])
|
| 49 |
else:
|
| 50 |
composite_audio = final_audio
|
|
|
|
| 51 |
final_video = final_video.set_audio(composite_audio)
|
| 52 |
for clip in audio_clips:
|
| 53 |
clip.close()
|
| 54 |
else:
|
| 55 |
-
#
|
| 56 |
if final_video.audio is not None:
|
| 57 |
final_video = final_video.volumex(orig_vol)
|
| 58 |
-
# else no audio
|
|
|
|
|
|
|
| 59 |
final_video.write_videofile(output_path, codec="libx264", audio_codec="aac")
|
| 60 |
for clip in video_clips:
|
| 61 |
clip.close()
|
| 62 |
final_video.close()
|
|
|
|
| 63 |
return output_path
|
|
|
|
| 64 |
except Exception as e:
|
| 65 |
error_msg = f"Error during merge: {str(e)}\n{traceback.format_exc()}"
|
| 66 |
logger.error(error_msg)
|
| 67 |
return error_msg
|
| 68 |
|
|
|
|
| 69 |
app = FastAPI()
|
| 70 |
|
| 71 |
@app.post("/merge")
|
|
@@ -76,6 +104,7 @@ async def merge_endpoint(
|
|
| 76 |
):
|
| 77 |
temp_dir = tempfile.mkdtemp()
|
| 78 |
try:
|
|
|
|
| 79 |
saved_files = []
|
| 80 |
for uploaded_file in files:
|
| 81 |
file_path = os.path.join(temp_dir, uploaded_file.filename)
|
|
@@ -83,21 +112,42 @@ async def merge_endpoint(
|
|
| 83 |
content = await uploaded_file.read()
|
| 84 |
out_file.write(content)
|
| 85 |
saved_files.append(file_path)
|
|
|
|
|
|
|
|
|
|
| 86 |
video_files = [f for f in saved_files if f.lower().endswith(".mp4")]
|
| 87 |
audio_files = [f for f in saved_files if f.lower().endswith((".mp3", ".wav"))]
|
|
|
|
|
|
|
| 88 |
if len(saved_files) < 2:
|
| 89 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
result_path = merge_videos_and_audios(
|
| 91 |
video_files, audio_files, orig_vol, music_vol, temp_dir
|
| 92 |
)
|
|
|
|
|
|
|
| 93 |
if isinstance(result_path, str) and result_path.startswith("Error"):
|
| 94 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
media_type = "video/mp4" if result_path.lower().endswith(".mp4") else "audio/mpeg"
|
| 96 |
filename = os.path.basename(result_path)
|
| 97 |
return FileResponse(result_path, media_type=media_type, filename=filename)
|
|
|
|
| 98 |
finally:
|
|
|
|
| 99 |
shutil.rmtree(temp_dir)
|
|
|
|
| 100 |
|
|
|
|
| 101 |
def log_api_url():
|
| 102 |
url = os.getenv("SPACE_PUBLIC_URL")
|
| 103 |
if url:
|
|
@@ -105,4 +155,4 @@ def log_api_url():
|
|
| 105 |
else:
|
| 106 |
logger.info("SPACE_PUBLIC_URL environment variable not found")
|
| 107 |
|
| 108 |
-
log_api_url()
|
|
|
|
| 1 |
from fastapi import FastAPI, UploadFile, File, Form
|
| 2 |
+
from fastapi.responses import FileResponse, JSONResponse
|
| 3 |
import tempfile
|
| 4 |
import shutil
|
| 5 |
import os
|
|
|
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
| 21 |
+
def safe_audio_clip(path):
|
| 22 |
+
clip = AudioFileClip(path)
|
| 23 |
+
if clip.reader is None or clip.duration is None or clip.duration <= 0:
|
| 24 |
+
clip.close()
|
| 25 |
+
raise ValueError(f"Invalid or empty audio file: {os.path.basename(path)}")
|
| 26 |
+
return clip
|
| 27 |
+
|
| 28 |
+
def safe_video_clip(path):
|
| 29 |
+
clip = VideoFileClip(path)
|
| 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
|
| 37 |
):
|
|
|
|
| 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 |
+
logger.info(f"Merging {len(audio_files)} audio files...")
|
| 46 |
+
audio_clips = [safe_audio_clip(a) for a in audio_files]
|
| 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 |
+
logger.info(f"Merging {len(video_files)} video files...")
|
| 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 |
+
logger.info(f"Merging {len(audio_files)} audio files into video...")
|
| 62 |
+
audio_clips = [safe_audio_clip(a) for a in audio_files]
|
| 63 |
final_audio = concatenate_audioclips(audio_clips).volumex(music_vol)
|
| 64 |
+
|
| 65 |
+
# Handle video original audio
|
| 66 |
original_audio = (
|
| 67 |
final_video.audio.volumex(orig_vol) if final_video.audio is not None else None
|
| 68 |
)
|
|
|
|
| 70 |
composite_audio = CompositeAudioClip([original_audio, final_audio])
|
| 71 |
else:
|
| 72 |
composite_audio = final_audio
|
| 73 |
+
|
| 74 |
final_video = final_video.set_audio(composite_audio)
|
| 75 |
for clip in audio_clips:
|
| 76 |
clip.close()
|
| 77 |
else:
|
| 78 |
+
# No audio uploaded → optionally adjust video audio volume
|
| 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 |
+
logger.info(f"Video merge complete: {output_path}")
|
| 89 |
return output_path
|
| 90 |
+
|
| 91 |
except Exception as e:
|
| 92 |
error_msg = f"Error during merge: {str(e)}\n{traceback.format_exc()}"
|
| 93 |
logger.error(error_msg)
|
| 94 |
return error_msg
|
| 95 |
|
| 96 |
+
# FastAPI app
|
| 97 |
app = FastAPI()
|
| 98 |
|
| 99 |
@app.post("/merge")
|
|
|
|
| 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 |
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 = [f for f in saved_files if f.lower().endswith((".mp3", ".wav"))]
|
| 120 |
+
|
| 121 |
+
# Require at least 2 files
|
| 122 |
if len(saved_files) < 2:
|
| 123 |
+
return JSONResponse(
|
| 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 JSONResponse(
|
| 136 |
+
status_code=500,
|
| 137 |
+
content={"error": result_path},
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# Return merged file
|
| 141 |
media_type = "video/mp4" if result_path.lower().endswith(".mp4") else "audio/mpeg"
|
| 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 |
+
# Log the API public URL for HuggingFace Spaces
|
| 151 |
def log_api_url():
|
| 152 |
url = os.getenv("SPACE_PUBLIC_URL")
|
| 153 |
if url:
|
|
|
|
| 155 |
else:
|
| 156 |
logger.info("SPACE_PUBLIC_URL environment variable not found")
|
| 157 |
|
| 158 |
+
log_api_url()
|