public.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. from __future__ import annotations
  2. import re
  3. from datetime import datetime
  4. from typing import List, Optional, Union
  5. from urllib.parse import urlparse
  6. import json
  7. from app.utils.price_parser import parse_prices
  8. from app.utils.apikey_crypto import try_encrypt
  9. from fastapi import APIRouter, HTTPException, Request
  10. from pydantic import BaseModel
  11. from app.db import get_pool
  12. from app.services.geo import geo_resolver
  13. router = APIRouter()
  14. class PublicPriceOut(BaseModel):
  15. url: str
  16. model_name: str
  17. prices: dict
  18. model_info: Optional[dict] = None
  19. rate_limits: Optional[dict] = None
  20. tool_prices: Optional[list] = None
  21. icon: Optional[str] = None
  22. scraped_at: datetime
  23. discount: Optional[float] = None
  24. api_key: Optional[str] = None
  25. group_name: Optional[str] = None
  26. class ParsedPriceItem(BaseModel):
  27. url: str
  28. model_name: str
  29. tier_min: Optional[float] = None
  30. tier_max: Optional[float] = None
  31. tier_unit: Optional[str] = None
  32. input_price: Optional[float] = None
  33. output_price: Optional[float] = None
  34. currency: str = "CNY"
  35. unit: Optional[str] = None
  36. label: Optional[str] = None
  37. class DiscountedPriceItem(BaseModel):
  38. url: str
  39. model_name: str
  40. tier_min: Optional[float] = None
  41. tier_max: Optional[float] = None
  42. tier_unit: Optional[str] = None
  43. input_price: Optional[float] = None
  44. output_price: Optional[float] = None
  45. currency: str = "CNY"
  46. unit: Optional[str] = None
  47. label: Optional[str] = None
  48. discount: Optional[float] = None # None 表示未知,1.0 表示原价
  49. class ModelTypeItem(BaseModel):
  50. model_name: str
  51. type: List[str]
  52. class PricesResponse(BaseModel):
  53. version: int
  54. models: List[PublicPriceOut]
  55. parsed_prices: List[ParsedPriceItem]
  56. discounted_prices: List[DiscountedPriceItem]
  57. types: List[ModelTypeItem]
  58. class UpToDateResponse(BaseModel):
  59. up_to_date: bool = True
  60. version: int
  61. def _extract_domain(referer: Optional[str]) -> Optional[str]:
  62. if not referer:
  63. return None
  64. try:
  65. return urlparse(referer).netloc or None
  66. except Exception:
  67. return None
  68. @router.get("/prices", response_model=Union[PricesResponse, UpToDateResponse])
  69. async def get_public_prices(
  70. request: Request,
  71. url: Optional[str] = None,
  72. ) -> Union[PricesResponse, UpToDateResponse]:
  73. pool = get_pool()
  74. # referer 必须提供
  75. referer = request.headers.get("referer") or request.headers.get("origin")
  76. if not referer:
  77. raise HTTPException(status_code=400, detail="Missing Referer header")
  78. # version 从 Header 读取,默认 0(首次请求)
  79. try:
  80. version = int(request.headers.get("version", "0") or "0")
  81. except ValueError:
  82. version = 0
  83. # 记录调用来源
  84. ip = request.client.host if request.client else "unknown"
  85. geo = geo_resolver.resolve(ip)
  86. try:
  87. await pool.execute(
  88. "INSERT INTO price_api_logs (ip, referer, org, country, city) VALUES ($1, $2, $3, $4, $5)",
  89. ip, referer, geo.org, geo.country, geo.city,
  90. )
  91. except Exception:
  92. pass
  93. # 查调用方域名对应的折扣
  94. caller_domain = _extract_domain(referer)
  95. discount_rate: float = 1.0
  96. # 域名级别的模型自定义价格:{model_name: {input_price, output_price}}
  97. model_custom_prices: dict = {}
  98. if caller_domain:
  99. row = await pool.fetchrow("SELECT discount FROM discounts WHERE domain = $1", caller_domain)
  100. if row:
  101. discount_rate = float(row["discount"])
  102. # 加载该域名下所有模型的自定义折扣
  103. mp_rows = await pool.fetch(
  104. "SELECT model_name, discount FROM domain_model_prices WHERE domain = $1",
  105. caller_domain,
  106. )
  107. for mp in mp_rows:
  108. model_custom_prices[mp["model_name"]] = float(mp["discount"])
  109. def _j(v):
  110. if v is None:
  111. return None
  112. return v if isinstance(v, (dict, list)) else json.loads(v)
  113. # 读取版本号:优先用域名专属版本,没有则回退到全局版本
  114. if caller_domain:
  115. ver_row = await pool.fetchrow(
  116. "SELECT version FROM domain_version WHERE domain = $1", caller_domain
  117. )
  118. if ver_row:
  119. current_version = int(ver_row["version"])
  120. else:
  121. ver_row = await pool.fetchrow("SELECT version FROM price_snapshot_version WHERE id = 1")
  122. current_version = int(ver_row["version"]) if ver_row else 0
  123. else:
  124. ver_row = await pool.fetchrow("SELECT version FROM price_snapshot_version WHERE id = 1")
  125. current_version = int(ver_row["version"]) if ver_row else 0
  126. # version != 0 且与当前一致 → 无需更新(0 视为首次请求,强制返回数据)
  127. if version != 0 and version == current_version:
  128. return UpToDateResponse(up_to_date=True, version=current_version)
  129. # 从 price_snapshot 读取数据,LEFT JOIN models 取 api_key 和 group
  130. if url is None:
  131. rows = await pool.fetch(
  132. """
  133. SELECT ps.url, ps.model_name, ps.prices, ps.model_info, ps.rate_limits,
  134. ps.tool_prices, ps.icon, ps.updated_at,
  135. k.key_value AS api_key,
  136. m.group_id, g.name AS group_name
  137. FROM price_snapshot ps
  138. LEFT JOIN models m ON m.url = ps.url
  139. LEFT JOIN api_keys k ON k.id = m.api_key_id
  140. LEFT JOIN model_groups g ON g.id = m.group_id
  141. ORDER BY ps.url
  142. """
  143. )
  144. else:
  145. rows = await pool.fetch(
  146. """
  147. SELECT ps.url, ps.model_name, ps.prices, ps.model_info, ps.rate_limits,
  148. ps.tool_prices, ps.icon, ps.updated_at,
  149. k.key_value AS api_key,
  150. m.group_id, g.name AS group_name
  151. FROM price_snapshot ps
  152. LEFT JOIN models m ON m.url = ps.url
  153. LEFT JOIN api_keys k ON k.id = m.api_key_id
  154. LEFT JOIN model_groups g ON g.id = m.group_id
  155. WHERE ps.url = $1
  156. """,
  157. url,
  158. )
  159. if not rows:
  160. raise HTTPException(status_code=404, detail="No price snapshot found for the given URL")
  161. if not rows:
  162. raise HTTPException(status_code=503, detail="Price snapshot not yet available")
  163. # version != 0 且与当前一致 → 无需更新
  164. if version != 0 and version == current_version:
  165. return UpToDateResponse(up_to_date=True, version=current_version)
  166. def _extract_type(model_info: Optional[dict]) -> Optional[List[str]]:
  167. if not model_info:
  168. return None
  169. tags = model_info.get("display_tags", [])
  170. TYPE_TAGS = {"文本生成", "图像生成", "视频生成", "向量表示", "向量模型", "多模态向量", "语音识别", "实时语音识别", "语音合成"}
  171. result = [t for t in tags if t in TYPE_TAGS]
  172. return result if result else None
  173. models = [PublicPriceOut(
  174. url=r["url"],
  175. model_name=r["model_name"],
  176. prices=_j(r["prices"]) or {},
  177. model_info=_j(r["model_info"]),
  178. rate_limits=_j(r["rate_limits"]),
  179. tool_prices=_j(r["tool_prices"]),
  180. icon=r["icon"],
  181. scraped_at=r["updated_at"],
  182. discount=model_custom_prices.get(r["model_name"]) if model_custom_prices.get(r["model_name"]) is not None else discount_rate,
  183. api_key=try_encrypt(r["api_key"]),
  184. group_name=r["group_name"],
  185. ) for r in rows]
  186. parsed_prices: List[ParsedPriceItem] = []
  187. discounted_prices: List[DiscountedPriceItem] = []
  188. # 只保留输入/输出主价格,过滤掉缓存命中、Batch File、调优等附加价格
  189. _EXCLUDED_LABEL_RE = re.compile(
  190. r"缓存|batch\s*file|批量|调优|思考模式",
  191. re.I,
  192. )
  193. for r in rows:
  194. for item in parse_prices(_j(r["prices"]) or {}):
  195. # 过滤掉输入和输出价格都为 None 的条目(保留单边价格,如向量模型、图像生成等)
  196. if item.get("input_price") is None and item.get("output_price") is None:
  197. continue
  198. # 过滤掉缓存命中、Batch File、调优等非主价格条目
  199. label = item.get("label") or ""
  200. if _EXCLUDED_LABEL_RE.search(label):
  201. continue
  202. # 将 label 改为中文
  203. item = dict(item)
  204. if item.get("label") == "input/output":
  205. item["label"] = "输入/输出"
  206. parsed_prices.append(ParsedPriceItem(url=r["url"], model_name=r["model_name"], **item))
  207. d_item = dict(item)
  208. model_name = r["model_name"]
  209. custom = model_custom_prices.get(model_name)
  210. # 模型级折扣优先,没有则用域名全局折扣
  211. effective_discount = custom if custom is not None else discount_rate
  212. if effective_discount is not None:
  213. if d_item.get("input_price") is not None:
  214. d_item["input_price"] = round(d_item["input_price"] * effective_discount, 6)
  215. if d_item.get("output_price") is not None:
  216. d_item["output_price"] = round(d_item["output_price"] * effective_discount, 6)
  217. discounted_prices.append(DiscountedPriceItem(url=r["url"], model_name=r["model_name"], discount=effective_discount, **d_item))
  218. all_types = [
  219. ModelTypeItem(model_name=r["model_name"], type=_extract_type(_j(r["model_info"])) or [])
  220. for r in rows
  221. ]
  222. return PricesResponse(
  223. version=current_version,
  224. models=models,
  225. parsed_prices=parsed_prices,
  226. discounted_prices=discounted_prices,
  227. types=all_types,
  228. )