search_eval.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # -*- coding: utf-8 -*-
  2. """搜索 + 评估 · 任意 query → 多渠道搜索去重 → LLM 逐帖评估 → search_data 表
  3. ================================================================================
  4. 引擎函数全部只读复用 search_and_evaluate.py(搜索/去重/转写/评估/英平台翻译)。
  5. 用法(一般由 server.py 起子进程调):
  6. python pipeline/search_eval.py --query-id q0004 --query "AI 人像 图片 生成 怎么做"
  7. python pipeline/search_eval.py --query-id q0005 --query "GPT image2 评测" \
  8. --synonyms "GPT image2 测评,GPT image2 实测" --platforms xhs,gzh --max-count 10
  9. """
  10. import argparse
  11. import asyncio
  12. import json
  13. import sys
  14. from pathlib import Path
  15. PROJECT_ROOT = Path(__file__).resolve().parents[3] # …/Agent
  16. sys.path.insert(0, str(PROJECT_ROOT))
  17. from dotenv import load_dotenv
  18. load_dotenv()
  19. from examples.process_pipeline.script.search_eval.search_and_evaluate import (
  20. search_all, evaluate_posts, transcribe_video_posts, build_query_overrides,
  21. )
  22. from examples.process_pipeline.script.llm_evaluate_sources import (
  23. build_eval_llm_call, EVAL_MODELS, DEFAULT_EVAL_MODEL,
  24. )
  25. HERE = Path(__file__).resolve().parent
  26. MW = HERE.parent
  27. sys.path.insert(0, str(MW))
  28. import db
  29. async def run(args):
  30. phrasings = [args.query] + [s.strip() for s in (args.synonyms or "").split(",") if s.strip()]
  31. # 去重保序
  32. seen, uniq = set(), []
  33. for q in phrasings:
  34. if q not in seen:
  35. seen.add(q); uniq.append(q)
  36. phrasings = uniq
  37. platforms = [p.strip() for p in args.platforms.split(",") if p.strip()]
  38. eval_llm, eval_model_id = build_eval_llm_call(args.eval_model)
  39. print(f"▶ {args.query_id} query={args.query!r} 措辞={phrasings} 渠道={platforms}")
  40. overrides = await build_query_overrides(platforms, phrasings, eval_llm, eval_model_id)
  41. sources = await search_all(platforms, phrasings, args.max_count,
  42. args.max_concurrent, query_overrides=overrides)
  43. print(f"🔎 去重后 {len(sources)} 帖")
  44. if not sources:
  45. print("❌ 搜索无结果"); return 1
  46. try:
  47. from examples.process_pipeline.script.extract_sources import _convert_timestamps
  48. _convert_timestamps(sources)
  49. except Exception:
  50. pass
  51. if not args.no_transcribe:
  52. n = await transcribe_video_posts(sources, concurrency=args.max_concurrent)
  53. if n:
  54. print(f"🎙️ 视频转写 {n} 条")
  55. cost = 0.0
  56. if not args.no_eval:
  57. sources, cost = await evaluate_posts(
  58. sources, "", eval_llm, eval_model_id, args.max_concurrent,
  59. include_images=not args.no_images, max_images=args.max_images,
  60. image_mode=args.image_mode, query=args.query,
  61. )
  62. for s in sources:
  63. s.pop("_image_data_urls", None)
  64. n = db.upsert_search_posts(args.query_id, args.query, sources,
  65. mode_type=args.mode_type or None)
  66. print(f"🗄️ search_data 入库 {n} 行 · 方向 {args.mode_type or '通用'} · 评估成本 ${cost:.4f}")
  67. out_dir = MW / "runs" / "search"
  68. out_dir.mkdir(parents=True, exist_ok=True)
  69. (out_dir / f"{args.query_id}.json").write_text(json.dumps({
  70. "query_id": args.query_id, "query": args.query, "phrasings": phrasings,
  71. "platforms": platforms, "total": len(sources), "results": sources,
  72. }, ensure_ascii=False, indent=2), encoding="utf-8")
  73. return 0
  74. def main():
  75. p = argparse.ArgumentParser(description="搜索+评估 → search_data")
  76. p.add_argument("--query-id", required=True, help="如 q0004(server 自动分配)")
  77. p.add_argument("--query", required=True, help="基准 query(评估锚点)")
  78. p.add_argument("--synonyms", default="", help="逗号分隔的同义措辞(可选)")
  79. p.add_argument("--mode-type", default="", choices=["", "工序", "工具"],
  80. help="该 query 的解构方向(写入 search_data.mode_type;空=通用)")
  81. p.add_argument("--platforms", default="xhs,gzh")
  82. p.add_argument("--max-count", type=int, default=10)
  83. p.add_argument("--eval-model", default=DEFAULT_EVAL_MODEL, choices=list(EVAL_MODELS))
  84. p.add_argument("--max-concurrent", type=int, default=3)
  85. p.add_argument("--max-images", type=int, default=4)
  86. p.add_argument("--image-mode", choices=["url", "base64"], default="url")
  87. p.add_argument("--no-transcribe", action="store_true")
  88. p.add_argument("--no-eval", action="store_true")
  89. p.add_argument("--no-images", action="store_true")
  90. args = p.parse_args()
  91. raise SystemExit(asyncio.run(run(args)))
  92. if __name__ == "__main__":
  93. main()