Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
import tempfile
|
| 4 |
+
import subprocess
|
| 5 |
+
import os
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
def process_video(input_bytes, speed=1.5):
|
| 11 |
+
"""
|
| 12 |
+
Process video to change playback speed and compress.
|
| 13 |
+
"""
|
| 14 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_input:
|
| 15 |
+
tmp_input.write(input_bytes)
|
| 16 |
+
input_path = tmp_input.name
|
| 17 |
+
|
| 18 |
+
output_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
|
| 19 |
+
|
| 20 |
+
video_speed = 1 / speed
|
| 21 |
+
audio_speed = speed
|
| 22 |
+
|
| 23 |
+
cmd = [
|
| 24 |
+
"ffmpeg", "-i", input_path,
|
| 25 |
+
"-filter_complex", f"[0:v]setpts={video_speed}*PTS[v];[0:a]atempo={audio_speed}[a]",
|
| 26 |
+
"-map", "[v]", "-map", "[a]",
|
| 27 |
+
"-vcodec", "libx264", "-crf", "28", "-preset", "fast",
|
| 28 |
+
"-movflags", "+faststart",
|
| 29 |
+
"-y", output_path
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
| 33 |
+
process.wait()
|
| 34 |
+
|
| 35 |
+
if process.returncode != 0:
|
| 36 |
+
os.remove(input_path)
|
| 37 |
+
os.remove(output_path)
|
| 38 |
+
raise HTTPException(status_code=500, detail="Video processing failed.")
|
| 39 |
+
|
| 40 |
+
with open(output_path, "rb") as f:
|
| 41 |
+
output_data = f.read()
|
| 42 |
+
|
| 43 |
+
os.remove(input_path)
|
| 44 |
+
os.remove(output_path)
|
| 45 |
+
|
| 46 |
+
return output_data
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@app.post("/process_video")
|
| 50 |
+
async def upload_video(file: UploadFile = File(...), speed: float = 1.5):
|
| 51 |
+
"""
|
| 52 |
+
Upload a video file and return processed video.
|
| 53 |
+
"""
|
| 54 |
+
if not (0.25 <= speed <= 4.0):
|
| 55 |
+
raise HTTPException(status_code=400, detail="Speed must be between 0.25x and 4x.")
|
| 56 |
+
|
| 57 |
+
video_bytes = await file.read()
|
| 58 |
+
processed_video = process_video(video_bytes, speed)
|
| 59 |
+
|
| 60 |
+
return StreamingResponse(
|
| 61 |
+
io.BytesIO(processed_video),
|
| 62 |
+
media_type="video/mp4",
|
| 63 |
+
headers={"Content-Disposition": "attachment; filename=processed_video.mp4"}
|
| 64 |
+
)
|