jcnok commited on
Commit
d34ee05
·
verified ·
1 Parent(s): 05b7e8a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -0
app.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException
2
+ from fastapi.responses import FileResponse, JSONResponse
3
+ import os
4
+ import asyncio
5
+ import uuid
6
+ import shutil
7
+
8
+ app = FastAPI()
9
+
10
+ TEMP_DIR = "/tmp/ffmpeg_processing"
11
+
12
+ @app.on_event("startup")
13
+ async def startup_event():
14
+ os.makedirs(TEMP_DIR, exist_ok=True)
15
+
16
+ @app.on_event("shutdown")
17
+ async def shutdown_event():
18
+ # Limpa o diretório temporário ao desligar, opcional para Spaces persistentes
19
+ shutil.rmtree(TEMP_DIR, ignore_errors=True)
20
+ os.makedirs(TEMP_DIR, exist_ok=True) # Recria para a próxima inicialização
21
+
22
+ @app.post("/process-video/")
23
+ async def process_video(
24
+ file: UploadFile = File(...),
25
+ output_filename: str = Form(...),
26
+ ffmpeg_command_args: str = Form(...)
27
+ ):
28
+ """
29
+ Processa um vídeo usando FFmpeg.
30
+ Espera um arquivo de vídeo e argumentos de comando FFmpeg.
31
+ """
32
+ unique_id = str(uuid.uuid4())
33
+ input_path = os.path.join(TEMP_DIR, f"{unique_id}_{file.filename}")
34
+ output_path = os.path.join(TEMP_DIR, f"{unique_id}_{output_filename}")
35
+
36
+ try:
37
+ # Salva o arquivo enviado
38
+ with open(input_path, "wb") as buffer:
39
+ shutil.copyfileobj(file.file, buffer)
40
+
41
+ # Monta o comando FFmpeg
42
+ # CUIDADO: ffmpeg_command_args deve ser sanitizado ou controlado no n8n
43
+ # para evitar injeção de comandos maliciosos.
44
+ command = f"ffmpeg -i {input_path} {ffmpeg_command_args} {output_path}"
45
+
46
+ # Executa o comando
47
+ process = await asyncio.create_subprocess_shell(
48
+ command,
49
+ stdout=asyncio.subprocess.PIPE,
50
+ stderr=asyncio.subprocess.PIPE
51
+ )
52
+ stdout, stderr = await process.communicate()
53
+
54
+ if process.returncode != 0:
55
+ print(f"FFmpeg Stdout: {stdout.decode()}")
56
+ print(f"FFmpeg Stderr: {stderr.decode()}")
57
+ raise HTTPException(status_code=500, detail=f"FFmpeg error: {stderr.decode()}")
58
+
59
+ # Retorna o arquivo processado
60
+ return FileResponse(
61
+ path=output_path,
62
+ filename=output_filename,
63
+ media_type="application/octet-stream" # ou o tipo MIME correto do seu output
64
+ )
65
+ except Exception as e:
66
+ raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
67
+ finally:
68
+ # Limpa os arquivos temporários
69
+ if os.path.exists(input_path):
70
+ os.remove(input_path)
71
+ if os.path.exists(output_path):
72
+ os.remove(output_path)
73
+
74
+ @app.post("/get-duration/")
75
+ async def get_duration(file: UploadFile = File(...)):
76
+ """
77
+ Obtém a duração de um arquivo de áudio/vídeo usando ffprobe.
78
+ """
79
+ unique_id = str(uuid.uuid4())
80
+ input_path = os.path.join(TEMP_DIR, f"{unique_id}_{file.filename}")
81
+
82
+ try:
83
+ with open(input_path, "wb") as buffer:
84
+ shutil.copyfileobj(file.file, buffer)
85
+
86
+ command = f"ffprobe -i {input_path} -show_entries format=duration -v quiet -of csv='p=0'"
87
+ process = await asyncio.create_subprocess_shell(
88
+ command,
89
+ stdout=asyncio.subprocess.PIPE,
90
+ stderr=asyncio.subprocess.PIPE
91
+ )
92
+ stdout, stderr = await process.communicate()
93
+
94
+ if process.returncode != 0:
95
+ print(f"FFprobe Stdout: {stdout.decode()}")
96
+ print(f"FFprobe Stderr: {stderr.decode()}")
97
+ raise HTTPException(status_code=500, detail=f"FFprobe error: {stderr.decode()}")
98
+
99
+ duration = float(stdout.decode().strip())
100
+ return JSONResponse(content={"duration_seconds": duration})
101
+
102
+ except ValueError:
103
+ raise HTTPException(status_code=400, detail="Could not parse duration from ffprobe output.")
104
+ except Exception as e:
105
+ raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
106
+ finally:
107
+ if os.path.exists(input_path):
108
+ os.remove(input_path)
109
+
110
+ @app.get("/")
111
+ async def read_root():
112
+ return {"message": "FFmpeg FastAPI service is running!"}