Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
import subprocess
|
| 4 |
+
import io
|
| 5 |
+
import os
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
app = FastAPI(title="FFmpeg API for n8n")
|
| 9 |
+
|
| 10 |
+
@app.get("/")
|
| 11 |
+
async def health_check():
|
| 12 |
+
return {"status": "online", "service": "FFmpeg Image Processor"}
|
| 13 |
+
|
| 14 |
+
@app.post("/process")
|
| 15 |
+
async def process_image(
|
| 16 |
+
file: Optional[UploadFile] = File(None),
|
| 17 |
+
url: Optional[str] = Form(None),
|
| 18 |
+
options: Optional[str] = Form("-vf scale=800:-1") # 默认缩小到800宽
|
| 19 |
+
):
|
| 20 |
+
"""
|
| 21 |
+
支持两种输入方式:
|
| 22 |
+
1. file: 上传二进制图片文件
|
| 23 |
+
2. url: 远程图片地址
|
| 24 |
+
"""
|
| 25 |
+
input_source = ""
|
| 26 |
+
input_data = None
|
| 27 |
+
|
| 28 |
+
if file:
|
| 29 |
+
input_data = await file.read()
|
| 30 |
+
input_source = "pipe:0"
|
| 31 |
+
elif url:
|
| 32 |
+
input_source = url
|
| 33 |
+
else:
|
| 34 |
+
raise HTTPException(status_code=400, detail="需提供 file 或 url 参数")
|
| 35 |
+
|
| 36 |
+
# 构建命令
|
| 37 |
+
# 默认输出为 .jpg 格式,你可以根据需要调整
|
| 38 |
+
command = [
|
| 39 |
+
'ffmpeg',
|
| 40 |
+
'-i', input_source,
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
# 解析 options 参数并加入命令
|
| 44 |
+
if options:
|
| 45 |
+
command.extend(options.split())
|
| 46 |
+
|
| 47 |
+
# 强制输出为图像流
|
| 48 |
+
command.extend(['-f', 'image2', 'pipe:1'])
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
process = subprocess.Popen(
|
| 52 |
+
command,
|
| 53 |
+
stdin=subprocess.PIPE if input_data else None,
|
| 54 |
+
stdout=subprocess.PIPE,
|
| 55 |
+
stderr=subprocess.PIPE
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
out, err = process.communicate(input=input_data)
|
| 59 |
+
|
| 60 |
+
if process.returncode != 0:
|
| 61 |
+
return {"error": err.decode()}
|
| 62 |
+
|
| 63 |
+
return StreamingResponse(io.BytesIO(out), media_type="image/jpeg")
|
| 64 |
+
|
| 65 |
+
except Exception as e:
|
| 66 |
+
raise HTTPException(status_code=500, detail=str(e))
|