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(merge_leve2_list, 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. rows = session.query(TopicPatternElement).filter(
  49. TopicPatternElement.execution_id == execution_id
  50. ).all()
  51. if not rows:
  52. return {"message": "没有可处理的数据", "execution_id": execution_id}
  53. # 1) 去重 post_id 拉取 ROV
  54. all_post_ids = sorted({r.post_id for r in rows if r.post_id})
  55. rov_by_post_id = (
  56. get_rov_by_merge_leve2_and_video_ids(merge_leve2_list, all_post_ids) if all_post_ids else {}
  57. )
  58. # 2) 按 element_type 分组,计算 name 的平均 ROV 分
  59. grouped = {
  60. "实质": {
  61. "name_post_ids": defaultdict(set),
  62. "name_paths": defaultdict(set),
  63. },
  64. "形式": {
  65. "name_post_ids": defaultdict(set),
  66. "name_paths": defaultdict(set),
  67. },
  68. "意图": {
  69. "name_post_ids": defaultdict(set),
  70. "name_paths": defaultdict(set),
  71. },
  72. }
  73. for r in rows:
  74. element_type = (r.element_type or "").strip()
  75. if element_type not in grouped:
  76. continue
  77. name = (r.name or "").strip()
  78. if not name:
  79. continue
  80. if r.post_id:
  81. grouped[element_type]["name_post_ids"][name].add(r.post_id)
  82. if r.category_path:
  83. grouped[element_type]["name_paths"][name].add(r.category_path.strip())
  84. output_dir = Path(__file__).parent / "data" / str(execution_id)
  85. output_dir.mkdir(parents=True, exist_ok=True)
  86. summary = {"execution_id": execution_id, "files": {}}
  87. for element_type, data in grouped.items():
  88. name_post_ids = data["name_post_ids"]
  89. name_paths = data["name_paths"]
  90. name_scores = {}
  91. for name, post_ids in name_post_ids.items():
  92. rovs = [_safe_float(rov_by_post_id.get(pid, 0.0)) for pid in post_ids]
  93. score = sum(rovs) / len(rovs) if rovs else 0.0
  94. name_scores[name] = score
  95. raw_elements = []
  96. for name, score in name_scores.items():
  97. post_ids_set = name_post_ids.get(name, set())
  98. raw_elements.append(
  99. {
  100. "name": name,
  101. "score": round(score, 6),
  102. # 不在结果文件里输出帖子 ID 明细,避免体积过大/泄露。
  103. "post_ids_count": len(post_ids_set),
  104. "category_paths": sorted(list(name_paths.get(name, set()))),
  105. }
  106. )
  107. # 通过(score, name)确保排序稳定,进而生成可重复的 id。
  108. element_payload = sorted(
  109. raw_elements,
  110. key=lambda x: (-x["score"], x["name"]),
  111. )
  112. # 3) 计算分类路径节点权重(节点分 = 覆盖的 name score 求和)
  113. category_scores, category_post_ids = _build_category_scores(
  114. name_scores, name_paths, name_post_ids
  115. )
  116. category_payload = sorted(
  117. [
  118. {
  119. "category_path": path,
  120. "category": path.split(">")[-1].strip() if path else "",
  121. "score": round(score, 6),
  122. "post_ids_count": len(category_post_ids.get(path, set())),
  123. }
  124. for path, score in category_scores.items()
  125. ],
  126. key=lambda x: x["score"],
  127. reverse=True,
  128. )
  129. element_file = output_dir / f"{element_type}_元素.json"
  130. category_file = output_dir / f"{element_type}_分类.json"
  131. _write_json(element_file, element_payload)
  132. _write_json(category_file, category_payload)
  133. summary["files"][f"{element_type}_元素"] = str(element_file)
  134. summary["files"][f"{element_type}_分类"] = str(category_file)
  135. return summary
  136. finally:
  137. session.close()
  138. def piaoquan_prepare(cluster_name):
  139. execution_id = run_mining(cluster_name=cluster_name, merge_leve2=cluster_name, platform='piaoquan')
  140. if execution_id:
  141. prepare([cluster_name], execution_id)
  142. return execution_id
  143. if __name__ == '__main__':
  144. # cluster_name = '贪污腐败'
  145. #
  146. # execution_id = run_mining(cluster_name=cluster_name, merge_leve2=cluster_name)
  147. prepare(8)
  148. # execution_id = piaoquan_prepare(cluster_name=cluster_name)
  149. # print(execution_id)