Files
meijiaka-zy/python-api/app/services/volcengine_mediakit_service.py
T

88 lines
2.4 KiB
Python

"""
火山引擎 MediaKit Service
=========================
通过 PlatformGateway 调用 MediaKit 第三方 API,自身负责:
- 参数校验
- 结果提取与格式化
"""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any
from app.ai.adapters.constants import Method
from app.platform_gateway import PlatformGateway
logger = logging.getLogger(__name__)
@dataclass
class RemoveBackgroundResult:
"""抠图结果"""
image_url: str = ""
raw: dict[str, Any] = field(default_factory=dict)
class VolcengineMediakitService:
"""火山引擎 MediaKit 服务封装"""
# 支持的场景
SUPPORTED_SCENES = {"general", "human", "product"}
def __init__(self, gateway: PlatformGateway):
self.gateway = gateway
async def remove_background(
self,
image_url: str,
scene: str = "human",
) -> RemoveBackgroundResult:
"""同步抠图
Args:
image_url: 原始图片 URL
scene: 场景类型,"general"(通用)、"human"(人物)或 "product"(商品)
Returns:
RemoveBackgroundResult: 包含抠图结果图片 URL
Raises:
ValueError: 参数校验失败
PlatformError: 平台调用失败
"""
if not image_url:
raise ValueError("image_url 不能为空")
if scene not in self.SUPPORTED_SCENES:
raise ValueError(f"不支持的场景: {scene},可选: {self.SUPPORTED_SCENES}")
# 人物/商品场景默认启用白色描边 + 裁剪背景
enable_contour = scene in ("human", "product")
payload = {
"image_url": image_url,
"scene": scene,
"need_contour": enable_contour,
"contour_color": "#FFFFFF",
"contour_size": 20,
"need_crop_background": enable_contour,
}
response = await self.gateway.call_sync(
platform="volcengine_mediakit",
method=Method.REMOVE_BACKGROUND,
payload=payload,
)
if not response.success:
raise RuntimeError(response.error_message or "抠图失败")
result_image_url = (response.data or {}).get("image_url", "")
return RemoveBackgroundResult(
image_url=result_image_url,
raw=response.data or {},
)