Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -10,7 +10,6 @@ import tempfile
|
|
10 |
|
11 |
app = FastAPI()
|
12 |
|
13 |
-
# Define permissões restritas para os arquivos criados
|
14 |
os.umask(0o077)
|
15 |
|
16 |
def detect_product_in_frame(frame):
|
@@ -18,23 +17,25 @@ def detect_product_in_frame(frame):
|
|
18 |
|
19 |
@app.post("/process_video/")
|
20 |
async def process_video(file: UploadFile = File(...)):
|
21 |
-
# Cria um diretório temporário exclusivo para a requisição
|
22 |
temp_dir = tempfile.mkdtemp()
|
23 |
input_filename = os.path.join(temp_dir, f"input_{uuid.uuid4()}.mp4")
|
24 |
output_filename = os.path.join(temp_dir, f"output_{uuid.uuid4()}.mp4")
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
29 |
|
30 |
cap = cv2.VideoCapture(input_filename)
|
31 |
success, frame = cap.read()
|
|
|
32 |
if not success:
|
33 |
shutil.rmtree(temp_dir)
|
34 |
return {"error": "Não foi possível ler o vídeo."}
|
35 |
|
36 |
roi_box = detect_product_in_frame(frame)
|
37 |
-
cap.release()
|
38 |
|
39 |
if roi_box:
|
40 |
x, y, w, h = roi_box
|
@@ -46,24 +47,26 @@ async def process_video(file: UploadFile = File(...)):
|
|
46 |
output_filename
|
47 |
]
|
48 |
try:
|
49 |
-
subprocess.run(crop_cmd, check=True)
|
50 |
-
|
|
|
|
|
51 |
shutil.rmtree(temp_dir)
|
52 |
-
return {"error": "Erro ao processar o vídeo com FFmpeg."}
|
|
|
|
|
53 |
|
54 |
-
# Verifica se o arquivo de saída foi criado e prepara a resposta
|
55 |
if os.path.exists(output_filename):
|
56 |
response = FileResponse(output_filename, media_type="video/mp4", filename="cropped_video.mp4")
|
57 |
response.headers["X-Delete-Dir"] = temp_dir
|
58 |
return response
|
59 |
else:
|
60 |
shutil.rmtree(temp_dir)
|
61 |
-
return {"error": "O arquivo de saída não foi gerado."}
|
62 |
else:
|
63 |
shutil.rmtree(temp_dir)
|
64 |
return {"error": "Não foi possível detectar o produto para realizar o crop."}
|
65 |
|
66 |
-
# Middleware para limpar o diretório temporário após a resposta
|
67 |
class CleanupMiddleware(BaseHTTPMiddleware):
|
68 |
async def dispatch(self, request, call_next):
|
69 |
response = await call_next(request)
|
|
|
10 |
|
11 |
app = FastAPI()
|
12 |
|
|
|
13 |
os.umask(0o077)
|
14 |
|
15 |
def detect_product_in_frame(frame):
|
|
|
17 |
|
18 |
@app.post("/process_video/")
|
19 |
async def process_video(file: UploadFile = File(...)):
|
|
|
20 |
temp_dir = tempfile.mkdtemp()
|
21 |
input_filename = os.path.join(temp_dir, f"input_{uuid.uuid4()}.mp4")
|
22 |
output_filename = os.path.join(temp_dir, f"output_{uuid.uuid4()}.mp4")
|
23 |
|
24 |
+
try:
|
25 |
+
with open(input_filename, "wb") as f:
|
26 |
+
f.write(await file.read())
|
27 |
+
except Exception as e:
|
28 |
+
shutil.rmtree(temp_dir)
|
29 |
+
return {"error": f"Erro ao salvar o vídeo de entrada: {str(e)}"}
|
30 |
|
31 |
cap = cv2.VideoCapture(input_filename)
|
32 |
success, frame = cap.read()
|
33 |
+
cap.release()
|
34 |
if not success:
|
35 |
shutil.rmtree(temp_dir)
|
36 |
return {"error": "Não foi possível ler o vídeo."}
|
37 |
|
38 |
roi_box = detect_product_in_frame(frame)
|
|
|
39 |
|
40 |
if roi_box:
|
41 |
x, y, w, h = roi_box
|
|
|
47 |
output_filename
|
48 |
]
|
49 |
try:
|
50 |
+
result = subprocess.run(crop_cmd, check=True, capture_output=True, text=True)
|
51 |
+
print("FFmpeg output:", result.stdout)
|
52 |
+
print("FFmpeg error (if any):", result.stderr)
|
53 |
+
except subprocess.CalledProcessError as e:
|
54 |
shutil.rmtree(temp_dir)
|
55 |
+
return {"error": f"Erro ao processar o vídeo com FFmpeg: {e.stderr}"}
|
56 |
+
|
57 |
+
os.remove(input_filename)
|
58 |
|
|
|
59 |
if os.path.exists(output_filename):
|
60 |
response = FileResponse(output_filename, media_type="video/mp4", filename="cropped_video.mp4")
|
61 |
response.headers["X-Delete-Dir"] = temp_dir
|
62 |
return response
|
63 |
else:
|
64 |
shutil.rmtree(temp_dir)
|
65 |
+
return {"error": "O arquivo de saída não foi gerado pelo FFmpeg."}
|
66 |
else:
|
67 |
shutil.rmtree(temp_dir)
|
68 |
return {"error": "Não foi possível detectar o produto para realizar o crop."}
|
69 |
|
|
|
70 |
class CleanupMiddleware(BaseHTTPMiddleware):
|
71 |
async def dispatch(self, request, call_next):
|
72 |
response = await call_next(request)
|