piaoquan_prepare.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import json
  2. from collections import defaultdict
  3. from pathlib import Path
  4. from examples.demand.data_query_tools import get_rov_by_merge_leve2_and_video_ids
  5. from examples.demand.db_manager import DatabaseManager
  6. from examples.demand.models import TopicPatternElement, TopicPatternExecution
  7. from examples.demand.pattern_builds.pattern_service import run_mining
  8. db = DatabaseManager()
  9. def _safe_float(value):
  10. if value is None:
  11. return 0.0
  12. try:
  13. return float(value)
  14. except (TypeError, ValueError):
  15. return 0.0
  16. def _build_category_scores(name_scores, name_paths, name_post_ids):
  17. """
  18. 计算分类路径节点权重:
  19. - 一个 name 的 score 贡献给其路径上的每个节点
  20. - 同一个 name 多条路径时,每条路径都累加
  21. """
  22. node_scores = defaultdict(float)
  23. node_post_ids = defaultdict(set)
  24. for name, score in name_scores.items():
  25. paths = name_paths.get(name, set())
  26. post_ids = name_post_ids.get(name, set())
  27. for category_path in paths:
  28. if not category_path:
  29. continue
  30. nodes = [segment.strip() for segment in category_path.split(">") if segment.strip()]
  31. for idx in range(len(nodes)):
  32. prefix = ">".join(nodes[: idx + 1])
  33. node_scores[prefix] += score
  34. if post_ids:
  35. node_post_ids[prefix].update(post_ids)
  36. return node_scores, node_post_ids
  37. def _write_json(path, payload):
  38. with open(path, "w", encoding="utf-8") as f:
  39. json.dump(payload, f, ensure_ascii=False, indent=2)
  40. def prepare(execution_id):
  41. session = db.get_session()
  42. try:
  43. execution = session.query(TopicPatternExecution).filter(
  44. TopicPatternExecution.id == execution_id
  45. ).first()
  46. if not execution:
  47. raise ValueError(f"execution_id 不存在: {execution_id}")
  48. merge_leve2 = execution.merge_leve2
  49. rows = session.query(TopicPatternElement).filter(
  50. TopicPatternElement.execution_id == execution_id
  51. ).all()
  52. if not rows:
  53. return {"message": "没有可处理的数据", "execution_id": execution_id}
  54. # 1) 去重 post_id 拉取 ROV
  55. all_post_ids = sorted({r.post_id for r in rows if r.post_id})
  56. rov_by_post_id = get_rov_by_merge_leve2_and_video_ids(merge_leve2, all_post_ids) if all_post_ids else {}
  57. # 2) 按 element_type 分组,计算 name 的平均 ROV 分
  58. grouped = {
  59. "实质": {
  60. "name_post_ids": defaultdict(set),
  61. "name_paths": defaultdict(set),
  62. },
  63. "形式": {
  64. "name_post_ids": defaultdict(set),
  65. "name_paths": defaultdict(set),
  66. },
  67. "意图": {
  68. "name_post_ids": defaultdict(set),
  69. "name_paths": defaultdict(set),
  70. },
  71. }
  72. for r in rows:
  73. element_type = (r.element_type or "").strip()
  74. if element_type not in grouped:
  75. continue
  76. name = (r.name or "").strip()
  77. if not name:
  78. continue
  79. if r.post_id:
  80. grouped[element_type]["name_post_ids"][name].add(r.post_id)
  81. if r.category_path:
  82. grouped[element_type]["name_paths"][name].add(r.category_path.strip())
  83. output_dir = Path(__file__).parent / "data" / str(execution_id)
  84. output_dir.mkdir(parents=True, exist_ok=True)
  85. summary = {"execution_id": execution_id, "merge_leve2": merge_leve2, "files": {}}
  86. for element_type, data in grouped.items():
  87. name_post_ids = data["name_post_ids"]
  88. name_paths = data["name_paths"]
  89. name_scores = {}
  90. for name, post_ids in name_post_ids.items():
  91. rovs = [_safe_float(rov_by_post_id.get(pid, 0.0)) for pid in post_ids]
  92. score = sum(rovs) / len(rovs) if rovs else 0.0
  93. name_scores[name] = score
  94. raw_elements = []
  95. for name, score in name_scores.items():
  96. post_ids_set = name_post_ids.get(name, set())
  97. raw_elements.append(
  98. {
  99. "name": name,
  100. "score": round(score, 6),
  101. # 不在结果文件里输出帖子 ID 明细,避免体积过大/泄露。
  102. "post_ids_count": len(post_ids_set),
  103. "category_paths": sorted(list(name_paths.get(name, set()))),
  104. }
  105. )
  106. # 通过(score, name)确保排序稳定,进而生成可重复的 id。
  107. element_payload = sorted(
  108. raw_elements,
  109. key=lambda x: (-x["score"], x["name"]),
  110. )
  111. # 3) 计算分类路径节点权重(节点分 = 覆盖的 name score 求和)
  112. category_scores, category_post_ids = _build_category_scores(
  113. name_scores, name_paths, name_post_ids
  114. )
  115. category_payload = sorted(
  116. [
  117. {
  118. "category_path": path,
  119. "category": path.split(">")[-1].strip() if path else "",
  120. "score": round(score, 6),
  121. "post_ids_count": len(category_post_ids.get(path, set())),
  122. }
  123. for path, score in category_scores.items()
  124. ],
  125. key=lambda x: x["score"],
  126. reverse=True,
  127. )
  128. element_file = output_dir / f"{element_type}_元素.json"
  129. category_file = output_dir / f"{element_type}_分类.json"
  130. _write_json(element_file, element_payload)
  131. _write_json(category_file, category_payload)
  132. summary["files"][f"{element_type}_元素"] = str(element_file)
  133. summary["files"][f"{element_type}_分类"] = str(category_file)
  134. return summary
  135. finally:
  136. session.close()
  137. def piaoquan_prepare(cluster_name):
  138. execution_id = run_mining(cluster_name=cluster_name, merge_leve2=cluster_name, platform='piaoquan')
  139. if execution_id:
  140. prepare(execution_id)
  141. return execution_id
  142. if __name__ == '__main__':
  143. cluster_name = '历史名人'
  144. execution_id = run_mining(cluster_name=cluster_name, merge_leve2=cluster_name)
  145. # execution_id = piaoquan_prepare(cluster_name=cluster_name)
  146. # print(execution_id)