agg.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. # -*- coding:utf-8 -*-
  2. import math
  3. import os
  4. import re
  5. import shutil
  6. import threading
  7. import time
  8. from concurrent.futures import ProcessPoolExecutor, as_completed, ThreadPoolExecutor
  9. import jieba
  10. import redis
  11. from bitarray import bitarray
  12. from tqdm import tqdm
  13. import utils
  14. import logging
  15. from constant import FILE_LONG_TAIL_MERGE
  16. # 文件:长尾词_合并_分词.txt
  17. FILE_LONG_TAIL_MERGE_SPLIT = "长尾词_合并_分词.txt"
  18. # 文件:长尾词_合并_聚合.txt
  19. FILE_LONG_TAIL_MERGE_AGG = "长尾词_合并_聚合.txt"
  20. # 文件夹:历史聚合数据归档文件夹
  21. DIR_AGG_FILE_ARCHIVE = "长尾词_聚合_归档_%s"
  22. # 文件:长尾词_合并_分词倒排索引.txt
  23. FILE_LONG_TAIL_MERGE_REVERSE_INDEX = "长尾词_合并_倒排索引.txt"
  24. # 子文件:长尾词_合并_聚合_%s.txt
  25. FILE_LONG_TAIL_MERGE_AGG_PID = "长尾词_合并_聚合_%s_%s.txt"
  26. # 缓存前缀:分词词根
  27. CACHE_WORD_STEM = "word:stem"
  28. # 缓存前缀:倒排索引
  29. CACHE_WORD_REVERSE_INDEX = "word:reverse_index"
  30. # 缓存:长尾词缓存
  31. CACHE_WORD = "word"
  32. # 缓存:聚合位图
  33. CACHE_UNUSED_BITMAP = "unused_bitmap"
  34. # 字符集:UTF-8
  35. CHARSET_UTF_8 = "UTF-8"
  36. # redis缓存池
  37. redis_pool: redis.ConnectionPool = None
  38. # 线程池
  39. thread_pool: ThreadPoolExecutor = None
  40. # 线程本地变量
  41. local_var = threading.local()
  42. def agg_word(file_path: str):
  43. """
  44. 长尾词聚合
  45. :param file_path:
  46. :return:
  47. """
  48. # 总长尾词数量
  49. # word_total_num = 0
  50. word_total_num = 1000000
  51. # 聚合阈值
  52. agg_threshold = 0.8
  53. # 每份任务计算量
  54. task_cal_num = 10000
  55. # 工作现成(减1是为了留一个处理器给redis)
  56. worker_num = os.cpu_count() - 1
  57. # worker_num = 1
  58. # 正则表达式:聚合文件分文件
  59. agg_file_pattern = re.compile(r"长尾词_合并_聚合_\d+_\d+.txt", re.I)
  60. # 最大线程数
  61. max_threads = 2
  62. # redis最大连接数(和工作线程数保持一致,免得浪费)
  63. redis_max_conns = max_threads
  64. # redis缓存
  65. m_redis_cache = redis.StrictRedis(host='127.0.0.1', port=6379)
  66. # 判断文件是否存在
  67. for file_name in [FILE_LONG_TAIL_MERGE, FILE_LONG_TAIL_MERGE_SPLIT,
  68. FILE_LONG_TAIL_MERGE_REVERSE_INDEX]:
  69. input_file = os.path.join(file_path, file_name)
  70. if os.path.exists(input_file) and not os.path.isfile(input_file):
  71. raise Exception("文件不存在!文件路径:" + input_file)
  72. # 归档历史数据文件
  73. history_agg_file_list = [file for file in os.listdir(file_path) if agg_file_pattern.match(file)]
  74. if len(history_agg_file_list) > 0:
  75. archive_path = os.path.join(file_path, DIR_AGG_FILE_ARCHIVE % time.strftime('%Y%m%d%H%M%S'))
  76. os.makedirs(archive_path)
  77. for history_agg_file in history_agg_file_list:
  78. shutil.move(os.path.join(file_path, history_agg_file), archive_path)
  79. # 缓存关键词位置
  80. # word_file = os.path.join(file_path, FILE_LONG_TAIL_MERGE)
  81. # word_dict = {}
  82. # with open(word_file, "r", encoding="utf-8") as f:
  83. # for position, word in enumerate(f, start=1):
  84. # word = utils.remove_line_break(word)
  85. # if not word:
  86. # continue
  87. # word_dict[position] = word
  88. # m_redis_cache.hset(CACHE_WORD, mapping=word_dict)
  89. # # 记录总关键词数
  90. # word_total_num = len(word_dict)
  91. # # 释放内存
  92. # del word_dict
  93. #
  94. # # 缓存分词
  95. # word_split_file = os.path.join(file_path, FILE_LONG_TAIL_MERGE_SPLIT)
  96. # word_split_dict = {}
  97. # with open(word_split_file, "r", encoding=CHARSET_UTF_8) as f:
  98. # for position, word_split_line in enumerate(f, start=1):
  99. # word_split_line = utils.remove_line_break(word_split_line)
  100. # if not word_split_line:
  101. # continue
  102. # word_split_dict[position] = word_split_line
  103. # m_redis_cache.hset(CACHE_WORD_STEM, mapping=word_split_dict)
  104. # # 释放内存
  105. # del word_split_dict
  106. #
  107. # # 缓存倒排索引
  108. # word_reverse_index_file = os.path.join(file_path, FILE_LONG_TAIL_MERGE_REVERSE_INDEX)
  109. # word_reverse_index_dict = {}
  110. # # 分词
  111. # key_pattern = re.compile(r"([^,]+),\[", re.I)
  112. # # 索引
  113. # index_pattern = re.compile(r"\d+", re.I)
  114. # with open(word_reverse_index_file, "r", encoding="utf-8") as f:
  115. # for word_split_line in f:
  116. # key_m = key_pattern.match(word_split_line)
  117. # key = key_m.group(1)
  118. # val = index_pattern.findall(word_split_line[word_split_line.index(","):])
  119. # word_reverse_index_dict[key] = ",".join(val)
  120. # m_redis_cache.hset(CACHE_WORD_REVERSE_INDEX, mapping=word_reverse_index_dict)
  121. # # 释放内存
  122. # del word_reverse_index_dict
  123. # 先清除,然后重新构建长尾词使用位图
  124. m_redis_cache.delete(CACHE_UNUSED_BITMAP)
  125. m_redis_cache.setbit(CACHE_UNUSED_BITMAP, word_total_num + 2, 1)
  126. # 提交任务 并输出结果
  127. word_agg_file = os.path.join(file_path, FILE_LONG_TAIL_MERGE_AGG)
  128. with ProcessPoolExecutor(max_workers=worker_num, initializer=init_process,
  129. initargs=(redis_max_conns, max_threads, file_path)) as process_pool:
  130. # 计算任务边界
  131. task_list = utils.avg_split_task(word_total_num, task_cal_num, 1)
  132. # 提交任务
  133. process_futures = []
  134. for skip_line, pos in enumerate(task_list, start=1):
  135. skip_line = (skip_line % worker_num) + 1
  136. p_future = process_pool.submit(agg_word_process, agg_threshold, pos[0], pos[1], word_total_num,
  137. skip_line)
  138. process_futures.append(p_future)
  139. # 显示任务进度
  140. with tqdm(total=len(process_futures), desc='文本聚合进度', unit='份', unit_scale=True) as pbar:
  141. for p_future in as_completed(process_futures):
  142. p_result = p_future.result()
  143. # 更新发呆进度
  144. pbar.update(1)
  145. # 关闭线程
  146. process_pool.shutdown()
  147. # 获取子进程结果文件列表,并合并
  148. with open(word_agg_file, "w", encoding="UTF-8") as fo:
  149. for file in os.listdir(file_path):
  150. # 不是处理结果部分跳过
  151. if not agg_file_pattern.match(file):
  152. continue
  153. with open(os.path.join(file_path, file), "r", encoding="UTF-8") as fi:
  154. for word in fi:
  155. fo.write(word)
  156. def prepare_word_split_and_reverse_index(file_path: str):
  157. """
  158. 预处理:长尾词分词、建立倒排索引
  159. :param file_path: 待处理文件夹路径
  160. :return:
  161. """
  162. # 判断文件是否存在
  163. word_input_file = os.path.join(file_path, FILE_LONG_TAIL_MERGE)
  164. if os.path.exists(word_input_file) and not os.path.isfile(word_input_file):
  165. print("文件不存在! " + word_input_file)
  166. return
  167. # 总文本数量
  168. total_line_num = 0
  169. with open(word_input_file, "r", encoding="utf-8") as fi:
  170. total_line_num = sum(1 for line in fi)
  171. if total_line_num == 0:
  172. print("没有待处理的数据,文本量为0")
  173. return
  174. # 分割任务数量
  175. task_list = utils.avg_split_task(total_line_num, math.ceil(total_line_num / os.cpu_count()))
  176. # 任务进程处理结果
  177. p_result_list = []
  178. # 多进程处理
  179. with ProcessPoolExecutor(os.cpu_count()) as process_pool:
  180. # 提交任务
  181. process_futures = [process_pool.submit(word_split_reverse, word_input_file, task[0], task[1]) for task in
  182. task_list]
  183. # 处理返回结果
  184. for p_future in as_completed(process_futures):
  185. p_result = p_future.result()
  186. if p_result:
  187. p_result_list.append(p_result)
  188. # 分词结果排序
  189. p_result_list = sorted(p_result_list, key=lambda v: v[0])
  190. # 输出分词结果
  191. split_output_file = os.path.join(file_path, FILE_LONG_TAIL_MERGE_SPLIT)
  192. with open(split_output_file, "w", encoding="UTF-8") as fo:
  193. for start_pos, word_arr_list, reverse_index in p_result_list:
  194. for word_arr in word_arr_list:
  195. fo.write("%s\n" % ",".join([str(i) for i in word_arr]))
  196. # 关键词倒排索引
  197. word_reverse_index_dict = dict()
  198. # 合并倒排索引
  199. for start_pos, word_arr, reverse_index_dict in p_result_list:
  200. for key, value in reverse_index_dict.items():
  201. reverse_index_arr = word_reverse_index_dict.get(key)
  202. if reverse_index_arr:
  203. reverse_index_arr.extend(value)
  204. else:
  205. word_reverse_index_dict[key] = value
  206. # 输出倒排索引
  207. with open(os.path.join(file_path, FILE_LONG_TAIL_MERGE_REVERSE_INDEX), "w", encoding="UTF-8") as fo:
  208. for key, value in word_reverse_index_dict.items():
  209. fo.write("%s,%s\n" % (key, value))
  210. # 关闭进程池
  211. process_pool.shutdown()
  212. def word_split_reverse(input_file: str, start_pos: int, end_pos: int):
  213. """
  214. 分词和建立倒排索引
  215. :param input_file: 待处理的文件
  216. :param start_pos: 处理的开始位置
  217. :param end_pos: 处理的结束位置
  218. :return: (开始位置,分词结果,倒排索引)
  219. """
  220. # 加载停用词
  221. stop_word_dict = utils.load_stop_word()
  222. # 关键词存放容器
  223. word_arr_list = []
  224. # 倒排索引
  225. word_reverse_index = dict()
  226. with open(input_file, "r", encoding="utf-8") as fr:
  227. for i, tmp_word in enumerate(fr):
  228. # start_pos是行数,而i要从0开始
  229. if i + 1 < start_pos:
  230. continue
  231. # 当前位置
  232. cur_pos = i + 1
  233. # 到达任务边界,结束
  234. if cur_pos == end_pos:
  235. break
  236. # 分词
  237. word_list = jieba.cut_for_search(tmp_word.replace("\n", ""))
  238. # 分词过滤结果
  239. word_filter_arr = []
  240. # 过滤停用词
  241. for word in word_list:
  242. if word in stop_word_dict:
  243. continue
  244. word_index_arr = word_reverse_index.get(word)
  245. if word_index_arr:
  246. word_index_arr.append(cur_pos)
  247. else:
  248. word_reverse_index[word] = [cur_pos]
  249. word_filter_arr.append(word)
  250. if len(word_filter_arr) == 0:
  251. word_arr_list.append([])
  252. else:
  253. word_arr_list.append(word_filter_arr)
  254. return start_pos, word_arr_list, word_reverse_index
  255. def init_process(max_conns: int, max_threads: int, file_path: str):
  256. """
  257. 初始化进程
  258. :param max_conns: redis最大连接数量
  259. :param max_threads: 线程最大数量
  260. :param file_path: 输出文件路径
  261. :return:
  262. """
  263. # redis缓存池 初始化
  264. global redis_pool
  265. redis_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, max_connections=max_conns)
  266. global thread_pool
  267. thread_pool = ThreadPoolExecutor(max_threads, initializer=init_thread, initargs=(file_path,))
  268. def agg_word_process(agg_threshold: float, start_pos: int, end_pos: int, final_pos: int,
  269. skip_line: int):
  270. """
  271. 长尾词聚合处理
  272. :param agg_threshold: 聚合阈值
  273. :param start_pos: 任务处理开始边界(包含)
  274. :param end_pos: 任务处理结束边界(不包含)
  275. :param final_pos: 总任务边界
  276. :param skip_line: 进度条显示位置
  277. :return:
  278. """
  279. # 进度长度
  280. process_len = 0
  281. if end_pos == -1:
  282. process_len = final_pos - start_pos
  283. else:
  284. process_len = end_pos - start_pos
  285. with tqdm(total=process_len, desc='子进程-%s:文本聚合进度' % os.getpid(), unit='份', unit_scale=True,
  286. position=skip_line) as pbar:
  287. thread_futures = [thread_pool.submit(agg_word_thread, main_word_position, agg_threshold) for main_word_position
  288. in
  289. range(start_pos, end_pos)]
  290. for t_future in as_completed(thread_futures):
  291. t_result = t_future.result()
  292. # 更新发呆进度
  293. pbar.update(1)
  294. return
  295. def init_thread(file_path: str):
  296. """
  297. 聚合线程初始化
  298. :param file_path: 输出文件路径
  299. :return:
  300. """
  301. # 初始化redis客户端
  302. local_var.redis_cache = redis.StrictRedis(connection_pool=redis_pool)
  303. # 初始化redis管道
  304. local_var.redis_pipeline = local_var.redis_cache.pipeline(transaction=False)
  305. # 生成临时结果文件
  306. word_agg_file = os.path.join(file_path,
  307. FILE_LONG_TAIL_MERGE_AGG_PID % (os.getpid(), threading.current_thread().ident))
  308. local_var.file_writer = open(word_agg_file, "w", encoding=CHARSET_UTF_8)
  309. # 已使用位图副本
  310. local_var.unused_bitmap = bitarray()
  311. # 从倒排索引中获取候选词的位置索引
  312. local_var.candidate_position_set = set()
  313. # 结果列表
  314. local_var.result_list = []
  315. def agg_word_thread(main_word_position: int, agg_threshold: float):
  316. try:
  317. # 获取已使用位图副本
  318. local_var.unused_bitmap.frombytes(local_var.redis_cache.get(CACHE_UNUSED_BITMAP))
  319. # 判断主词是否为已使用,是则跳过,否则设置为已使用
  320. if local_var.unused_bitmap[main_word_position]:
  321. return
  322. else:
  323. local_var.redis_cache.setbit(CACHE_UNUSED_BITMAP, main_word_position, 1)
  324. local_var.unused_bitmap[main_word_position] = 1
  325. # 获取主词和对应的词根
  326. local_var.redis_pipeline.hget(CACHE_WORD, main_word_position)
  327. local_var.redis_pipeline.hget(CACHE_WORD_STEM, main_word_position)
  328. main_result = local_var.redis_pipeline.execute()
  329. main_word = main_result[0]
  330. main_word_stem = main_result[1]
  331. # 如果存在为空则返回
  332. if not main_word or not main_word_stem:
  333. return
  334. main_word_stem_list = main_word_stem.decode(CHARSET_UTF_8).split(",")
  335. # 从倒排索引获取长尾词位置
  336. temp_candidate_position_list = local_var.redis_cache.hmget(CACHE_WORD_REVERSE_INDEX, main_word_stem_list)
  337. for temp_candidate_position in temp_candidate_position_list:
  338. if not temp_candidate_position:
  339. continue
  340. # 排除已聚合
  341. for candidate_position in temp_candidate_position.decode(CHARSET_UTF_8).split(","):
  342. if local_var.unused_bitmap[int(candidate_position)]:
  343. continue
  344. local_var.candidate_position_set.add(candidate_position)
  345. # 没有找到需要计算的候选词则跳过
  346. if not local_var.candidate_position_set:
  347. return
  348. # 从缓存获取关键词列表、分词列表,如果为空则跳过
  349. local_var.redis_pipeline.hmget(CACHE_WORD, local_var.candidate_position_set)
  350. local_var.redis_pipeline.hmget(CACHE_WORD_STEM, local_var.candidate_position_set)
  351. candidate_result = local_var.redis_pipeline.execute()
  352. candidate_word_cache_list = candidate_result[0]
  353. candidate_word_stem_cache_list = candidate_result[1]
  354. if not candidate_word_cache_list or not candidate_word_stem_cache_list:
  355. return
  356. # 延后编码成字符,以防前面直接返回
  357. main_word = main_word.decode(CHARSET_UTF_8)
  358. # 计算相似度
  359. for candidate_position in range(len(local_var.candidate_position_set)):
  360. # 获取关键词、分词,如果存在为空则跳过
  361. candidate_word = candidate_word_cache_list[int(candidate_position)]
  362. if not candidate_word:
  363. continue
  364. candidate_word_stem = candidate_word_stem_cache_list[int(candidate_position)]
  365. if not candidate_word_stem:
  366. continue
  367. candidate_word = candidate_word.decode(CHARSET_UTF_8)
  368. candidate_word_stem_list = candidate_word_stem.decode(CHARSET_UTF_8).split(",")
  369. # 计算相关性
  370. try:
  371. val = utils.cal_cos_sim(main_word, main_word_stem_list, candidate_word,
  372. candidate_word_stem_list)
  373. if val >= agg_threshold:
  374. local_var.redis_cache.setbit(CACHE_UNUSED_BITMAP, candidate_position, 1)
  375. local_var.result_list.append(candidate_word)
  376. except Exception as e:
  377. logging.error("主关键词:%s 发生异常,涉及的副关键词信息-关键词:%s,分词:%s" % (
  378. main_word, candidate_word, candidate_word_stem_list), e)
  379. # 保存结果
  380. if not local_var.result_list:
  381. return
  382. local_var.file_writer.write("%s\n" % main_word)
  383. for candidate_word in local_var.result_list:
  384. local_var.file_writer.write("%s\n" % candidate_word)
  385. local_var.file_writer.write("\n")
  386. except Exception as e:
  387. logging.error("子进程发生异常", e)
  388. finally:
  389. # 清除容器数据
  390. local_var.candidate_position_set.clear()
  391. local_var.result_list.clear()
  392. local_var.unused_bitmap.clear()
  393. return