"""成本统计:估算、记账与汇总。""" from __future__ import annotations from sqlalchemy import func, select from sqlalchemy.orm import Session from app.config import settings from app.models import CostRecord, GenerationRecord, Task def estimate_video_cost(spec, duration_seconds: float) -> float: price = float(getattr(spec, "price_per_second", 0.0) or 0.0) return round(price * max(0.0, float(duration_seconds)), 4) def estimate_voice_cost(spec, chars: int) -> float: price = float(getattr(spec, "price_per_1k_chars", 0.0) or 0.0) return round(price * max(0, int(chars)) / 1000.0, 4) def record_cost(db: Session, *, project_id: int, kind: str, provider: str = "", model: str = "", shot_id: int | None = None, task_id: int | None = None, quantity: float = 0.0, unit: str = "second", unit_price: float = 0.0, cost: float = 0.0, currency: str = "CNY", note: str = "") -> CostRecord: row = CostRecord(project_id=project_id, shot_id=shot_id, task_id=task_id, provider=provider, model=model, kind=kind, quantity=quantity, unit=unit, unit_price=unit_price, cost=round(cost, 6), currency=currency, note=note) db.add(row) db.flush() return row def record_generation(db: Session, **kwargs) -> GenerationRecord: row = GenerationRecord(**kwargs) db.add(row) db.flush() return row def summarize(db: Session, project_id: int | None = None) -> dict: def agg(stmt): rows = db.execute(stmt).all() return [{"key": (k or "unknown"), "cost": round(float(c or 0), 4), "count": int(n or 0)} for k, c, n in rows] def scoped(stmt): return stmt.where(CostRecord.project_id == project_id) if project_id is not None else stmt total = db.execute(scoped(select(func.coalesce(func.sum(CostRecord.cost), 0.0), func.count(CostRecord.id)))).one() by_provider = agg(scoped(select(CostRecord.provider, func.sum(CostRecord.cost), func.count(CostRecord.id)) .group_by(CostRecord.provider))) by_model = agg(scoped(select(CostRecord.model, func.sum(CostRecord.cost), func.count(CostRecord.id)) .group_by(CostRecord.model))) by_kind = agg(scoped(select(CostRecord.kind, func.sum(CostRecord.cost), func.count(CostRecord.id)) .group_by(CostRecord.kind))) pending_stmt = select(func.coalesce(func.sum(Task.cost), 0.0)).where( Task.status.in_(["queued", "running", "retrying", "planned"])) if project_id is not None: pending_stmt = pending_stmt.where(Task.project_id == project_id) pending = db.execute(pending_stmt).one() stmt_gen = select(func.count(GenerationRecord.id), func.coalesce(func.sum(GenerationRecord.duration_seconds), 0.0), func.coalesce(func.sum(GenerationRecord.attempts), 0)) if project_id is not None: stmt_gen = stmt_gen.where(GenerationRecord.project_id == project_id) generations = db.execute(stmt_gen).one() return {"total_cost": round(float(total[0] or 0), 4), "records": int(total[1] or 0), "estimated_pending": round(float(pending[0] or 0), 4), "currency": settings.cost_currency, "by_provider": sorted(by_provider, key=lambda r: -r["cost"]), "by_model": sorted(by_model, key=lambda r: -r["cost"]), "by_kind": sorted(by_kind, key=lambda r: -r["cost"]), "generations": {"count": int(generations[0] or 0), "seconds": round(float(generations[1] or 0), 2), "attempts": int(generations[2] or 0)}} def detailed_costs(db: Session, project_id: int | None = None, limit: int = 200) -> list[dict]: stmt = select(CostRecord).order_by(CostRecord.id.desc()).limit(limit) if project_id is not None: stmt = stmt.where(CostRecord.project_id == project_id) return [{"id": c.id, "project_id": c.project_id, "shot_id": c.shot_id, "task_id": c.task_id, "provider": c.provider, "model": c.model, "kind": c.kind, "quantity": c.quantity, "unit": c.unit, "unit_price": c.unit_price, "cost": c.cost, "currency": c.currency, "note": c.note, "created_at": c.created_at} for c in db.scalars(stmt).all()] def generation_records(db: Session, project_id: int | None = None, limit: int = 200) -> list[dict]: stmt = select(GenerationRecord).order_by(GenerationRecord.id.desc()).limit(limit) if project_id is not None: stmt = stmt.where(GenerationRecord.project_id == project_id) return [{"id": g.id, "project_id": g.project_id, "shot_id": g.shot_id, "task_id": g.task_id, "provider": g.provider, "model": g.model, "kind": g.kind, "prompt": g.prompt, "params": g.params_json or {}, "provider_job_id": g.provider_job_id, "asset_paths": g.asset_paths or [], "output_path": g.output_path, "duration_seconds": g.duration_seconds, "cost": g.cost, "currency": g.currency, "attempts": g.attempts, "created_at": g.created_at, # 供应商侧留痕(ComfyUI 的画布/帧数/实际 seed/产物文件名、耗时等)。 # 「生成记录可复现」要求前端/自检能原样看到这些参数, # 否则重跑时既不知道当初用的什么 seed,也不知道实际出图分辨率。 "metadata": g.metadata_json or {}, "provider_metadata": (g.metadata_json or {}).get("provider_metadata") or {}} for g in db.scalars(stmt).all()]