law.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #!/usr/bin/python3.6
  2. # -*- coding: utf-8 -*-
  3. # @Author : lijunliang
  4. # @Email : lijunliang@topnet.net.cn
  5. # @File : law.py
  6. # @Software: PyCharm
  7. import os
  8. import argparse
  9. import datetime
  10. from module.parse_file import parse_file_start
  11. from module.abstract import make_summary
  12. from loguru import logger
  13. from util.oss_file import OssServeClient
  14. from module.read_config import read_ini
  15. from util.db_helper import DBHelper
  16. from module.sql_operate import md5_exists
  17. from module.sql_operate import save_field
  18. from module.parse_file import get_property
  19. from util.file_operations import file_copy
  20. from util.file_operations import generate_directory, del_directory
  21. from module.ac_sensitive import ACAutomation
  22. from pymongo import MongoClient
  23. from util.convert2img import convert_img
  24. from module.load_classify import load_classify
  25. import pandas as pd
  26. import uuid
  27. logger.add("./logging/run.log", rotation="12:00") # 日志文件
  28. parser = argparse.ArgumentParser("指定监听端口")
  29. parser.add_argument('-dir', '--file_dir', default="./data/file/", type=str, help="目录")
  30. parser.add_argument('-config', '--config_path', default="./data/config.ini", type=str, help="配置文件config.ini")
  31. parser.add_argument('-class', '--docClass', default=1, type=int, help="类别")
  32. parser.add_argument('-tags', '--docTags', default="", type=str, help="标签")
  33. parser.add_argument('-pricing_model', '--pricing_type', default="页数", type=str, help="页数or字数")
  34. parser.add_argument('-pricing', '--base_price', default=500, type=float, help="初始价钱")
  35. # parser.add_argument('-addWater', '--Water', default="0" * 12, type=str, help="用户id")
  36. parser.add_argument('-sensitive_file', '--sensitive_path', default="./data/sensitive_words.txt", type=str,
  37. help="敏感词文件路径")
  38. parser.add_argument('-classify_file', '--classify_path', default="./data/classify.csv", type=str,
  39. help="分类文件")
  40. args = parser.parse_args()
  41. docType = {'doc': 1, 'docx': 1, 'ppt': 4, 'pptx': 4, 'xls': 3, 'xlsx': 3, 'txt': 5, 'pdf': 2, 'html': 2,
  42. 'htm': 2} # 文件类型字典
  43. ACA = ACAutomation()
  44. ACA.parse(args.sensitive_path)
  45. def create_oss_object(oss_config: dict):
  46. """
  47. oss服务初始化函数
  48. :param oss_config:
  49. :return:
  50. """
  51. return OssServeClient(access_key_id=oss_config["access_key_id"],
  52. access_key_secret=oss_config["access_key_secret"],
  53. endpoint=oss_config["endpoint"],
  54. bucket_name=oss_config["bucket_name"])
  55. def link_db():
  56. '''
  57. 连接数据库
  58. :return:
  59. '''
  60. Config = read_ini(args.config_path)
  61. FileConfig = Config["oss_file_config"]
  62. MySqlConfig = Config["mysql_config"]
  63. previewConfig = Config["previewConfig"]
  64. FileOss = create_oss_object(FileConfig) # file文件上传oss
  65. previewOss = create_oss_object(previewConfig) # file文件上传oss
  66. MySql = DBHelper(MySqlConfig)
  67. return FileOss, MySql, previewOss
  68. FileOss, MySql, previewOss = link_db()
  69. def check_file_type(doctype: str) -> bool:
  70. """
  71. 文件类型检测
  72. :param doctype:
  73. :return:
  74. """
  75. if doctype not in docType:
  76. logger.warning("%s文件类型不匹配---->" % doctype)
  77. return False
  78. return True
  79. @logger.catch
  80. def upload_oss(file_path: str, file_content: str, pdf_path: str, cover_path: str, persistent: dict) -> dict:
  81. """
  82. 文件上传oss
  83. :param file_path: 文件路径
  84. :param file_content: 解析文本
  85. :param persistent: 自定义请求头
  86. :return:
  87. """
  88. global FileOss, previewOss
  89. succeed = {}
  90. source_oss_name = str(uuid.uuid1(int(time.time()))) + "." + file_path.split(".")[-1]
  91. pdf_oss_name = str(uuid.uuid1(int(time.time()))) + "." + "pdf"
  92. cover_oss_name = str(uuid.uuid1(int(time.time()))) + "." + "png"
  93. text_oss_name = str(uuid.uuid1(int(time.time())))
  94. per_header = FileOss.create_oss_meta(persistent)
  95. if not per_header:
  96. per_header = None
  97. # 源文件上传
  98. with open(file_path, "rb") as file:
  99. state, request_id = FileOss.upload_bytes_file(source_oss_name, file, headers=per_header)
  100. if state:
  101. succeed["ossDocId"] = source_oss_name
  102. # pdf文件上传
  103. with open(pdf_path, "rb") as pdf:
  104. state, request_id = FileOss.upload_bytes_file(pdf_oss_name, pdf, headers=per_header)
  105. if state:
  106. succeed["ossPdfId"] = pdf_oss_name
  107. # 文本文件上传
  108. state, request_id = FileOss.upload_text_file(text_oss_name, file_content, headers=per_header)
  109. if state:
  110. succeed["ossTxtId"] = text_oss_name
  111. # 封面图片上传
  112. with open(cover_path, "rb") as cover:
  113. state, request_id = previewOss.upload_bytes_file(cover_oss_name, cover, headers=per_header)
  114. if state:
  115. succeed["previewImgId"] = cover_oss_name
  116. return succeed
  117. def get_field(file_path: str, persistent: dict):
  118. '''
  119. 文件获取重要字段
  120. :param file_path:
  121. :param file_md5:
  122. :param persistent:自定义请求头字段
  123. :return:
  124. '''
  125. field = {}
  126. # 解析文件,获得文本文档
  127. file_content, pages, pdf_path = parse_file_start(file_path)
  128. text_size = len(file_content)
  129. if text_size < 100: # 检测文本长度检测决定是否上传
  130. return {}
  131. # search = ACA.search(file_content) #敏感词检查
  132. # if search:
  133. # return field
  134. cover_path = convert_img(pdf_path)
  135. if not cover_path:
  136. return {}
  137. field["docPageSize"] = pages
  138. # 上传成功的文件,字段在函数内定义
  139. upload_ret = upload_oss(file_path, file_content, pdf_path, cover_path, persistent)
  140. if not upload_ret:
  141. return {}
  142. field.update(upload_ret)
  143. # 获得摘要
  144. # try:
  145. # summary = make_summary(file_content) # 获得摘要
  146. # except Exception as e:
  147. # logger.warning("摘要提取失败-->%s" % file_content)
  148. # summary = ""
  149. field["docSummary"] = file_content[:500]
  150. # 获得价钱
  151. return field
  152. def other_save(paths, filename):
  153. '''
  154. :param paths:
  155. :param filename:
  156. :return:
  157. '''
  158. try:
  159. source_path = os.path.join(paths, filename) # 文件路径
  160. abs_dir = os.path.abspath(".")
  161. target_dir = os.path.join(abs_dir, "data/folder/")
  162. if os.path.exists(target_dir):
  163. del_directory(target_dir)
  164. generate_directory(target_dir)
  165. target_path = os.path.join(target_dir, filename)
  166. state = file_copy(source_path, target_path)
  167. if not state:
  168. return False, target_path
  169. except Exception as e:
  170. print(e)
  171. return False, ""
  172. return True, target_path
  173. def get_persistent(row: dict):
  174. '''
  175. 自定义请求信息字典
  176. :param row:
  177. :return:
  178. '''
  179. persistent = {}
  180. persistent["title"] = row.get("title", "")
  181. persistent["office"] = row.get("office", "")
  182. persistent["publish"] = row.get("publish", "")
  183. persistent["expiry"] = row.get("expiry", "")
  184. persistent["type"] = row.get("type", "")
  185. persistent["status"] = row.get("status", "")
  186. persistent["url"] = row.get("url", "")
  187. return persistent
  188. @logger.catch
  189. def walk_dir_start():
  190. """
  191. 生成开始
  192. :param file_dir:
  193. :return:
  194. """
  195. from bson import ObjectId
  196. FileOss, MySql, previewOss = link_db()
  197. mongoClient = MongoClient("192.168.3.166:27082")
  198. m_col = mongoClient["bxh"]["gjflfgzsk"]
  199. classify_dict = load_classify(args.classify_path)
  200. base_class=[args]
  201. for row in m_col.find({"_id": {"$gt": ObjectId("604201abdca8410f1ef2cafb")}}, no_cursor_timeout=True).sort("_id",
  202. 1):
  203. print("id--->", row["_id"])
  204. file_path = ""
  205. persistent = get_persistent(row)
  206. title = row.get("title", "")
  207. files = row.get("file", [])
  208. for file in files:
  209. if "WORD" == file.get("type", ""):
  210. file_path = file.get("path", "")
  211. if not file_path:
  212. continue
  213. filename = file_path.split("/")[-1]
  214. paths = "./files"
  215. need_field = {}
  216. need_field["docName"] = title
  217. state, target_path = other_save(paths, filename)
  218. if not state:
  219. continue
  220. doctype, suffix, fileSize = get_property(target_path)
  221. if not check_file_type(doctype): # 类型检查
  222. continue
  223. need_field["docFileType"] = docType[doctype] # 文件类型
  224. need_field["docFileSuffix"] = suffix # 文件后缀
  225. need_field["docFileSize"] = fileSize # 文件大小
  226. state, file_md5 = md5_exists(MySql, target_path) # md5检查去重
  227. need_field["md5"] = file_md5
  228. if state:
  229. logger.warning("%s已经存在--------》" % filename)
  230. continue
  231. field = get_field(target_path, persistent)
  232. if not field:
  233. logger.warning("储存失败--->%s" % row["_id"])
  234. continue
  235. # continue
  236. need_field.update(field)
  237. need_field["uploadDate"] = datetime.datetime.now()
  238. need_field["isDelete"] = 0
  239. need_field["downOrUp"] = 1
  240. doctype = row.get("type", "").strip()
  241. if doctype in classify_dict:
  242. docClass = classify_dict[doctype]
  243. else:
  244. continue
  245. need_field["docTags"] = "法律法规/" + doctype # 获取输入标签
  246. need_field["docClass"] = docClass # 获取输入类别
  247. need_field["userId"] = str(row["_id"]) # 获取输入用户ID
  248. need_field["appId"] = "10000"
  249. save_field(MySql, need_field) # 保存到mysql
  250. if __name__ == '__main__':
  251. filepath = "./files"
  252. import time
  253. ret=load_classify(args.classify_path)
  254. print(ret)
  255. # start = time.time()
  256. # walk_dir_start()
  257. # end = time.time()
  258. # print(end - start)