scraper.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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) -> None:
  23. loop = asyncio.get_event_loop()
  24. async with pool.acquire() as conn:
  25. await conn.execute(
  26. "UPDATE scrape_jobs SET status = 'running', updated_at = NOW() WHERE id = $1",
  27. job_id,
  28. )
  29. try:
  30. exec_path = os.environ.get("PLAYWRIGHT_EXECUTABLE") or None
  31. headless = os.environ.get("PLAYWRIGHT_HEADLESS", "true").lower() != "false"
  32. def _norm(v) -> str:
  33. if v is None:
  34. return "null"
  35. return json.dumps(v if isinstance(v, (dict, list)) else json.loads(v), sort_keys=True)
  36. any_changed = False
  37. # 如果 snapshot 里已有的 URL 集合与本次爬取的不一致(多或少),触发变更
  38. async with pool.acquire() as conn:
  39. rows = await conn.fetch("SELECT url FROM price_snapshot")
  40. existing_snapshot_urls = {row["url"] for row in rows}
  41. if existing_snapshot_urls != set(urls):
  42. any_changed = True
  43. for url in urls:
  44. result: dict = await loop.run_in_executor(
  45. None,
  46. lambda u=url: scrape_all(
  47. u,
  48. headless=headless,
  49. timeout=20000,
  50. executable_path=exec_path,
  51. modules=["info", "rate", "tool", "price"],
  52. ),
  53. )
  54. prices = result.get("prices") or {}
  55. model_info = result.get("info") or {}
  56. rate_limits = result.get("rate_limits") or {}
  57. tool_prices = result.get("tool_call_prices") or []
  58. # model_name: 直接用 URL 中提取的 model_id,保持和用户输入一致
  59. model_name = (
  60. result.get("model_id")
  61. or url.rstrip("/").split("/")[-1]
  62. )
  63. async with pool.acquire() as conn:
  64. await conn.execute(
  65. """
  66. INSERT INTO scrape_results
  67. (job_id, url, model_name, prices, model_info, rate_limits, tool_prices, raw_data)
  68. VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::jsonb, $7::jsonb, $8::jsonb)
  69. """,
  70. job_id, url, model_name,
  71. json.dumps(prices), json.dumps(model_info),
  72. json.dumps(rate_limits), json.dumps(tool_prices),
  73. json.dumps(result),
  74. )
  75. # 对比旧快照,有变化才 upsert
  76. existing = await conn.fetchrow(
  77. "SELECT prices, model_info, rate_limits, tool_prices FROM price_snapshot WHERE url = $1",
  78. url,
  79. )
  80. data_changed = (
  81. existing is None
  82. or _norm(existing["prices"]) != _norm(prices)
  83. or _norm(existing["model_info"]) != _norm(model_info)
  84. or _norm(existing["rate_limits"]) != _norm(rate_limits)
  85. or _norm(existing["tool_prices"]) != _norm(tool_prices)
  86. )
  87. if data_changed:
  88. any_changed = True
  89. await conn.execute(
  90. """
  91. INSERT INTO price_snapshot
  92. (url, model_name, prices, model_info, rate_limits, tool_prices, updated_at)
  93. VALUES ($1, $2, $3::jsonb, $4::jsonb, $5::jsonb, $6::jsonb, NOW())
  94. ON CONFLICT (url) DO UPDATE SET
  95. model_name = EXCLUDED.model_name,
  96. prices = EXCLUDED.prices,
  97. model_info = EXCLUDED.model_info,
  98. rate_limits = EXCLUDED.rate_limits,
  99. tool_prices = EXCLUDED.tool_prices,
  100. updated_at = NOW()
  101. """,
  102. url, model_name,
  103. json.dumps(prices), json.dumps(model_info),
  104. json.dumps(rate_limits), json.dumps(tool_prices),
  105. )
  106. # 删除 snapshot 里不在本次爬取列表中的行(模型被移除的情况)
  107. async with pool.acquire() as conn:
  108. await conn.execute(
  109. "DELETE FROM price_snapshot WHERE url != ALL($1::text[])",
  110. urls,
  111. )
  112. # 本批次有任何数据变化,全局版本号 +1(从 1 开始)
  113. if any_changed:
  114. async with pool.acquire() as conn:
  115. await conn.execute(
  116. """
  117. UPDATE price_snapshot_version
  118. SET version = GREATEST(version + 1, 1), updated_at = NOW()
  119. WHERE id = 1
  120. """
  121. )
  122. async with pool.acquire() as conn:
  123. await conn.execute(
  124. "UPDATE scrape_jobs SET status = 'done', updated_at = NOW() WHERE id = $1",
  125. job_id,
  126. )
  127. except Exception as exc:
  128. error_msg = f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"
  129. async with pool.acquire() as conn:
  130. await conn.execute(
  131. "UPDATE scrape_jobs SET status = 'failed', error = $2, updated_at = NOW() WHERE id = $1",
  132. job_id,
  133. error_msg,
  134. )