search_eval.py 4.7 KB

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