""" 计费工具模块 — 分辨率映射 + token/费用计算 Token 预估公式(火山官方):(宽 × 高 × 帧率 × 时长) / 1024 单价:元 / 百万 tokens """ from decimal import Decimal, ROUND_HALF_UP # 分辨率 → 像素映射(来自 Seedance 2.0 API 文档) RESOLUTION_MAP = { # 720p ('720p', '16:9'): (1280, 720), ('720p', '9:16'): (720, 1280), ('720p', '4:3'): (1112, 834), ('720p', '1:1'): (960, 960), ('720p', '3:4'): (834, 1112), ('720p', '21:9'): (1470, 630), # 480p ('480p', '16:9'): (864, 496), ('480p', '9:16'): (496, 864), ('480p', '4:3'): (752, 560), ('480p', '1:1'): (640, 640), ('480p', '3:4'): (560, 752), ('480p', '21:9'): (992, 432), } # 默认帧率 DEFAULT_FPS = 24 def get_resolution(aspect_ratio: str, tier: str = '720p') -> tuple: """根据宽高比和分辨率档位返回 (width, height) 像素值。""" return RESOLUTION_MAP.get((tier, aspect_ratio), (1280, 720)) def estimate_tokens(width: int, height: int, duration: int, fps: int = DEFAULT_FPS) -> int: """预估视频生成消耗的 tokens。""" return round(width * height * fps * duration / 1024) def calculate_cost(tokens: int, base_price, markup_percentage) -> Decimal: """计算用户费用(加价后)。 Args: tokens: 消耗的 tokens 数 base_price: 成本价(元/百万tokens) markup_percentage: 加价百分比,如 20 表示 20% Returns: Decimal: 加价后费用,保留 2 位小数 """ base_price = Decimal(str(base_price)) markup = Decimal(str(markup_percentage)) team_price = base_price * (1 + markup / 100) cost = Decimal(str(tokens)) * team_price / Decimal('1000000') return cost.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) def calculate_base_cost(tokens: int, base_price) -> Decimal: """计算平台成本(不加价)。 Args: tokens: 消耗的 tokens 数 base_price: 成本价(元/百万tokens) Returns: Decimal: 成本费用,保留 2 位小数 """ base_price = Decimal(str(base_price)) cost = Decimal(str(tokens)) * base_price / Decimal('1000000') return cost.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)