m-crop / main.py
ricardo238costa's picture
Update main.py
799ee9e verified
raw
history blame
2.62 kB
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import FileResponse
from starlette.middleware.base import BaseHTTPMiddleware
import cv2
import subprocess
import uuid
import os
import shutil
import tempfile
app = FastAPI()
os.umask(0o077)
def detect_product_in_frame(frame):
return (100, 50, 400, 400)
@app.post("/process_video/")
async def process_video(file: UploadFile = File(...)):
temp_dir = tempfile.mkdtemp()
input_filename = os.path.join(temp_dir, f"input_{uuid.uuid4()}.mp4")
output_filename = os.path.join(temp_dir, f"output_{uuid.uuid4()}.mp4")
try:
with open(input_filename, "wb") as f:
f.write(await file.read())
except Exception as e:
shutil.rmtree(temp_dir)
return {"error": f"Erro ao salvar o vídeo de entrada: {str(e)}"}
cap = cv2.VideoCapture(input_filename)
success, frame = cap.read()
cap.release()
if not success:
shutil.rmtree(temp_dir)
return {"error": "Não foi possível ler o vídeo."}
roi_box = detect_product_in_frame(frame)
if roi_box:
x, y, w, h = roi_box
crop_cmd = [
'ffmpeg',
'-i', input_filename,
'-vf', f"crop={w}:{h}:{x}:{y}",
'-c:a', 'copy',
output_filename
]
try:
result = subprocess.run(crop_cmd, check=True, capture_output=True, text=True)
print("FFmpeg output:", result.stdout)
print("FFmpeg error (if any):", result.stderr)
except subprocess.CalledProcessError as e:
shutil.rmtree(temp_dir)
return {"error": f"Erro ao processar o vídeo com FFmpeg: {e.stderr}"}
os.remove(input_filename)
if os.path.exists(output_filename):
response = FileResponse(output_filename, media_type="video/mp4", filename="cropped_video.mp4")
response.headers["X-Delete-Dir"] = temp_dir
return response
else:
shutil.rmtree(temp_dir)
return {"error": "O arquivo de saída não foi gerado pelo FFmpeg."}
else:
shutil.rmtree(temp_dir)
return {"error": "Não foi possível detectar o produto para realizar o crop."}
class CleanupMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
temp_dir_to_delete = response.headers.get("X-Delete-Dir")
if temp_dir_to_delete and os.path.exists(temp_dir_to_delete):
shutil.rmtree(temp_dir_to_delete)
return response
app.add_middleware(CleanupMiddleware)