67 lines
2.0 KiB
Python
67 lines
2.0 KiB
Python
import json
|
|
|
|
from fastapi.templating import Jinja2Templates
|
|
|
|
|
|
templates = Jinja2Templates(directory="app/templates")
|
|
|
|
|
|
def status_badge_config(status: str) -> tuple[str, str]:
|
|
config = {
|
|
"pending": ("等待中", "bg-secondary"),
|
|
"running": ("运行中", "bg-warning text-dark"),
|
|
"success": ("已完成", "bg-success"),
|
|
"failed": ("失败", "bg-danger"),
|
|
}
|
|
return config.get(status, ("未知", "bg-secondary"))
|
|
|
|
|
|
def platform_label(platform: str) -> str:
|
|
return {"xiaohongshu": "小红书", "douyin": "抖音"}.get(platform, platform)
|
|
|
|
|
|
def from_json_filter(value: str | None) -> list:
|
|
try:
|
|
parsed = json.loads(value) if value else []
|
|
except (TypeError, json.JSONDecodeError):
|
|
return []
|
|
return parsed if isinstance(parsed, list) else []
|
|
|
|
|
|
def from_json_object_filter(value: str | None) -> dict:
|
|
try:
|
|
parsed = json.loads(value) if value else {}
|
|
except (TypeError, json.JSONDecodeError):
|
|
return {}
|
|
return parsed if isinstance(parsed, dict) else {}
|
|
|
|
|
|
def progress_percent(processed_count: int, total_count: int) -> int:
|
|
if total_count <= 0:
|
|
return 0
|
|
return min(100, max(0, round((processed_count / total_count) * 100)))
|
|
|
|
|
|
def rate_percent(rate: float | None) -> int:
|
|
if rate is None:
|
|
return 0
|
|
return min(100, max(0, round(rate * 100)))
|
|
|
|
|
|
def sentiment_label(sentiment: str) -> str:
|
|
return {
|
|
"positive": "正向",
|
|
"neutral": "中性",
|
|
"negative": "负向",
|
|
"unknown": "未知",
|
|
}.get(sentiment, sentiment)
|
|
|
|
|
|
templates.env.globals["status_badge_config"] = status_badge_config
|
|
templates.env.globals["progress_percent"] = progress_percent
|
|
templates.env.globals["rate_percent"] = rate_percent
|
|
templates.env.globals["sentiment_label"] = sentiment_label
|
|
templates.env.filters["platform_label"] = platform_label
|
|
templates.env.filters["from_json"] = from_json_filter
|
|
templates.env.filters["from_json_object"] = from_json_object_filter
|