-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
795 lines (671 loc) · 29.2 KB
/
Copy pathserver.py
File metadata and controls
795 lines (671 loc) · 29.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# -*- coding: utf-8 -*-
"""
ImageStudio FastAPI 后端服务
============================
提供图像/视频处理的 REST API,涵盖格式转换、滤镜处理、转码、剪辑、抽帧等功能。
启动方式:
python server.py
uvicorn server:app --host 0.0.0.0 --port 8000 --reload
API 文档:
Swagger UI : http://localhost:8000/docs
ReDoc : http://localhost:8000/redoc
"""
import base64
import io
import logging
import os
import tempfile
import time
import uuid
from enum import Enum
from typing import List, Optional
import cv2
import numpy as np
import uvicorn
from fastapi import BackgroundTasks, FastAPI, File, Form, HTTPException, Query, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel, ConfigDict, Field
from image_processing import ImageProcessor
from video_processing import VideoProcessor
# ── 日志 ──────────────────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("api")
app = FastAPI(
title="ImageStudio API",
description="""
基于 OpenCV 的图像/视频处理服务。
## 功能概览
| 模块 | 功能 |
|------|------|
| **图像处理** | 灰度、二值化、模糊、边缘检测、角点检测、轮廓检测、图像分割、直方图均衡、亮度调整、缩放、旋转、水印 |
| **图像转换** | 格式转换 (JPG/PNG/WebP/BMP) |
| **视频处理** | 转码、剪辑、逐帧滤镜、抽帧、信息查看 |
| **批处理** | 批量图像处理,后台异步执行,状态查询 |
## 使用流程
1. 通过 `POST /api/v1/image/process` 处理单张图像
2. 通过 `POST /api/v1/image/batch` 提交批量任务
3. 通过 `GET /api/v1/tasks/{task_id}` 查询任务状态
4. 处理完成的文件通过 `GET /api/v1/tasks/{task_id}/download` 下载
""",
version="1.0.0",
contact={"name": "ImageStudio"},
)
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ── 支持的格式 & 操作 ─────────────────────────────────────
IMAGE_FORMATS = {"jpg": ".jpg", "jpeg": ".jpg", "png": ".png", "webp": ".webp", "bmp": ".bmp"}
VIDEO_FORMATS = {"mp4": ".mp4", "avi": ".avi", "mov": ".mov", "mkv": ".mkv"}
IMAGE_OPERATIONS = {
"gray": ("to_gray", []),
"binary": ("to_binary", ["threshold"]),
"gaussian_blur": ("gaussian_blur", ["kernel_size"]),
"median_blur": ("median_blur", ["kernel_size"]),
"edge_detect": ("edge_detect", ["low_threshold", "high_threshold"]),
"corner_detect": ("corner_detect", []),
"contours": ("find_contours", ["threshold"]),
"segment": ("segment_image", ["k"]),
"emboss": ("emboss_filter", []),
"sketch": ("sketch_filter", []),
"cartoon": ("cartoon_filter", []),
"vintage": ("vintage_filter", []),
"mosaic": ("mosaic_filter", ["block_size"]),
"histogram_equalize": ("histogram_equalize", []),
"brightness": ("adjust_brightness", ["value"]),
}
VIDEO_FILTERS = [
"gray", "binary", "gaussian_blur", "median_blur", "edge_detect",
"emboss", "sketch", "cartoon", "vintage", "mosaic", "histogram_equalize",
]
# ── 后台任务存储(简易内存存储,生产环境应使用 Redis/DB) ──
_task_store: dict = {}
# ═══════════════════════════════════════════════════════════
# Pydantic 模型
# ═══════════════════════════════════════════════════════════
class HealthResponse(BaseModel):
model_config = ConfigDict(json_schema_extra={"example": {"status": "ok", "service": "image-processor-backend", "version": "1.0.0"}})
status: str = "ok"
service: str = "image-processor-backend"
version: str = "1.0.0"
class ImageBase64Response(BaseModel):
"""Base64 编码的图像响应(便于 JSON 传输 / 前端直接展示)。"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"format": "png",
"data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk...",
"width": 800,
"height": 600,
}
}
)
format: str = Field("png", description="图像格式")
data: str = Field(..., description="Base64 编码的图像数据")
width: int = Field(..., description="图像宽度(像素)")
height: int = Field(..., description="图像高度(像素)")
class VideoInfoResponse(BaseModel):
"""视频信息响应。"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"width": 1920,
"height": 1080,
"fps": 30.0,
"frame_count": 900,
"duration_sec": 30.0,
"codec": "avc1",
}
}
)
width: int
height: int
fps: float
frame_count: int
duration_sec: float
codec: str
class TaskStatus(str, Enum):
pending = "pending"
processing = "processing"
completed = "completed"
failed = "failed"
class TaskResponse(BaseModel):
"""异步任务状态响应。"""
model_config = ConfigDict(
json_schema_extra={
"example": {
"task_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "processing",
"progress": {"processed": 5, "total": 10},
"result": None,
"error": None,
"created_at": "2026-08-03 10:00:00",
"updated_at": "2026-08-03 10:00:05",
}
}
)
task_id: str = Field(..., description="任务 ID")
status: TaskStatus = Field(..., description="任务状态")
progress: Optional[dict] = Field(None, description="进度信息")
result: Optional[dict] = Field(None, description="处理结果")
error: Optional[str] = Field(None, description="错误信息")
created_at: str = Field("", description="创建时间")
updated_at: str = Field("", description="更新时间")
class OperationInfo(BaseModel):
"""操作信息。"""
name: str
description: str
parameters: List[str]
class OperationsListResponse(BaseModel):
"""可用操作列表。"""
operations: List[OperationInfo]
class ErrorResponse(BaseModel):
"""统一错误响应。"""
error: str = Field(..., description="错误描述")
detail: Optional[str] = Field(None, description="详细信息")
# ═══════════════════════════════════════════════════════════
# 工具函数
# ═══════════════════════════════════════════════════════════
def read_image_from_bytes(data: bytes) -> np.ndarray:
"""从字节流解码图像。"""
img = cv2.imdecode(np.frombuffer(data, dtype=np.uint8), cv2.IMREAD_COLOR)
if img is None:
raise HTTPException(status_code=400, detail="无法解析上传的图像文件")
return img
def encode_image(img: np.ndarray, fmt: str = ".png") -> bytes:
"""图像编码为字节流。"""
ok, buf = cv2.imencode(fmt, img)
if not ok:
raise HTTPException(status_code=500, detail="图像编码失败")
return buf.tobytes()
def img_to_base64(img: np.ndarray) -> dict:
"""图像编码为 base64(JSON 传输)。"""
ok, buf = cv2.imencode(".png", img)
if not ok:
raise HTTPException(status_code=500, detail="图像编码失败")
h, w = img.shape[:2]
return {
"format": "png",
"data": base64.b64encode(buf.tobytes()).decode("ascii"),
"width": w,
"height": h,
}
def save_upload(upload: UploadFile) -> str:
"""保存上传文件到临时目录,返回路径。"""
suffix = os.path.splitext(upload.filename or "")[1] or ".bin"
fd, path = tempfile.mkstemp(suffix=suffix)
with os.fdopen(fd, "wb") as f:
f.write(upload.file.read())
return path
def file_response(data: bytes, media_type: str, filename: str) -> Response:
"""构造文件下载响应。"""
safe_name = filename.replace('"', '_').replace("\\", "_")
return Response(
content=data,
media_type=media_type,
headers={"Content-Disposition": f'attachment; filename="{safe_name}"'},
)
def read_and_remove(path: str) -> bytes:
"""读取文件内容并删除临时文件。"""
with open(path, "rb") as f:
data = f.read()
try:
os.remove(path)
except OSError:
pass
return data
# ═══════════════════════════════════════════════════════════
# 健康检查 & 信息接口
# ═══════════════════════════════════════════════════════════
@app.get(
"/api/v1/health",
response_model=HealthResponse,
tags=["系统"],
summary="健康检查",
)
def health():
"""服务健康检查,返回版本信息。"""
return {"status": "ok", "service": "image-processor-backend", "version": "1.0.0"}
@app.get(
"/api/v1/operations",
response_model=OperationsListResponse,
tags=["系统"],
summary="查看可用操作",
)
def list_operations():
"""返回所有支持的图像/视频处理操作列表。"""
ops = []
for name, (method, params) in IMAGE_OPERATIONS.items():
ops.append(OperationInfo(name=name, description=method, parameters=params))
return {"operations": ops}
# ═══════════════════════════════════════════════════════════
# 图像处理接口
# ═══════════════════════════════════════════════════════════
@app.post(
"/api/v1/image/process",
response_model=ImageBase64Response,
responses={400: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
tags=["图像处理"],
summary="单张图像处理",
description="对上传的图像应用指定的处理操作(灰度、模糊、边缘检测等),返回处理后的图像。",
)
def process_image(
file: UploadFile = File(..., description="上传的图像文件"),
operation: str = Form(..., description=f"操作名称,可选: {list(IMAGE_OPERATIONS)}"),
threshold: Optional[int] = Form(127, ge=0, le=255, description="二值化/轮廓阈值 (0-255)"),
kernel_size: Optional[int] = Form(5, ge=1, le=31, description="模糊核大小 (奇数, 1-31)"),
low_threshold: Optional[int] = Form(50, ge=0, le=255, description="Canny 低阈值"),
high_threshold: Optional[int] = Form(150, ge=0, le=255, description="Canny 高阈值"),
k: Optional[int] = Form(4, ge=2, le=16, description="K-means 聚类数"),
block_size: Optional[int] = Form(15, ge=2, le=100, description="马赛克块大小"),
value: Optional[int] = Form(0, ge=-100, le=100, description="亮度调整值"),
):
if operation not in IMAGE_OPERATIONS:
raise HTTPException(
status_code=400,
detail=f"不支持的操作: {operation},可用: {list(IMAGE_OPERATIONS)}",
)
log.info(f"图像处理请求: operation={operation}, file={file.filename}")
try:
processor = ImageProcessor()
processor.image = read_image_from_bytes(file.file.read())
processor.processed_image = processor.image.copy()
method_name, _ = IMAGE_OPERATIONS[operation]
method = getattr(processor, method_name)
kwargs = {
"threshold": threshold,
"kernel_size": kernel_size,
"low_threshold": low_threshold,
"high_threshold": high_threshold,
"k": k,
"block_size": block_size,
"value": value,
}
import inspect
sig = inspect.signature(method)
filtered = {k: v for k, v in kwargs.items() if k in sig.parameters}
result = method(**filtered)
if isinstance(result, tuple):
result = result[0]
if result is None:
raise HTTPException(status_code=500, detail="图像处理返回空结果")
log.info(f"图像处理成功: {operation}")
return img_to_base64(result)
except HTTPException:
raise
except Exception as e:
log.exception(f"图像处理异常: {e}")
raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
@app.post(
"/api/v1/image/resize",
response_model=ImageBase64Response,
tags=["图像处理"],
summary="图像缩放",
description="按指定宽度或高度等比缩放图像(至少提供一个维度)。",
)
def resize_image(
file: UploadFile = File(..., description="上传的图像文件"),
width: Optional[int] = Form(None, ge=1, le=8000, description="目标宽度(像素)"),
height: Optional[int] = Form(None, ge=1, le=8000, description="目标高度(像素)"),
keep_aspect_ratio: bool = Form(True, description="是否保持宽高比"),
):
if not width and not height:
raise HTTPException(status_code=400, detail="至少指定 width 或 height 中的一个")
try:
img = read_image_from_bytes(file.file.read())
h, w = img.shape[:2]
if keep_aspect_ratio:
if width and height:
# 同时指定:按较小的缩放比例适配
ratio = min(width / w, height / h)
elif width:
ratio = width / w
else:
ratio = height / h
new_size = (int(w * ratio), int(h * ratio))
else:
new_size = (width or w, height or h)
resized = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA if ratio < 1 else cv2.INTER_CUBIC)
log.info(f"图像缩放: {w}×{h} → {new_size[0]}×{new_size[1]}")
return img_to_base64(resized)
except HTTPException:
raise
except Exception as e:
log.exception(f"缩放失败: {e}")
raise HTTPException(status_code=500, detail=f"缩放失败: {str(e)}")
@app.post(
"/api/v1/image/rotate",
response_model=ImageBase64Response,
tags=["图像处理"],
summary="图像旋转",
description="旋转图像指定角度。",
)
def rotate_image(
file: UploadFile = File(..., description="上传的图像文件"),
angle: float = Form(..., description="旋转角度(顺时针,度数)"),
):
try:
img = read_image_from_bytes(file.file.read())
h, w = img.shape[:2]
center = (w // 2, h // 2)
matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
# 计算旋转后的边界
cos = abs(matrix[0, 0])
sin = abs(matrix[0, 1])
new_w = int(h * sin + w * cos)
new_h = int(h * cos + w * sin)
matrix[0, 2] += new_w / 2 - center[0]
matrix[1, 2] += new_h / 2 - center[1]
rotated = cv2.warpAffine(img, matrix, (new_w, new_h),
borderValue=(255, 255, 255))
log.info(f"图像旋转: {angle}°")
return img_to_base64(rotated)
except HTTPException:
raise
except Exception as e:
log.exception(f"旋转失败: {e}")
raise HTTPException(status_code=500, detail=f"旋转失败: {str(e)}")
@app.post(
"/api/v1/image/watermark",
response_model=ImageBase64Response,
tags=["图像处理"],
summary="添加文字水印",
description="在图像右下角添加半透明文字水印。",
)
def add_watermark(
file: UploadFile = File(..., description="上传的图像文件"),
text: str = Form(..., description="水印文字"),
font_scale: float = Form(1.0, ge=0.5, le=5.0, description="字体大小"),
opacity: float = Form(0.5, ge=0.1, le=1.0, description="透明度 (0.1-1.0)"),
):
try:
img = read_image_from_bytes(file.file.read())
overlay = img.copy()
h, w = img.shape[:2]
font = cv2.FONT_HERSHEY_SIMPLEX
(tw, th), baseline = cv2.getTextSize(text, font, font_scale, 2)
# 右下角定位,留 20px 边距
pos_x = w - tw - 20
pos_y = h - 20
cv2.putText(overlay, text, (pos_x, pos_y), font, font_scale,
(255, 255, 255), 2, cv2.LINE_AA)
result = cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0)
log.info(f"水印添加: '{text}'")
return img_to_base64(result)
except HTTPException:
raise
except Exception as e:
log.exception(f"水印添加失败: {e}")
raise HTTPException(status_code=500, detail=f"水印添加失败: {str(e)}")
@app.post(
"/api/v1/image/convert",
tags=["图像处理"],
summary="图像格式转换",
description="将图像转换为指定格式并下载。",
responses={
200: {"description": "转换后的图像文件", "content": {"image/*": {}}},
400: {"model": ErrorResponse},
},
)
def convert_image(
file: UploadFile = File(..., description="上传的图像文件"),
target_format: str = Form(..., description="目标格式: jpg/png/webp/bmp"),
):
target = target_format.lower()
if target not in IMAGE_FORMATS:
raise HTTPException(
status_code=400,
detail=f"不支持的格式: {target_format},可用: {list(IMAGE_FORMATS)}",
)
try:
img = read_image_from_bytes(file.file.read())
fmt = IMAGE_FORMATS[target]
data = encode_image(img, fmt)
mime = "image/jpeg" if target in ("jpg", "jpeg") else f"image/{target}"
return file_response(data, mime, f"output{fmt}")
except HTTPException:
raise
except Exception as e:
log.exception(f"格式转换失败: {e}")
raise HTTPException(status_code=500, detail=f"格式转换失败: {str(e)}")
# ═══════════════════════════════════════════════════════════
# 批量处理 & 异步任务
# ═══════════════════════════════════════════════════════════
@app.post(
"/api/v1/image/batch",
response_model=TaskResponse,
tags=["批量处理"],
summary="批量图像处理(异步)",
description="""
提交一个批量图像处理任务。支持同时上传多张图片,统一应用同一操作。
任务在后台执行,通过 `GET /api/v1/tasks/{task_id}` 查询进度,
完成后通过 `GET /api/v1/tasks/{task_id}/download` 下载打包结果。
""",
)
async def batch_process_images(
background_tasks: BackgroundTasks,
files: List[UploadFile] = File(..., description="上传的图像文件(可多张)"),
operation: str = Form(..., description=f"操作名称,可选: {list(IMAGE_OPERATIONS)}"),
threshold: Optional[int] = Form(127, ge=0, le=255),
kernel_size: Optional[int] = Form(5, ge=1, le=31),
):
if operation not in IMAGE_OPERATIONS:
raise HTTPException(
status_code=400,
detail=f"不支持的操作: {operation},可用: {list(IMAGE_OPERATIONS)}",
)
if not files:
raise HTTPException(status_code=400, detail="请至少上传一个文件")
task_id = str(uuid.uuid4())
now = time.strftime("%Y-%m-%d %H:%M:%S")
_task_store[task_id] = {
"task_id": task_id,
"status": "pending",
"progress": {"processed": 0, "total": len(files)},
"result": None,
"error": None,
"created_at": now,
"updated_at": now,
# 内部数据
"_files": [(f.filename, await f.read()) for f in files],
"_operation": operation,
"_params": {"threshold": threshold, "kernel_size": kernel_size},
}
background_tasks.add_task(_execute_batch_task, task_id)
log.info(f"批量任务已创建: {task_id}, {len(files)} 个文件, operation={operation}")
return _task_store[task_id]
def _execute_batch_task(task_id: str):
"""后台执行批量处理任务。"""
task = _task_store.get(task_id)
if not task:
return
task["status"] = "processing"
task["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
results = []
failures = []
total = task["progress"]["total"]
try:
method_name, _ = IMAGE_OPERATIONS[task["_operation"]]
kwargs = task["_params"]
for idx, (filename, data) in enumerate(task["_files"]):
task["progress"]["processed"] = idx + 1
task["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
try:
processor = ImageProcessor()
processor.image = read_image_from_bytes(data)
processor.processed_image = processor.image.copy()
method = getattr(processor, method_name)
result = method(**kwargs)
if isinstance(result, tuple):
result = result[0]
if result is not None:
encoded = base64.b64encode(encode_image(result)).decode("ascii")
results.append({
"filename": filename,
"format": "png",
"data": encoded,
"width": result.shape[1],
"height": result.shape[0],
})
else:
failures.append({"filename": filename, "reason": "处理返回空结果"})
except Exception as e:
failures.append({"filename": filename, "reason": str(e)})
task["status"] = "completed"
task["result"] = {
"success": len(results),
"failed": len(failures),
"items": results,
"failures": failures,
}
log.info(f"批量任务完成: {task_id}, {len(results)}/{total} 成功")
except Exception as e:
task["status"] = "failed"
task["error"] = str(e)
log.exception(f"批量任务失败: {task_id}")
@app.get(
"/api/v1/tasks/{task_id}",
response_model=TaskResponse,
tags=["批量处理"],
summary="查询任务状态",
responses={404: {"model": ErrorResponse}},
)
def get_task_status(task_id: str):
"""查询异步任务的处理进度和结果。"""
task = _task_store.get(task_id)
if not task:
raise HTTPException(status_code=404, detail=f"任务不存在: {task_id}")
return {
"task_id": task["task_id"],
"status": task["status"],
"progress": task["progress"],
"result": task["result"] if task["status"] == "completed" else None,
"error": task["error"],
"created_at": task["created_at"],
"updated_at": task["updated_at"],
}
@app.get(
"/api/v1/tasks/{task_id}/download",
tags=["批量处理"],
summary="下载批量处理结果",
description="将任务结果打包为 ZIP 文件下载。",
responses={404: {"model": ErrorResponse}},
)
def download_task_result(task_id: str):
"""下载批量任务的打包结果(ZIP)。"""
import zipfile
task = _task_store.get(task_id)
if not task:
raise HTTPException(status_code=404, detail=f"任务不存在: {task_id}")
if task["status"] != "completed":
raise HTTPException(status_code=400, detail=f"任务尚未完成,当前状态: {task['status']}")
if not task["result"] or not task["result"]["items"]:
raise HTTPException(status_code=400, detail="任务无可用结果")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
for item in task["result"]["items"]:
img_data = base64.b64decode(item["data"])
zf.writestr(item["filename"], img_data)
buf.seek(0)
return Response(
content=buf.getvalue(),
media_type="application/zip",
headers={"Content-Disposition": f'attachment; filename="batch_{task_id[:8]}.zip"'},
)
# ═══════════════════════════════════════════════════════════
# 视频处理接口
# ═══════════════════════════════════════════════════════════
@app.post(
"/api/v1/video/process",
tags=["视频处理"],
summary="视频处理",
description="""
视频处理统一入口。支持以下操作:
- **transcode**: 转码 / 格式转换
- **trim**: 按时间区间剪辑
- **filter**: 逐帧应用滤镜
- **extract_frames**: 指定时间点抽帧
- **info**: 查看视频信息
""",
)
async def process_video(
file: UploadFile = File(..., description="上传的视频文件"),
operation: str = Form(..., description="操作: transcode/trim/filter/extract_frames/info"),
output_format: Optional[str] = Form("mp4", description="转码目标格式"),
start_sec: Optional[float] = Form(0.0, description="剪辑开始时间(秒)"),
end_sec: Optional[float] = Form(0.0, description="剪辑结束时间(秒),0=到末尾"),
filter_name: Optional[str] = Form("gray", description="滤镜名称"),
timestamps: Optional[str] = Form("", description="抽帧时间点(秒),逗号分隔"),
):
input_path = save_upload(file)
try:
vp = VideoProcessor()
if operation == "info":
return vp.get_info(input_path)
elif operation == "transcode":
if output_format not in VIDEO_FORMATS:
raise HTTPException(
status_code=400,
detail=f"不支持的格式: {output_format},可用: {list(VIDEO_FORMATS)}",
)
out_path, info = vp.transcode(input_path, output_format)
return file_response(read_and_remove(out_path), "video/mp4", os.path.basename(out_path))
elif operation == "trim":
out_path = vp.trim(input_path, start_sec, end_sec)
return file_response(read_and_remove(out_path), "video/mp4", os.path.basename(out_path))
elif operation == "filter":
if filter_name not in VIDEO_FILTERS:
raise HTTPException(
status_code=400,
detail=f"不支持的滤镜: {filter_name},可用: {VIDEO_FILTERS}",
)
out_path = vp.apply_filter(input_path, filter_name)
return file_response(read_and_remove(out_path), "video/mp4", os.path.basename(out_path))
elif operation == "extract_frames":
ts_list = [float(t) for t in timestamps.split(",") if t.strip()]
if not ts_list:
raise HTTPException(status_code=400, detail="请提供时间点参数 timestamps,如 0.5,1.5,2.5")
frames = vp.extract_frames(input_path, ts_list)
# 多帧打包为 ZIP
import zipfile
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
for ts, frame in frames:
ok, frame_data = cv2.imencode(".jpg", frame)
if ok:
zf.writestr(f"frame_t{ts:.2f}s.jpg", frame_data.tobytes())
buf.seek(0)
return Response(
content=buf.getvalue(),
media_type="application/zip",
headers={"Content-Disposition": 'attachment; filename="frames.zip"'},
)
else:
raise HTTPException(
status_code=400,
detail=f"不支持的操作: {operation},可用: transcode/trim/filter/extract_frames/info",
)
except HTTPException:
raise
except Exception as e:
log.exception(f"视频处理异常: {e}")
raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
finally:
if os.path.exists(input_path):
os.remove(input_path)
# ═══════════════════════════════════════════════════════════
# 启动入口
# ═══════════════════════════════════════════════════════════
if __name__ == "__main__":
log.info("ImageStudio API 启动: http://0.0.0.0:8000")
log.info("Swagger 文档: http://localhost:8000/docs")
uvicorn.run(app, host="0.0.0.0", port=8000)