public.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. from __future__ import annotations
  2. from datetime import datetime
  3. from typing import List, Optional, Union
  4. from urllib.parse import urlparse
  5. import json
  6. from app.utils.price_parser import parse_prices
  7. from fastapi import APIRouter, HTTPException, Request
  8. from pydantic import BaseModel
  9. from app.db import get_pool
  10. from app.services.geo import geo_resolver
  11. router = APIRouter()
  12. class PublicPriceOut(BaseModel):
  13. url: str
  14. model_name: str
  15. prices: dict
  16. model_info: Optional[dict] = None
  17. rate_limits: Optional[dict] = None
  18. tool_prices: Optional[list] = None
  19. scraped_at: datetime
  20. class ParsedPriceItem(BaseModel):
  21. url: str
  22. model_name: str
  23. tier_min: Optional[float] = None
  24. tier_max: Optional[float] = None
  25. tier_unit: Optional[str] = None
  26. input_price: Optional[float] = None
  27. output_price: Optional[float] = None
  28. currency: str = "CNY"
  29. unit: Optional[str] = None
  30. label: Optional[str] = None
  31. class DiscountedPriceItem(BaseModel):
  32. url: str
  33. model_name: str
  34. tier_min: Optional[float] = None
  35. tier_max: Optional[float] = None
  36. tier_unit: Optional[str] = None
  37. input_price: Optional[float] = None
  38. output_price: Optional[float] = None
  39. currency: str = "CNY"
  40. unit: Optional[str] = None
  41. label: Optional[str] = None
  42. discount: Optional[float] = None # None 表示无折扣(原价)
  43. class ModelTypeItem(BaseModel):
  44. model_name: str
  45. type: List[str]
  46. class PricesResponse(BaseModel):
  47. version: int
  48. models: List[PublicPriceOut]
  49. parsed_prices: List[ParsedPriceItem]
  50. discounted_prices: List[DiscountedPriceItem]
  51. types: List[ModelTypeItem]
  52. discount: float = 1.0
  53. class UpToDateResponse(BaseModel):
  54. up_to_date: bool = True
  55. version: int
  56. def _extract_domain(referer: Optional[str]) -> Optional[str]:
  57. if not referer:
  58. return None
  59. try:
  60. return urlparse(referer).netloc or None
  61. except Exception:
  62. return None
  63. @router.get("/prices", response_model=Union[PricesResponse, UpToDateResponse])
  64. async def get_public_prices(
  65. request: Request,
  66. url: Optional[str] = None,
  67. ) -> Union[PricesResponse, UpToDateResponse]:
  68. pool = get_pool()
  69. # referer 必须提供
  70. referer = request.headers.get("referer") or request.headers.get("origin")
  71. if not referer:
  72. raise HTTPException(status_code=400, detail="Missing Referer header")
  73. # version 从 Header 读取,默认 0(首次请求)
  74. try:
  75. version = int(request.headers.get("version", "0") or "0")
  76. except ValueError:
  77. version = 0
  78. # 记录调用来源
  79. ip = request.client.host if request.client else "unknown"
  80. geo = geo_resolver.resolve(ip)
  81. try:
  82. await pool.execute(
  83. "INSERT INTO price_api_logs (ip, referer, org, country, city) VALUES ($1, $2, $3, $4, $5)",
  84. ip, referer, geo.org, geo.country, geo.city,
  85. )
  86. except Exception:
  87. pass
  88. # 查调用方域名对应的折扣
  89. caller_domain = _extract_domain(referer)
  90. discount_rate: Optional[float] = None
  91. if caller_domain:
  92. row = await pool.fetchrow("SELECT discount FROM discounts WHERE domain = $1", caller_domain)
  93. if row:
  94. discount_rate = float(row["discount"])
  95. def _j(v):
  96. if v is None:
  97. return None
  98. return v if isinstance(v, (dict, list)) else json.loads(v)
  99. # 读取全局版本号(0 表示尚未有任何快照)
  100. ver_row = await pool.fetchrow("SELECT version FROM price_snapshot_version WHERE id = 1")
  101. current_version: int = int(ver_row["version"]) if ver_row else 0
  102. # version != 0 且与当前一致 → 无需更新(0 视为首次请求,强制返回数据)
  103. if version != 0 and version == current_version:
  104. return UpToDateResponse(up_to_date=True, version=current_version)
  105. # 从 price_snapshot 读取数据
  106. if url is None:
  107. rows = await pool.fetch(
  108. "SELECT url, model_name, prices, model_info, rate_limits, tool_prices, updated_at FROM price_snapshot ORDER BY url"
  109. )
  110. else:
  111. rows = await pool.fetch(
  112. "SELECT url, model_name, prices, model_info, rate_limits, tool_prices, updated_at FROM price_snapshot WHERE url = $1",
  113. url,
  114. )
  115. if not rows:
  116. raise HTTPException(status_code=404, detail="No price snapshot found for the given URL")
  117. if not rows:
  118. raise HTTPException(status_code=503, detail="Price snapshot not yet available")
  119. # version != 0 且与当前一致 → 无需更新
  120. if version != 0 and version == current_version:
  121. return UpToDateResponse(up_to_date=True, version=current_version)
  122. def _extract_type(model_info: Optional[dict]) -> Optional[List[str]]:
  123. if not model_info:
  124. return None
  125. tags = model_info.get("display_tags", [])
  126. TYPE_TAGS = {"文本生成", "图像生成", "视频生成", "向量表示", "向量模型", "多模态向量", "语音识别", "实时语音识别", "语音合成"}
  127. result = [t for t in tags if t in TYPE_TAGS]
  128. return result if result else None
  129. models = [PublicPriceOut(
  130. url=r["url"],
  131. model_name=r["model_name"],
  132. prices=_j(r["prices"]) or {},
  133. model_info=_j(r["model_info"]),
  134. rate_limits=_j(r["rate_limits"]),
  135. tool_prices=_j(r["tool_prices"]),
  136. scraped_at=r["updated_at"],
  137. ) for r in rows]
  138. parsed_prices: List[ParsedPriceItem] = []
  139. discounted_prices: List[DiscountedPriceItem] = []
  140. for r in rows:
  141. for item in parse_prices(_j(r["prices"]) or {}):
  142. parsed_prices.append(ParsedPriceItem(url=r["url"], model_name=r["model_name"], **item))
  143. d_item = dict(item)
  144. if discount_rate is not None:
  145. if d_item.get("input_price") is not None:
  146. d_item["input_price"] = round(d_item["input_price"] * discount_rate, 6)
  147. if d_item.get("output_price") is not None:
  148. d_item["output_price"] = round(d_item["output_price"] * discount_rate, 6)
  149. discounted_prices.append(DiscountedPriceItem(url=r["url"], model_name=r["model_name"], discount=discount_rate, **d_item))
  150. all_types = [
  151. ModelTypeItem(model_name=r["model_name"], type=_extract_type(_j(r["model_info"])) or [])
  152. for r in rows
  153. ]
  154. return PricesResponse(
  155. version=current_version,
  156. models=models,
  157. parsed_prices=parsed_prices,
  158. discounted_prices=discounted_prices,
  159. types=all_types,
  160. discount=discount_rate if discount_rate is not None else 1.0,
  161. )