scraper.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. """
  2. ScraperService: runs scrape jobs asynchronously using a thread pool executor.
  3. Uses the new crawl/main.py scrape_all() which collects prices, model info,
  4. rate limits and tool call prices in a single browser session.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import json
  9. import os
  10. import sys
  11. import traceback
  12. from typing import Any
  13. # Add backend root and crawl dir to path
  14. _backend_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  15. _crawl_dir = os.path.join(_backend_root, "crawl")
  16. for _p in (_backend_root, _crawl_dir):
  17. if _p not in sys.path:
  18. sys.path.insert(0, _p)
  19. from main import scrape_all # noqa: E402 (backend/crawl/main.py)
  20. class ScraperService:
  21. """Manages the lifecycle of a scrape job."""
  22. async def run_job(self, job_id: str, urls: list[str], pool: Any, api_keys: dict[str, str] | None = None) -> None:
  23. loop = asyncio.get_event_loop()
  24. if api_keys is None:
  25. api_keys = {}
  26. async with pool.acquire() as conn:
  27. await conn.execute(
  28. "UPDATE scrape_jobs SET status = 'running', updated_at = NOW() WHERE id = $1",
  29. job_id,
  30. )
  31. try:
  32. exec_path = os.environ.get("PLAYWRIGHT_EXECUTABLE") or None
  33. headless = os.environ.get("PLAYWRIGHT_HEADLESS", "true").lower() != "false"
  34. def _norm(v) -> str:
  35. if v is None:
  36. return "null"
  37. return json.dumps(v if isinstance(v, (dict, list)) else json.loads(v), sort_keys=True)
  38. any_changed = False
  39. # 如果 snapshot 里已有的 URL 集合与本次爬取的不一致(多或少),触发变更
  40. async with pool.acquire() as conn:
  41. rows = await conn.fetch("SELECT url FROM price_snapshot")
  42. existing_snapshot_urls = {row["url"] for row in rows}
  43. if existing_snapshot_urls != set(urls):
  44. any_changed = True
  45. # 查出 url -> name 映射,用于 model_hint
  46. async with pool.acquire() as conn:
  47. name_rows = await conn.fetch(
  48. "SELECT url, name FROM models WHERE url = ANY($1::text[])",
  49. urls,
  50. )
  51. model_names = {row["url"]: row["name"] for row in name_rows}
  52. for url in urls:
  53. api_key = api_keys.get(url)
  54. model_hint = model_names.get(url)
  55. result: dict = await loop.run_in_executor(
  56. None,
  57. lambda u=url, k=api_key, h=model_hint: scrape_all(
  58. u,
  59. headless=headless,
  60. timeout=20000,
  61. executable_path=exec_path,
  62. modules=["info", "rate", "tool", "price", "icon"],
  63. api_key=k,
  64. model_hint=h,
  65. ),
  66. )
  67. prices = result.get("prices") or {}
  68. model_info = result.get("info") or {}
  69. rate_limits = result.get("rate_limits") or {}
  70. tool_prices = result.get("tool_call_prices") or []
  71. icon = result.get("icon") # SVG string or None
  72. # model_name: 直接用 URL 中提取的 model_id,保持和用户输入一致
  73. model_name = (
  74. result.get("model_id")
  75. or url.rstrip("/").split("/")[-1]
  76. )
  77. async with pool.acquire() as conn:
  78. await conn.execute(
  79. """
  80. INSERT INTO scrape_results
  81. (job_id, url, model_name, prices, model_info, rate_limits, tool_prices, raw_data, icon)
  82. VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::jsonb, $7::jsonb, $8::jsonb, $9)
  83. """,
  84. job_id, url, model_name,
  85. json.dumps(prices), json.dumps(model_info),
  86. json.dumps(rate_limits), json.dumps(tool_prices),
  87. json.dumps(result), icon,
  88. )
  89. # 对比旧快照,有变化才 upsert
  90. existing = await conn.fetchrow(
  91. "SELECT prices, model_info, rate_limits, tool_prices, icon FROM price_snapshot WHERE url = $1",
  92. url,
  93. )
  94. data_changed = (
  95. existing is None
  96. or _norm(existing["prices"]) != _norm(prices)
  97. or _norm(existing["model_info"]) != _norm(model_info)
  98. or _norm(existing["rate_limits"]) != _norm(rate_limits)
  99. or _norm(existing["tool_prices"]) != _norm(tool_prices)
  100. or (existing["icon"] or "") != (icon or "")
  101. )
  102. if data_changed:
  103. any_changed = True
  104. await conn.execute(
  105. """
  106. INSERT INTO price_snapshot
  107. (url, model_name, prices, model_info, rate_limits, tool_prices, icon, updated_at)
  108. VALUES ($1, $2, $3::jsonb, $4::jsonb, $5::jsonb, $6::jsonb, $7, NOW())
  109. ON CONFLICT (url) DO UPDATE SET
  110. model_name = EXCLUDED.model_name,
  111. prices = EXCLUDED.prices,
  112. model_info = EXCLUDED.model_info,
  113. rate_limits = EXCLUDED.rate_limits,
  114. tool_prices = EXCLUDED.tool_prices,
  115. icon = EXCLUDED.icon,
  116. updated_at = NOW()
  117. """,
  118. url, model_name,
  119. json.dumps(prices), json.dumps(model_info),
  120. json.dumps(rate_limits), json.dumps(tool_prices), icon,
  121. )
  122. # 删除 snapshot 里不在本次爬取列表中的行(模型被移除的情况)
  123. async with pool.acquire() as conn:
  124. await conn.execute(
  125. "DELETE FROM price_snapshot WHERE url != ALL($1::text[])",
  126. urls,
  127. )
  128. # 本批次有任何数据变化,全局版本号 +1(从 1 开始),同时 bump 所有已有 domain_version 的域名
  129. if any_changed:
  130. async with pool.acquire() as conn:
  131. await conn.execute(
  132. """
  133. UPDATE price_snapshot_version
  134. SET version = GREATEST(version + 1, 1), updated_at = NOW()
  135. WHERE id = 1
  136. """
  137. )
  138. # 同步 bump 所有已有 domain_version 记录的域名
  139. await conn.execute(
  140. """
  141. UPDATE domain_version
  142. SET version = version + 1, updated_at = NOW()
  143. """
  144. )
  145. async with pool.acquire() as conn:
  146. await conn.execute(
  147. "UPDATE scrape_jobs SET status = 'done', updated_at = NOW() WHERE id = $1",
  148. job_id,
  149. )
  150. except Exception as exc:
  151. error_msg = f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"
  152. async with pool.acquire() as conn:
  153. await conn.execute(
  154. "UPDATE scrape_jobs SET status = 'failed', error = $2, updated_at = NOW() WHERE id = $1",
  155. job_id,
  156. error_msg,
  157. )