resume_parse.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. import os
  4. import sys
  5. import re
  6. import json
  7. import time
  8. from os import walk
  9. import subprocess
  10. import rarfile
  11. import py7zr
  12. import tarfile
  13. from zipfile import ZipFile
  14. import requests
  15. from requests.adapters import HTTPAdapter
  16. import logging
  17. from docx import Document
  18. from docx.shared import Inches
  19. from pdfminer.pdfpage import PDFPage
  20. from pdfminer.pdfparser import PDFParser
  21. from pdfminer.pdfdocument import PDFDocument
  22. from pdfminer.high_level import extract_pages
  23. from pdfminer.converter import PDFPageAggregator
  24. from pdfminer.layout import LTTextContainer, LTChar, LTLine, LAParams, LTTextBox, LTFigure, LTImage, LTText, LTAnno, LTTextLine, LTTextLineHorizontal
  25. from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
  26. import pdfplumber
  27. from paddlenlp import Taskflow
  28. class Logger:
  29. def __init__(self, name: str, console_handler_level: str = logging.INFO, fmt: str = '%(asctime)s: %(name)s: %(levelname)s: %(filename)s: %(funcName)s: %(message)s'):
  30. self.logger = logging.getLogger(name)
  31. self.logger.setLevel(logging.INFO)
  32. self.fmt = logging.Formatter(fmt)
  33. self.set_console_handler(console_handler_level)
  34. def set_console_handler(self, console_handler_level: str = logging.INFO) -> None:
  35. ch = logging.StreamHandler()
  36. ch.setLevel(console_handler_level)
  37. ch.setFormatter(self.fmt)
  38. self.logger.addHandler(ch)
  39. def set_file_handler(self, filename: str, mode: str = "a", file_handler_level: str = logging.WARNING) -> None:
  40. fh = logging.FileHandler(filename, mode=mode, encoding='utf-8')
  41. fh.setLevel(file_handler_level)
  42. fh.setFormatter(self.fmt)
  43. self.logger.addHandler(fh)
  44. def debug(self, msg):
  45. self.logger.debug(msg)
  46. def info(self, msg):
  47. self.logger.info(msg)
  48. def warning(self, msg):
  49. self.logger.warning(msg)
  50. def error(self, msg):
  51. self.logger.error(msg)
  52. def critical(self, msg):
  53. self.logger.critical(msg)
  54. logger = Logger("resume_parse")
  55. logger.set_file_handler(filename='data.log')
  56. from rich.console import Console
  57. console = Console()
  58. import uvicorn
  59. from fastapi import BackgroundTasks, FastAPI, File, UploadFile
  60. app = FastAPI()
  61. ner = Taskflow("ner", mode='fast')
  62. ner_tag = Taskflow("ner")
  63. base_info_ie = Taskflow('information_extraction', schema=["姓名","性别","婚姻状况","电子邮箱","政治面貌","手机号码","籍贯","出生日期","现任职务","参加工作时间","英语水平","计算机水平","工作年限","当前单位","所在城市","职业资格"])
  64. prize_ie = Taskflow('information_extraction', schema=["时间", "奖项"])
  65. cet_ie = Taskflow('information_extraction', schema=["时间","证书"])
  66. pro_ie = Taskflow("information_extraction", schema=["时间","项目名称","机构","职位"], task_path='./model_100')
  67. global block, block_rev
  68. with open("resources/SegmentName.json", "r", encoding="utf-8") as fp:
  69. block = json.load(fp)
  70. block_rev = {1:"基本信息", 2:"求职意向", 3:"教育经历", 4:"工作经历", 5:"项目经历", 6:"专业技能", 7:"intro", 8:"兴趣爱好", 9:"语言能力", 10:"证书", 11:"获奖情况", 12:"培训经历", 13:"家庭成员", "other":"其他"}
  71. # 基本信息(旧版)
  72. def get_base_info_old(lines):
  73. logger.info(lines)
  74. schema = {
  75. '姓名': None,
  76. }
  77. for line in [' '.join(' '.join(lines).split('\n'))]:
  78. line = line.replace(r'[ ]{5,}','\n')
  79. w = re.sub(r'[\W]+(\w[::])[\W]{0,}\w', r'\1', line)
  80. for i in w.split():
  81. if ':' in i:
  82. try:
  83. key, val = i.split(':')
  84. schema[key] = val
  85. except Exception as e:
  86. logger.error(e)
  87. if not schema.get('姓名'):
  88. schema['姓名'] = re.search(r'[姓名::]{3,}(\w{2,4})', w).group(1) if re.search(r'[姓名::]{3,}(\w{2,4})', w) else None
  89. if not schema.get('姓名'):
  90. for word, tag in ner_tag(w):
  91. if tag == "人物类_实体":
  92. schema['姓名'] = word
  93. if not schema.get('性别'):
  94. schema['性别'] = re.search(r'[男女]', w).group() if re.search(r'[男女]', w) else None
  95. if not schema.get('婚姻状况'):
  96. schema['婚姻状况'] = re.search(r'[已未]婚', w).group() if re.search(r'[已未]婚', w) else None
  97. if not schema.get('电子邮箱'):
  98. schema['电子邮箱'] = re.search(r'([.\w]+@[.\w]+)', w).group() if re.search(r'([.\w]+@[.\w]+)', w) else None
  99. if not schema.get('政治面貌'):
  100. schema['政治面貌'] = re.search(r'[预备中共党团员群众无派人士]{2,6}', w).group() if re.search(r'[预备中共党团员群众无派人士]{2,6}', w) else None
  101. if not schema.get('手机号码'):
  102. schema['手机号码'] = re.search(r'\W(1[\d]{10})\W', w).group(1) if re.search(r'\W(1[\d]{10})\W', w) else None
  103. # if not schema.get('籍贯'):
  104. # schema['籍贯'] = re.search(r'[籍贯::]{3,}(\w{2,5})', w).group(1) if re.search(r'[籍贯::]{3,}(\w{2,})', w) else None
  105. if not schema.get('出生年月'):
  106. schema['出生年月'] = re.search(r'\d{4}[./年\-]\d{1,2}[月]', w).group() if re.search(r'\d{4}[./年\-]\d{1,2}[月]', w) else None
  107. # if not schema.get('当前职位'):
  108. # schema['当前职位'] = re.search(r'[当前职位: ]{3,}(\w)+', w).group() if re.search(r'[当前职位: ]{3,}(\w)+', w) else None
  109. # if not schema.get('参加工作时间'):
  110. # schema['参加工作时间'] = re.search(r'[参加工作时间:]{3,}(\d{4}[./年\-]\d{1,2}[月])', w).group(1) if re.search(r'[参加工作时间:]{3,}(\d{4}[./年\-]\d{1,2}[月])', w) else None
  111. return {key:value for key, value in schema.items() if value}
  112. # 基本信息(OIE 已完成)
  113. def get_base_info(lines):
  114. if not lines:
  115. return
  116. logger.info(lines)
  117. data = " ".join(lines)
  118. rst = base_info_ie(data)[0]
  119. if rst.get("出生日期"):
  120. dates = re.findall(r'\d+' ,rst["出生日期"][0]["text"])
  121. if len(dates) == 1:
  122. if len(dates[0]) > 4:
  123. rst["出生日期"][0]["text"] = "{:4d}-{:02d}-01".format(int(dates[0][:4]), int(dates[0][4:6]))
  124. else:
  125. rst["出生日期"][0]["text"] = "{:4d}-01-01".format(int(dates[0][:4]))
  126. elif len(dates) == 2:
  127. rst["出生日期"][0]["text"] = "{:4d}-{:02d}-01".format(int(dates[0]), int(dates[1]))
  128. elif len(dates) == 3:
  129. rst["出生日期"][0]["text"] = "{:4d}-{:02d}-01".format(int(dates[0]), int(dates[1]))
  130. if rst.get("参加工作时间"):
  131. dates = re.findall(r'\d+' ,rst["参加工作时间"][0]["text"])
  132. if len(dates) == 1:
  133. if len(dates[0]) > 4:
  134. rst["参加工作时间"][0]["text"] = "{:4d}-{:02d}-01".format(int(dates[0][:4]), int(dates[0][4:6]))
  135. else:
  136. rst["参加工作时间"][0]["text"] = "{:4d}-01-01".format(int(dates[0]))
  137. elif len(dates) == 2:
  138. rst["参加工作时间"][0]["text"] = "{:4d}-{:02d}-01".format(int(dates[0]), int(dates[1]))
  139. elif len(dates) == 3:
  140. rst["参加工作时间"][0]["text"] = "{:4d}-{:02d}-01".format(int(dates[0]), int(dates[1]))
  141. normal = {
  142. "姓名":"name",
  143. "性别":"gender",
  144. "电子邮箱":"email",
  145. "政治面貌":"politics",
  146. "手机号码":"mobile",
  147. "籍贯":"birthplace",
  148. "出生日期":"birth_time",
  149. "现任职务":"current_job",
  150. "所在城市":"living_city",
  151. "参加工作时间":"work_begin_time",
  152. }
  153. for key in normal.keys():
  154. if rst.get(key):
  155. rst[normal[key]] = rst[key]
  156. del rst[key]
  157. return {key:rst[key][0]["text"] for key in rst.keys()}
  158. # 求职意向(已完成)
  159. def get_job_intention(lines):
  160. logger.info(lines)
  161. schema = {}
  162. for line in lines:
  163. regex = re.compile(r'\W{0,3}[::]\s+')
  164. line = regex.sub(':', line)
  165. for i in line.split():
  166. if ":" in i:
  167. try:
  168. key, val = i.split(":")
  169. schema[key] = val
  170. except Exception as e:
  171. logger.error(e)
  172. return schema
  173. # 教育经历 (已停用)
  174. # ner + 分词 (判断学校,时间,学历) 专业需要单独处理。
  175. def get_edu_list_old(lines):
  176. logger.info(lines)
  177. job_list = []
  178. job_dict = {'edu_time_beg':'', 'edu_time_end':'', 'edu_name':'','edu_leval':'','edu_domain':'', 'edu_statue':0}
  179. re_txt = '\d{4,4}.\d{1,2}.?\040{0,2}[\-–至-\—~]\040{0,2}\d{4,4}.\d{1,2}[月]?|\d+\.\d+\-至今|\d+年\d+月\-\d+年\d+月|\d+年\d+月\-\~|\d+年\d+月[\-\~]至今|\d+-\d+\040{0,2}[\~至]\040{0,2}\d+-\d+|\d+-\d+\~|\d+-\d+\~至今|\d+-\d+\040{0,2}至今|^\d{4,4}.\d{1,2}|19\d{2,2}.|20\d{2,2}.'
  180. re_txt_1 = '\d{4,4}.\d{1,2}.?\040{0,2}[\-–至-\—~]\040{0,2}\d{4,4}.\d{1,2}[月]?|\d+\.\d+\-至今|\d+年\d+月\-\d+年\d+月|\d+年\d+月\-\~|\d+年\d+月[\-\~]至今|\d+-\d+\040{0,2}[\~至]\040{0,2}\d+-\d+|\d+-\d+\~|\d+-\d+\~至今|\d+-\d+\040{0,2}至今'
  181. nums = []
  182. for i in range(len(lines)):
  183. if re.findall(re_txt, lines[i]):
  184. nums.append(i)
  185. nums.append(len(lines))
  186. edu_level = {'本科':18, "大专":17, "博士研究生":20, "学士":18, "博士":20, "硕士":19, "研究生":19, "博后":21, '博士后':21}
  187. year_dict = {18:4, 17:3,20:3,19:3,21:2}
  188. edu_dict = {18:'本科', 17:'大专',20:'博士研究生',19:'硕士',21:'博士后'}
  189. edu_list = []
  190. for i in range(1, len(nums[:])):
  191. job_dict = {'edu_time_beg':'', 'edu_time_end':'', 'edu_name':'','edu_leval':'','edu_domain':''}
  192. data_list = lines[nums[i-1]:nums[i]]
  193. if len(data_list) > 1 and data_list[1] and data_list[1][-1] == '|' and data_list[0][-1] != '|':
  194. data_list[0] = data_list[0] + data_list[1]
  195. data_list[1] = ''
  196. if len(data_list) > 2 and data_list[2] and data_list[2][-1] == '|' and data_list[0][-1] != '|' and '|' in str(data_list[0]) and data_list[1] and data_list[1][-1] != '|':
  197. data_list[0] = data_list[0] + data_list[1] + data_list[2]
  198. data_list[1] = ''
  199. data_list[2] = ''
  200. if '' in data_list:
  201. data_list.remove('')
  202. data_line = ' '.join(data_list)
  203. data_line = re.sub('[\|]', ' ', data_line)
  204. data_line = re.sub('-{3,}', '', data_line)
  205. ner_data = ner(''.join(data_list[:2]))
  206. org = ''
  207. time_list = []
  208. for jj in range(1, len(ner_data)):
  209. if ner_data[jj][1] == ner_data[jj-1][1]:
  210. ner_data[jj] = list(ner_data[jj])
  211. ner_data[jj][0] = ner_data[jj-1][0] + ner_data[jj][0]
  212. ner_data[jj-1] = ('','')
  213. for _ in ner_data:
  214. if _[1] == 'ORG' and not org:
  215. org = _[0].strip()
  216. elif _[1] == 'TIME' and len(_[1]) >= 4:
  217. time_list.append(_[0])
  218. #TIME
  219. # print(data_line)
  220. _list_data = re.split('\040+',data_line)
  221. top_level = 18
  222. remove_list = []
  223. logger.info(_list_data)
  224. logger.info(time_list)
  225. for ii in range(len(_list_data)):
  226. for t in time_list:
  227. if t in _list_data[ii]:
  228. _list_data[ii] = ''
  229. break
  230. for i in range(len(_list_data)):
  231. #if org in _list_data[i]:
  232. # _list_data[i] = ''
  233. if re.findall('^\d{4,4}', _list_data[i]):
  234. _list_data[i] = ''
  235. _data = re.findall('本科|学士|硕士|博士研究生|博士后|博后|博士|研究生|大专', _list_data[i])
  236. if not _data:
  237. continue
  238. top_level = edu_level[_data[0]]
  239. _list_data[i] = ''
  240. break
  241. #remove_list.append(i)
  242. logger.info(_list_data)
  243. job_time = re.findall(re_txt_1, data_list[0])
  244. if job_time:
  245. job_dict['edu_time'] = job_time[0]
  246. else:
  247. job_dict['edu_time'] = ''
  248. _nums = re.findall('\d+', job_dict['edu_time'])
  249. if len(_nums) >= 4:
  250. job_dict['edu_time_beg'] = '%s-%02d'%(_nums[0], int(_nums[1]))
  251. job_dict['edu_time_end'] = '%s-%02d'%(_nums[2], int(_nums[3]))
  252. job_dict['edu_time'] = '%s-%02d~%s-%02d'%(_nums[0], int(_nums[1]), _nums[2], int(_nums[3]))
  253. elif len(_nums) == 2:
  254. job_dict['edu_time'] = '%s-%02d~%s'%(_nums[0], int(_nums[1]), '至今')
  255. job_dict['edu_time_beg'] = '%s-%02d'%(_nums[0], int(_nums[1]))
  256. job_dict['edu_time_end'] = '%s'%('至今')
  257. elif len(time_list) == 2:
  258. nums_1 = re.findall('\d+', time_list[0])
  259. nums_2 = re.findall('\d+', time_list[1])
  260. nums_1.append('09')
  261. nums_2.append('07')
  262. job_dict['edu_time_beg'] = '%s-%02d'%(nums_1[0], int(nums_1[1]))
  263. try:
  264. job_dict['edu_time_end'] = '%s-%02d'%(nums_2[0], int(nums_2[1]))
  265. except:
  266. job_dict['edu_time_end'] = None
  267. try:
  268. job_dict['edu_time'] = '%s-%02d~%s-%02d'%(nums_1[0], int(nums_1[1]), nums_2[0], int(nums_2[1]))
  269. except:
  270. job_dict['edu_time'] = '%s-%02d~今'%(nums_1[0], int(nums_1[1]))
  271. elif len(time_list) == 1:
  272. _nums = re.findall('\d+', time_list[0])
  273. if '毕业' in data_list[0]:
  274. _nums.append('06')
  275. _nums.insert(0, '09')
  276. _nums.insert(0, str(int(_nums[1]) - year_dict[top_level]))
  277. job_dict['edu_time'] = '%s-%02d~%s-%02d'%(_nums[0], int(_nums[1]), _nums[2], int(_nums[3]))
  278. job_dict['edu_time_beg'] = '%s-%02d'%(_nums[0], int(_nums[1]))
  279. job_dict['edu_time_end'] = '%s-%02d'%(_nums[2], int(_nums[3]))
  280. else:
  281. _nums.append('09')
  282. job_dict['edu_time'] = '%s-%02d~%s'%(_nums[0], int(_nums[1]), '至今')
  283. job_dict['edu_time_beg'] = '%s-%02d'%(_nums[0], int(_nums[1]))
  284. job_dict['edu_time_end'] = '%s'%('至今')
  285. job_dict['edu_leval'] = edu_dict[top_level]
  286. if org:
  287. job_dict['edu_name'] = org
  288. else:
  289. job_dict['edu_name'] = ''
  290. edu_domain = ''
  291. for i in range(len(_list_data)):
  292. if org in _list_data[i]:
  293. continue
  294. if not _list_data[i] and '专业' in _list_data[i]:
  295. edu_domain = _list_data[i]
  296. if not edu_domain:
  297. for i in range(len(_list_data)):
  298. if org in _list_data[i]:
  299. continue
  300. if _list_data[i] and len(_list_data[i]) >= 3:
  301. edu_domain = _list_data[i]
  302. break
  303. if not edu_domain:
  304. for i in range(len(_list_data)):
  305. if org in _list_data[i]:
  306. for j in range(i+1, len(_list_data)):
  307. if _list_data[i] and len(_list_data[j]) >= 2:
  308. edu_domain = _list_data[j]
  309. break
  310. break
  311. job_dict['edu_domain'] = edu_domain
  312. if len(job_list) ==0:
  313. job_list.append(job_dict)
  314. else:
  315. if job_dict in job_list:
  316. continue
  317. if not job_dict['edu_time']:
  318. continue
  319. if int(job_dict['edu_time'][:4]) > int(job_list[-1]['edu_time'][:4]):
  320. job_list = [job_dict] + job_list
  321. else:
  322. job_list.append(job_dict)
  323. continue
  324. data_list[0] = re.sub(job_time[0], '', data_list[0])
  325. _list = re.split('\|\040+', data_list[0])
  326. #print(_list)
  327. if len(_list) == 1:
  328. __list = re.split('\040+', data_list[0])
  329. job_dict['edu_name'] = __list[1].strip()
  330. job_dict['edu_domain'] = __list[2].strip()
  331. job_dict['edu_leval'] = __list[3].strip()
  332. else:
  333. #if job_dict['edu_leval'] not in
  334. if len(_list) > 3:
  335. job_dict['edu_name'] = _list[2].strip()
  336. job_dict['edu_domain'] = _list[3].strip()
  337. job_dict['edu_leval'] = _list[1].strip()
  338. else:
  339. job_dict['edu_leval'] = _list[0].strip()
  340. job_dict['edu_name'] = _list[1].strip()
  341. job_dict['edu_domain'] = _list[2].strip()
  342. if '硕士' in _list[0] or '研究生' in _list[0]:
  343. job_dict['edu_leval'] = '硕士'
  344. elif '博士' in _list[0]:
  345. job_dict['edu_leval'] = '博士'
  346. elif '本科' in _list[0]:
  347. job_dict['edu_leval'] = '本科'
  348. elif '学士' in _list[0]:
  349. job_dict['edu_leval'] = '本科'
  350. # print(job_dict)
  351. if len(job_list) ==0:
  352. job_list.append(job_dict)
  353. else:
  354. if job_dict in job_list:
  355. continue
  356. if int(job_dict['edu_time'][:4]) > int(job_list[-1]['edu_time'][:4]):
  357. job_list = [job_dict] + job_list
  358. else:
  359. job_list.append(job_dict)
  360. #edu_list.append(job_dict['edu_time'] + job_dict['edu_name'] + job_dict['edu_domain'] + job_dict['edu_leval'])
  361. #if job_list[0]['edu_leval'] not in ['硕士', '博士', '本科', '博后'] and len(job_list[0]['edu_leval']) > 5:
  362. # job_list[0]['edu_leval'] = '本科'
  363. return job_list
  364. # 教育经历改 (已完成)
  365. def get_edu_list(lines):
  366. logger.info(lines)
  367. edu_list = [{"Time":None, "start_time":None, "end_time":None, "school_name":None, "major":None, "degree":None}]
  368. regex_time = re.compile(r'((\d{4})[年\W]{1,2}(\d{1,2})[月\W]?[\d]{0,2})[至到\W]+((\d{4})[年\W]{1,2}(\d{1,2})[月\W]?)?([今])?|(\d{4})[至\W]+([\d今]{4})')
  369. regex_end = re.compile(r'毕业时间[\w\W]{0,5}(\d{4})[\W年]?(\d{0,2})[月\W]?')
  370. regex_level = re.compile(r'[大本专科硕博士研究生后]{2,}')
  371. regex_domain = re.compile(u'[\u4E00-\u9FA5]{2,10}', re.UNICODE)
  372. count = 0
  373. for line in lines:
  374. line = line.replace("学士","本科").replace("专业","").replace("学位","")
  375. for cell in re.split(r'[·\|\t]', line):
  376. if not cell.strip():
  377. continue
  378. flags = 0
  379. edu_time = regex_time.search(cell)
  380. edu_end_time = regex_end.search(cell)
  381. edu_level = regex_level.search(cell)
  382. edu_domain = regex_domain.search(cell)
  383. # 标准时间格式
  384. if edu_time:
  385. # 提交信息
  386. if edu_list[count].get("Time") and edu_list[count].get("school_name"):
  387. edu_list.append({"Time":None, "start_time":None, "end_time":None, "school_name":None, "major":None, "degree":None})
  388. count += 1
  389. edu_list[count]["start_time"] = '{:4d}-{:02d}'.format(int(edu_time.group(2)),int(edu_time.group(3)))
  390. # 年月日
  391. if edu_time.group(5) != None:
  392. edu_list[count]["end_time"] = '{:4d}-{:02d}'.format(int(edu_time.group(5)),int(edu_time.group(6)))
  393. edu_list[count]["Time"] = '{:4d}-{:02d}~{:4d}-{:02d}'.format(int(edu_time.group(2)),int(edu_time.group(3)),int(edu_time.group(5)),int(edu_time.group(6)))
  394. # 只有年
  395. elif edu_time.group(8) != None:
  396. edu_list[count]["Time"] = '{:4d}~{:4d}'.format(int(edu_time.group(8)),int(edu_time.group(9)))
  397. edu_list[count]["start_time"] = '{:4d}'.format(int(edu_time.group(8)))
  398. edu_list[count]["end_time"] = '{:4d}'.format(int(edu_time.group(9)))
  399. # 至今类
  400. elif edu_time.group(7):
  401. edu_list[count]["end_time"] = edu_time.group(7)
  402. edu_list[count]['Time'] = '{:4d}-{:02d}~{}'.format(int(edu_time.group(2)),int(edu_time.group(3)),edu_time.group(7))
  403. flags = 1
  404. # 只有毕业时间
  405. elif edu_end_time:
  406. # 提交信息
  407. if edu_list[count].get("end_time") and edu_list[count].get("school_name"):
  408. edu_list.append({"Time":None, "start_time":None, "end_time":None, "school_name":None, "major":None, "degree":None})
  409. count += 1
  410. # 年月
  411. if edu_end_time.group(2):
  412. edu_list[count]["Time"] = '{:4d}-{:02d}~{:4d}-{:02d}'.format(int(edu_end_time.group(1))-3,int(edu_end_time.group(2)),int(edu_end_time.group(1)),int(edu_end_time.group(2)))
  413. edu_list[count]["end_time"] = '{:4d}-{:02d}'.format(int(edu_end_time.group(1)),int(edu_end_time.group(2)))
  414. # 只有年
  415. elif edu_end_time.group(1):
  416. edu_list[count]["Time"] = '{:4d}~{:4d}'.format(int(edu_end_time.group(1))-3,int(edu_end_time.group(1)))
  417. edu_list[count]["end_time"] = '{:4d}'.format(int(edu_end_time.group(1)))
  418. # 学历
  419. if (not edu_list[count].get("degree")) and edu_level:
  420. edu_list[count]["degree"] = edu_level.group(0)
  421. # WordTag 识别 学校/专业
  422. for word, tag in ner_tag(cell):
  423. if (not edu_list[count].get("school_name")) and (tag == "组织机构类_教育组织机构"):
  424. edu_list[count]["school_name"] = word.strip()
  425. flags = 1
  426. elif (not edu_list[count].get("major")) and (tag in "_术语类型"):
  427. edu_list[count]["major"] = word.strip()
  428. elif edu_list[count].get("school_name") and edu_list[count].get("major"):
  429. break
  430. # LAC 识别 学校
  431. else:
  432. for word, tag in ner(cell):
  433. if (tag == "ORG"):
  434. edu_list[count]["school_name"] = word
  435. flags = 1
  436. break
  437. # 未识别成功时填充专业
  438. if (not (edu_level or flags or edu_list[count].get("major"))) and edu_domain:
  439. edu_list[count]["major"] = edu_domain.group(0)
  440. # 剔除时间不存在、学校不存在的列
  441. if (not edu_list[-1].get("Time")) or (not edu_list[-1].get("school_name")):
  442. edu_list.pop()
  443. return edu_list
  444. # 工作经历 (已完成)
  445. # ner + 分词 机构信息,人物身份信息,时间 工作内容区分判断
  446. # 其中,时间是判断是否下一份工作情况的主要标识符之一。字符数量
  447. # 时间类 数量词
  448. def get_job_list(lines):
  449. logger.info(lines)
  450. job_list = []
  451. re_txt = '\d{4,4}\040{0,2}.\d+\040{0,2}.?\040{0,2}[\-–至-\—~]{1,2}\040{0,2}\d{4,4}\040{0,2}.\040{0,2}\d+.?|\d{4,4}.\d+.?\040{0,2}[\-–-—]{0,2}\040{0,2}至?今|\d{4,4}.\d+.?\040{0,2}[\-–-]{1,2}\040{0,2}现在|\d{4,4}年\d+月\-\d{4,4}年\d+月|\d{4,4}年\d+月\-\~|\d{4,4}年\d+月[\-\~-]至今|\d{4,4}-\d+\040{0,2}[-\~至]\040{0,2}\d{4,4}-\d+|\d{4,4}-\d+\~|\d{4,4}-\d+\[~-]至今|\d{4,4}-\d+\040{0,2}至今'
  452. nums = []
  453. for i in range(len(lines)):
  454. #print(lines[i])
  455. #print(lines[i], re.findall(re_txt, lines[i]), re.findall('\||\040{1,}', lines[i]))
  456. if re.findall(re_txt, lines[i].replace(' ', '')) and re.findall('\||\040{1,}', lines[i]):
  457. nums.append(i)
  458. continue
  459. if re.findall(re_txt, lines[i].replace(' ', '')[:20]):
  460. nums.append(i)
  461. continue
  462. if len(lines[i].strip().replace(' ', '')) > 50:
  463. continue
  464. year_list = re.findall('19\d{2,2}.\d{1,2}|20\d{2,2}.\d{1,2}', lines[i])
  465. if len(year_list) >= 2:
  466. nums.append(i)
  467. elif len(year_list) == 1 and '至今' in lines[i]:
  468. nums.append(i)
  469. nums.append(len(lines))
  470. # logger.info(nums)
  471. logger.info('get_job_list :{}'.format(nums))
  472. for i in range(1, len(nums[:])):
  473. job_dict = {'job_time':'', 'job_leval':'','job_company':'','job_content':''}
  474. data_list = lines[nums[i-1]:nums[i]]
  475. if '' in data_list:
  476. data_list.remove('')
  477. org = ''
  478. person_professor_list = []
  479. org_index = -1
  480. end_index = 3
  481. job_time = re.findall(re_txt, data_list[0])
  482. if not job_time:
  483. year_list = re.findall('19\d{2,2}.\d{1,2}|20\d{2,2}.\d{1,2}', data_list[0])
  484. if len(year_list) >= 2:
  485. job_time = ['-'.join(year_list)]
  486. elif len(year_list) == 1 and '至今' in lines[i]:
  487. job_time = [year_list[0] + '~' + '至今']
  488. if not job_time:
  489. regex = re.compile(r'((\d{4})[年\W]+(\d{1,2})[\W]?[\w]?)[至到\W]+((\d{4})[年\W]+(\d{1,2})[\W]?[\w]?)?([今])?')
  490. job_time = [re.search(regex, data_list[0]).group(0)]
  491. job_dict['job_time'] = job_time[0]
  492. _nums = re.findall('\d{1,4}', job_dict['job_time'])
  493. #print(_nums)
  494. if len(_nums) >= 4:
  495. job_dict['job_time'] = '%s-%02d~%s-%02d'%(_nums[0], int(_nums[1]), _nums[2], int(_nums[3]))
  496. elif len(_nums) == 2:
  497. job_dict['job_time'] = '%s-%02d~%s'%(_nums[0], int(_nums[1]), '至今')
  498. if re.findall('\d', job_time[0]):
  499. job_time[0] = job_time[0][:-1]
  500. data_list[0] = re.sub(job_time[0], '', data_list[0])
  501. data_list[0] = data_list[0].strip()
  502. ner_list = []
  503. for ii in range(len(data_list[:3])):
  504. if '工作' in data_list[ii][:4] and (re.findall(':|\:', data_list[ii])):
  505. end_index = ii
  506. break
  507. #print(re.findall('\040|\||/', data_list[ii].strip()), org)
  508. if not re.findall('\040|\||/', data_list[ii].strip()) and org:
  509. end_index = ii
  510. break
  511. if len(data_list[ii]) > 80:
  512. end_index = ii
  513. break
  514. if data_list[ii]:
  515. ner_data = ner_tag(data_list[ii].strip())
  516. #print('\n\nnerdata:\t',ner_data)
  517. else:
  518. continue
  519. ner_list.append(ner_data)
  520. for x in ner_data:
  521. if x[1] == '人物类_概念' and len(x[0]) > 2:
  522. person_professor_list.append(x[0].strip())
  523. elif x[1] == '组织机构类_企事业单位' or x[1] == '组织机构类_教育组织机构' or x[1] == '组织机构类_国家机关':
  524. if not org and len(x[0]) >= 3:
  525. org = re.split('\040|\|/', x[0].strip())[0]
  526. org_index = ii
  527. if not org:
  528. for ii in range(len(ner_list)):
  529. if org:
  530. break
  531. ner_data = ner_list[ii]
  532. for x in ner_data:
  533. if x[1][:5] == '组织机构类':
  534. org = re.split('\040|\|/', x[0].strip())[0]
  535. break
  536. #print(person_professor_list)
  537. if not person_professor_list:
  538. for ii in range(len(ner_list)):
  539. ner_data = ner_list[ii]
  540. for x in ner_data:
  541. if x[1] == '人物类_概念':
  542. person_professor_list = [re.split('\040|\|/', x[0].strip())[0]]
  543. break
  544. data_line = ' '.join(data_list[:end_index])
  545. data_line = re.sub('\||/', ' ', data_line)
  546. _list_data = re.split('\040+', data_line)
  547. if len(_list_data) == 1 and len(data_list) == 1:
  548. end_index = 0
  549. #print(_list_data)
  550. if not person_professor_list:
  551. for x in range(len(_list_data)):
  552. if re.findall('经理|工程师|会计|董事长|总监|秘书|主管|处长|局长|主任|讲师|教授', _list_data[x][-4:]):
  553. person_professor_list.append(_list_data[x])
  554. if not org:
  555. for x in range(len(_list_data)):
  556. if len(_list_data[x]) < 4:
  557. _list_data[x] = ''
  558. elif person_professor_list and re.findall('|'.join(person_professor_list), _list_data[x]):
  559. _list_data[x] = ''
  560. elif '经理' == _list_data[x][-2:]:
  561. _list_data[x] = ''
  562. for x in range(len(_list_data)):
  563. if _list_data[x]:
  564. org = _list_data[x]
  565. break
  566. if not person_professor_list:
  567. for x in range(len(_list_data)):
  568. if org in _list_data[x]:
  569. for j in range(x+1, len(_list_data)):
  570. if _list_data[j]:
  571. person_professor_list = [_list_data[j]]
  572. break
  573. break
  574. #print(org, person_professor_list, job_time)
  575. job_dict['job_company'] = org
  576. job_dict['job_leval'] = ' '.join(person_professor_list)
  577. if not data_list[end_index:] and end_index == 3:
  578. end_index = 2
  579. if not data_list[end_index:] and end_index == 2:
  580. end_index = 1
  581. job_dict['job_content'] = re.sub('工工作作内内容容::|工工作作内内容容::|工工作作内内容容', '工作内容:', ''.join(data_list[end_index:]))
  582. job_dict['job_content'] = re.sub('/', '-', job_dict['job_content'])
  583. job_dict['start_time'] = job_dict['job_time'].split('~')[0]
  584. job_dict['end_time'] = job_dict['job_time'].split('~')[1]
  585. normal = {"job_company":"company_name","job_content":"job_desc","job_leval":"job_name"}
  586. for key in normal.keys():
  587. if job_dict.get(key):
  588. job_dict[normal[key]] = job_dict[key]
  589. job_dict.pop(key)
  590. job_list.append(job_dict)
  591. continue
  592. if len(data_list) > 1 and data_list[1] and data_list[1][-1] == '|':# and data_list[0] and data_list[0][-1] != '|':
  593. data_list[0] = data_list[0] + data_list[1]
  594. data_list[1] = ''
  595. elif len(data_list) > 2 and data_list[2] and data_list[2][-1] == '|' and data_list[0][-1] != '|' and '|' in str(data_list[0]) and data_list[1] and data_list[1][-1] != '|':
  596. data_list[0] = data_list[0] + data_list[1] + data_list[2]
  597. data_list[1] = ''
  598. data_list[2] = ''
  599. elif len(data_list) > 1 and data_list[1] and '工作职责:' in data_list[2]:
  600. data_list[0] = data_list[0] + data_list[1]
  601. data_list[1] = ''
  602. elif len(data_list) > 1 and '工作职责:' in data_list[3]:
  603. data_list[0] = data_list[0] + data_list[1] + data_list[2]
  604. data_list[1] = ''
  605. data_list[2] = ''
  606. job_time = re.findall(re_txt, data_list[0])
  607. job_dict['job_time'] = job_time[0]
  608. _nums = re.findall('\d+', job_dict['job_time'])
  609. #print(_nums)
  610. if len(_nums) >= 4:
  611. job_dict['job_time'] = '%s-%02d~%s-%02d'%(_nums[0], int(_nums[1]), _nums[2], int(_nums[3]))
  612. elif len(_nums) == 2:
  613. job_dict['job_time'] = '%s-%02d~%s'%(_nums[0], int(_nums[1]), '至今')
  614. data_list[0] = re.sub(job_time[0], '', data_list[0])
  615. data_list[0] = data_list[0].strip()
  616. data_list[0] = re.sub('历任:', ' ', data_list[0])
  617. _list = data_list[0].split('|')
  618. if len(_list) == 1:
  619. __list = re.split('\040{2,}', data_list[0])
  620. #print(__list)
  621. job_dict['job_leval'] = __list[1].strip()
  622. job_dict['job_company'] = __list[0].strip()
  623. else:
  624. job_dict['job_leval'] = _list[0].strip()
  625. job_dict['job_company'] = _list[1].strip()
  626. if '职级:' in data_list[1:]:
  627. data_list.remove('职级:')
  628. job_dict['job_content'] = re.sub('工工作作内内容容::|工工作作内内容容::|工工作作内内容容', '工作内容:', ''.join(data_list[1:]))
  629. job_dict['job_content'] = re.sub('/', '-', job_dict['job_content'])
  630. #print(job_dict)
  631. job_list.append(job_dict)
  632. return job_list
  633. # 项目经历 (已弃用)
  634. # 项目名称未知
  635. def get_pro_list_old(lines):
  636. logger.info(lines)
  637. pro_list = [{"Time":None,"startTime":None,"endTime":None,"pro_name":None,"job_leval":None,"job_company":None,"content":None,},]
  638. regex = re.compile(r'((\d{4})[年\W]+(\d{1,2})[\W]?[\w]?)[至到\W]+((\d{4})[年\W]+(\d{1,2})[\W]?[\w]?)?([今])?')
  639. re_con = re.compile(r'负责内容(.*?)')
  640. re_na = re.compile(r'\W(.*?项目)\W')
  641. count = 0
  642. for line in lines:
  643. regex_time = regex.search(line)
  644. regex_content = re_con.search(line)
  645. regex_name = re_na.search(line)
  646. if regex_time:
  647. if pro_list[count].get("Time"):
  648. pro_list.append({"Time":None,"startTime":None,"endTime":None,"pro_name":None,"job_leval":None,"job_company":None,"content":None,})
  649. count += 1
  650. pro_list[count]["startTime"] = '{:4d}-{:02d}'.format(int(regex_time.group(2)),int(regex_time.group(3)))
  651. if regex_time.group(5) != None:
  652. pro_list[count]["endTime"] = '{:4d}-{:02d}'.format(int(regex_time.group(5)),int(regex_time.group(6)))
  653. pro_list[count]["Time"] = '{:4d}-{:02d}~{:4d}-{:02d}'.format(int(regex_time.group(2)),int(regex_time.group(3)),int(regex_time.group(5)),int(regex_time.group(6)))
  654. else:
  655. pro_list[count]["endTime"] = regex_time.group(7)
  656. pro_list[count]['Time'] = '{:4d}-{:02d}~{}'.format(int(regex_time.group(2)),int(regex_time.group(3)),regex_time.group(7))
  657. elif regex_name and (not pro_list[count].get("job_name")):
  658. pro_list[count]["pro_name"] = regex_name.group()
  659. elif pro_list[count].get("content"):
  660. pro_list[count]["content"] += line
  661. else:
  662. try:
  663. for word, tag in ner_tag(line):
  664. if (not pro_list[count].get("job_leval")) and (tag == "人物类_概念"):
  665. pro_list[count]["job_leval"] = word
  666. if (not pro_list[count].get("job_company")) and (tag in "组织机构类_企事业单位"):
  667. pro_list[count]["job_company"] = word
  668. except Exception as e:
  669. logger.error(e)
  670. pro_list[count]["content"] = line
  671. return pro_list
  672. # 项目经历 (UIE 已完成)
  673. def get_pro_list(lines):
  674. logger.info(lines)
  675. starts = []
  676. # 时间查找
  677. for index, line in enumerate(lines):
  678. if re.search(r'\d{4}', line):
  679. starts.append(index)
  680. # 简单筛选
  681. count = len(starts)
  682. c = (starts[-1] - starts[0])/count
  683. for i in range(count-1):
  684. if (starts[i+1]-starts[i] < c/2):
  685. starts[i+1] = starts[i]
  686. # 合并
  687. pro_list = []
  688. pros = {}
  689. index = 0
  690. for i in range(len(lines)):
  691. if i in starts:
  692. index = i
  693. pros[index] = [lines[i], []]
  694. pros[index][1].append(lines[i])
  695. elif not pros:
  696. continue
  697. else:
  698. pros[index][0] += lines[i]
  699. pros[index][1].append(lines[i])
  700. # 提取
  701. for key in pros.keys():
  702. info = pro_ie(pros[key][0])
  703. src = pros[key][1]
  704. for rst in info:
  705. if not rst.get("时间") or not rst.get("项目名称"):
  706. continue
  707. rst["工作内容"] = [{"text":""}]
  708. logger.info(rst)
  709. for l in src:
  710. if rst["时间"][0]["text"] in l:
  711. continue
  712. else:
  713. rst["工作内容"][0]["text"] += l
  714. for key in rst.keys():
  715. if key == "时间":
  716. time_list = [None, None, None, None, None, None]
  717. tim_list = re.findall(r'\d+', rst["时间"][0]["text"])
  718. i = 0
  719. for t in tim_list:
  720. if (len(t) == 4) and (i != 0):
  721. i = 3
  722. time_list[i] = t
  723. else:
  724. time_list[i] = t
  725. i += 1
  726. else:
  727. continue
  728. if time_list[3] is not None:
  729. if time_list[4] is not None:
  730. rst["时间"][0]["text"] = "{:4d}-{:02d}~{:4d}-{:02d}".format(int(time_list[0]),int(time_list[1]),int(time_list[3]),int(time_list[4]))
  731. else:
  732. rst["时间"][0]["text"] = "{:4d}~{:4d}".format(int(time_list[0]),int(time_list[3]))
  733. else:
  734. if time_list[1] is not None:
  735. rst["时间"][0]["text"] = "{:4d}-{:02d}~至今".format(int(time_list[0]),int(time_list[1]))
  736. else:
  737. rst["时间"][0]["text"] = "{:4d}~至今".format(int(time_list[0]))
  738. normal = {"时间":"Time","项目名称":"project_name","机构":"company_name","职位":"project_duty","工作内容":"project_desc"}
  739. for key in normal.keys():
  740. if rst.get(key):
  741. rst[normal[key]] = rst[key]
  742. rst.pop(key)
  743. pro_list.extend([{key:rst[key][0]["text"] for key in rst.keys()} for rst in info])
  744. return pro_list
  745. # 培训经历 (已完成)
  746. # ner + 分词 (机构名) 培训项目 时间
  747. def get_cultivate_list(lines):
  748. logger.info(lines)
  749. job_list = []
  750. re_txt = '\d{4,4}.\d{1,2}.?\040{0,2}[\-–至-\—~]\040{0,2}\d{4,4}.\d{1,2}[月]?|\d+\.\d+\-至今|\d+年\d+月\-\d+年\d+月|\d+年\d+月\-\~|\d+年\d+月[\-\~]至今|\d+-\d+\040{0,2}[\~至]\040{0,2}\d+-\d+|\d+-\d+\~|\d+-\d+\~至今|\d+-\d+\040{0,2}至今|^\d{4,4}.\d{1,2}|\d{4,4}.'
  751. re_txt_1 = '\d{4,4}.\d{1,2}.?\040{0,2}[\-–至-\—~]\040{0,2}\d{4,4}.\d{1,2}[月]?|\d+\.\d+\-至今|\d+年\d+月\-\d+年\d+月|\d+年\d+月\-\~|\d+年\d+月[\-\~]至今|\d+-\d+\040{0,2}[\~至]\040{0,2}\d+-\d+|\d+-\d+\~|\d+-\d+\~至今|\d+-\d+\040{0,2}至今'
  752. nums = []
  753. for i in range(len(lines)):
  754. if re.findall(re_txt, lines[i].replace(' ', '')) and re.findall('\||\040{1,}', lines[i]):
  755. nums.append(i)
  756. continue
  757. if re.findall(re_txt, lines[i].replace(' ', '')[:20]):
  758. nums.append(i)
  759. if len(lines[i].strip().replace(' ', '')) > 50:
  760. continue
  761. nums.append(len(lines))
  762. year_dict = {18:4, 17:3,20:3,19:3,21:2,22:1}
  763. for i in range(1, len(nums[:])):
  764. job_dict = {'cultivate_time':'', 'cultivate_time_beg':'', 'cultivate_time_end':'', 'cultivate_name':'','cultivate_leval':'','cultivate_content':''}
  765. data_list = lines[nums[i-1]:nums[i]]
  766. data_line = ' '.join(data_list)
  767. data_line = re.sub('[\|\t]', ' ', data_line)
  768. data_line = re.sub('-{3,}', '', data_line)
  769. ner_data = ner(''.join(data_list[:2]))
  770. org = ''
  771. time_list = []
  772. for _ in ner_data:
  773. if _[1] == 'ORG' and not org:
  774. org = _[0].strip()
  775. elif _[1] == 'TIME' and len(_[1]) >= 4:
  776. time_list.append(_[0])
  777. #TIME
  778. logger.info(data_line)
  779. _list_data = re.split('\040+', data_line)
  780. top_level = 22
  781. end_index = 0
  782. remove_list = []
  783. if len(_list_data) <= 2:
  784. end_index = 0
  785. #continue
  786. job_time = re.findall(re_txt_1, data_list[0])
  787. if job_time:
  788. job_dict['cultivate_time'] = job_time[0]
  789. data_list[0] = re.sub(job_time[0], '', data_list[0])
  790. else:
  791. job_dict['cultivate_time'] = ''
  792. for t in time_list:
  793. data_list[0] = re.sub(t, '', data_list[0])
  794. _list = data_list[0].split('|')
  795. if len(_list) >= 2:
  796. job_dict['cultivate_name'] = _list[0].strip()
  797. job_dict['cultivate_leval'] = _list[1].strip()
  798. end_index = 1
  799. _nums = re.findall('\d+', job_dict['cultivate_time'])
  800. if len(_nums) >= 4:
  801. job_dict['cultivate_time_beg'] = '%s-%02d'%(_nums[0], int(_nums[1]))
  802. job_dict['cultivate_time_end'] = '%s-%02d'%(_nums[2], int(_nums[3]))
  803. job_dict['cultivate_time'] = '%s-%02d~%s-%02d'%(_nums[0], int(_nums[1]), _nums[2], int(_nums[3]))
  804. elif len(_nums) == 2:
  805. job_dict['cultivate_time'] = '%s-%02d~%s'%(_nums[0], int(_nums[1]), '至今')
  806. job_dict['cultivate_time_beg'] = '%s-%02d'%(_nums[0], int(_nums[1]))
  807. job_dict['cultivate_time_end'] = '%s'%('至今')
  808. elif len(time_list) == 2:
  809. nums_1 = re.findall('\d+', time_list[0])
  810. nums_2 = re.findall('\d+', time_list[1])
  811. nums_1.append('09')
  812. nums_2.append('07')
  813. job_dict['cultivate_time_beg'] = '%s-%02d'%(nums_1[0], int(nums_1[1]))
  814. job_dict['cultivate_time_end'] = '%s-%02d'%(nums_2[0], int(nums_2[1]))
  815. job_dict['cultivate_time'] = '%s-%02d~%s-%02d'%(nums_1[0], int(nums_1[1]), nums_2[0], int(nums_2[1]))
  816. elif len(time_list) == 1:
  817. _nums = re.findall('\d+', time_list[0])
  818. if '获得' in data_list[0]:
  819. _nums.append('01')
  820. _nums.insert(0, '01')
  821. _nums.insert(0, str(int(_nums[1]) - year_dict[top_level]))
  822. job_dict['cultivate_time'] = '%s-%02d~%s-%02d'%(_nums[0], int(_nums[1]), _nums[2], int(_nums[3]))
  823. job_dict['cultivate_time_beg'] = '%s-%02d'%(_nums[0], int(_nums[1]))
  824. job_dict['cultivate_time_end'] = '%s-%02d'%(_nums[2], int(_nums[3]))
  825. else:
  826. _nums.append('01')
  827. job_dict['cultivate_time'] = '%s-%02d~%s'%(_nums[0], int(_nums[1]), '至今')
  828. job_dict['cultivate_time_beg'] = '%s-%02d'%(_nums[0], int(_nums[1]))
  829. job_dict['cultivate_time_end'] = '%s'%('至今')
  830. job_dict['cultivate_content'] = re.sub('培培训训内内容容::|培培训训内内容容::|培培训训内内容容', '培训内容:', ''.join(data_list[end_index:]))
  831. if not job_dict['cultivate_name']:
  832. job_dict['cultivate_name'] = org
  833. logger.info(job_dict)
  834. job_list.append(job_dict)
  835. continue
  836. '''
  837. #print(nums)
  838. for i in range(1, len(nums[:])):
  839. job_dict = {'cultivate_time':'', 'cultivate_name':'','cultivate_leval':'','cultivate_content':''}
  840. data_list = lines[nums[i-1]:nums[i]]
  841. if '' in data_list:
  842. data_list.remove('')
  843. if len(data_list) > 1 and data_list[1] and data_list[1][-1] == '|' and data_list[0][-1] != '|':
  844. data_list[0] = data_list[0] + data_list[1]
  845. data_list[1] = ''
  846. job_time = re.findall(re_txt_1, data_list[0])
  847. job_dict['cultivate_time'] = job_time[0]
  848. _nums = re.findall('\d+', job_dict['cultivate_time'])
  849. if len(_nums) >= 4:
  850. job_dict['cultivate_time'] = '%s-%02d~%s-%02d'%(_nums[0], int(_nums[1]), _nums[2], int(_nums[3]))
  851. elif len(_nums) == 2:
  852. job_dict['cultivate_time'] = '%s-%02d~%s'%(_nums[0], int(_nums[1]), '至今')
  853. data_list[0] = re.sub(job_time[0], '', data_list[0])
  854. _list = data_list[0].split('|')
  855. if len(_list) >= 2:
  856. job_dict['cultivate_name'] = _list[0].strip()
  857. job_dict['cultivate_leval'] = _list[1].strip()
  858. job_dict['cultivate_content'] = re.sub('培培训训内内容容|培培训训内内容容::|培培训训内内容容::', '培训内容:', ''.join(data_list[1:]))
  859. else:
  860. job_dict['cultivate_content'] = re.sub('培培训训内内容容|培培训训内内容容::|培培训训内内容容::', '培训内容:', ''.join(data_list[0:]))
  861. #print(job_dict)
  862. '''
  863. return job_list
  864. # 语言能力(已完成)
  865. def get_lag_list(lines):
  866. logger.info(lines)
  867. lan_list = []
  868. re_lan = re.compile(r'(\w+[语话])')
  869. re_lev = re.compile(r'([公共级四专八]+)')
  870. lag_dict = {'lan_name':'', 'level':""}
  871. for l in lines:
  872. if not l.strip():
  873. continue
  874. lan_name = re.search(re_lan, l)
  875. lag_lev = re.search(re_lev, l)
  876. if lag_lev and lag_lev.group(1):
  877. lag_dict["level"] = lag_lev.group(1)
  878. if lan_name and lan_name.group(1):
  879. if lag_dict["lan_name"]:
  880. lan_list.append(lag_dict)
  881. lag_dict = {'lan_name':'', 'level':""}
  882. lag_dict['lan_name'] = lan_name.group(1)
  883. return lan_list
  884. # 家庭情况(已弃用)
  885. def get_fam_list(lines):
  886. job_list = []
  887. fam_dict = {}
  888. for l in lines:
  889. if not l.strip():
  890. continue
  891. ls = l.split('|')
  892. if len(ls) == 1:
  893. continue
  894. fam_dict = {'fam_name':"",'fam_company':"",'fam_lable':"","fam_status":"", 'fam_job':""}
  895. fam_dict["fam_lable"] = ls[0].strip()
  896. fam_dict["fam_name"] = ls[1].strip()
  897. flag = 0
  898. if re.findall('\d岁|\d{4,5}', ls[2]):
  899. flag = 1
  900. fam_dict["fam_company"] = ls[flag+2].strip()
  901. fam_dict["fam_job"] = ls[flag+3].strip()
  902. fam_dict["fam_status"] = ls[flag+4].strip()
  903. #print(fam_dict)
  904. job_list.append(fam_dict)
  905. return job_list
  906. # 证书情况 时间+证书名称 (旧版)
  907. def get_cet_list_old(lines):
  908. logger.info(lines)
  909. job_list = []
  910. re_txt = '\d+年\d+月|\d+-\d+|\d+\.\d+'
  911. lines_word = ' '.join(lines)
  912. lines = re.findall('\d+年\d+月|\d+-\d+|\d+\.\d+', lines_word)
  913. nums = []
  914. for x in range(len(lines) - 1):
  915. _index = lines_word.index(lines[x])
  916. _end_index = lines_word.index(lines[x+1])
  917. l = lines_word[_index : _end_index]
  918. if not l.strip():
  919. continue
  920. lines_word = lines_word[_end_index:]
  921. job_time = re.findall(re_txt, l)
  922. cet_dict = {'cet_name':'','cet_time':""}
  923. if job_time:
  924. cet_dict['prize_time'] = job_time[0]
  925. l = re.sub(job_time[0], '', l)
  926. else:
  927. continue
  928. ls = re.split('\||\040+|\t+', l)
  929. logger.info(ls)
  930. for l in ls:
  931. if len(l) <= 3:
  932. continue
  933. cet_dict['prize_name'] = l.strip()
  934. break
  935. job_list.append(cet_dict)
  936. return job_list
  937. # 证书情况 时间+证书名称 (UIE已完成)
  938. def get_cet_list(lines):
  939. logger.info(lines)
  940. cet_list = []
  941. for line in lines:
  942. info = cet_ie(line)
  943. cet_list.extend([{key:rst[key][0]["text"] for key in rst.keys()} for rst in info if rst.get("证书")])
  944. return cet_list
  945. # 获奖情况 时间+获奖名称 (旧版)
  946. def get_prize_list_old(lines):
  947. logger.info(lines)
  948. job_list = []
  949. re_txt = '\d+年\d+月|\d+-\d+|\d{4,4}.\d{1,2}'
  950. lines_word = ' '.join(lines)
  951. lines = re.findall('\d+年\d+月|\d{4,4}-\d+|\d{4,4}.\d{1,2}', lines_word)
  952. nums = []
  953. for x in range(len(lines) - 1):
  954. _index = lines_word.index(lines[x])
  955. _end_index = lines_word.index(lines[x+1])
  956. l = lines_word[_index : _end_index]
  957. if not l.strip():
  958. continue
  959. lines_word = lines_word[_end_index:]
  960. job_time = re.findall(re_txt, l)
  961. cet_dict = {'prize_name':'','prize_time':""}
  962. if job_time:
  963. cet_dict['prize_time'] = job_time[0]
  964. l = re.sub(job_time[0], '', l)
  965. else:
  966. continue
  967. ls = re.split('\||\040+|\t+', l)
  968. logger.info(ls)
  969. for l in ls:
  970. if len(l) <= 3:
  971. continue
  972. cet_dict['prize_name'] = l.strip()
  973. break
  974. logger.info(cet_dict)
  975. job_list.append(cet_dict)
  976. return job_list
  977. # 获奖情况 时间+获奖名称 (UIE已完成)
  978. def get_prize_list(lines):
  979. logger.info(lines)
  980. prize_list = []
  981. for line in lines:
  982. info = prize_ie(line)
  983. prize_list.extend([{key:rst[key][0]["text"] for key in rst.keys()} for rst in info if rst.get("奖项")])
  984. return prize_list
  985. # 返回其他信息
  986. def get_other_list(lines):
  987. other_list = []
  988. other_list.append("\n".join(lines))
  989. return other_list
  990. # Linux doc 文件处理
  991. def doc2pdf_linux(docPath, pdfPath):
  992. """
  993. 允许的文档格式:doc,docx
  994. 仅在linux平台下可以
  995. 需要在linux中下载好libreoffice
  996. """
  997. # 注意cmd中的libreoffice要和linux中安装的一致
  998. cmd = 'libreoffice6.3 --headless --convert-to pdf'.split() + [docPath] + ['--outdir'] + [pdfPath]
  999. # cmd = 'libreoffice6.2 --headless --convert-to pdf'.split() + [docPath]
  1000. p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
  1001. p.wait(timeout=30) # 停顿30秒等待转化
  1002. stdout, stderr = p.communicate()
  1003. if stderr:
  1004. raise subprocess.SubprocessError(stderr)
  1005. # Windows doc 文件处理
  1006. def doc2pdf_win(docPath, pdfPath):
  1007. console.print(pdfPath+'/'+os.path.splitext(os.path.split(docPath)[-1])[0] + '.pdf')
  1008. import win32com
  1009. from win32com.client import DispatchEx, constants
  1010. word = DispatchEx("Word.Application") #内部方法
  1011. word.Visible = 1 # 后台运行,不显示
  1012. word.DisplayAlerts = 0 # 不警告
  1013. doc = word.Documents.Open(docPath) #转换源文件
  1014. doc.SaveAs(pdfPath+'/'+os.path.splitext(os.path.split(docPath)[-1])[0] + '.pdf', FileFormat=17) #txt=4,html=10,docx=16,pdf=17 #新文件
  1015. doc.Close() #关闭
  1016. word.Quit() #退出
  1017. # doc 文件处理
  1018. def doc2pdf(docPath, pdfPath, system):
  1019. """
  1020. 注意使用绝对路径
  1021. pdf的生成只写路径,不写名字
  1022. """
  1023. docPathTrue = os.path.abspath(docPath) # bugfix - searching files in windows/system32
  1024. if system == "Linux":
  1025. return doc2pdf_linux(docPathTrue, pdfPath)
  1026. if system == "Windows":
  1027. return doc2pdf_win(docPathTrue, pdfPath)
  1028. # txt 纯文本解析(已完成)
  1029. def parse_txt(path, save_dir):
  1030. with open(path, 'r', encoding='utf-8') as fp:
  1031. data = fp.read()
  1032. global block, block_rev
  1033. chun = 1
  1034. page = {1: []}
  1035. if len(data.split("\n")) <= 2:
  1036. for line in data.split("\n"):
  1037. line = line.replace("\xa0", "").replace("【","").replace("】","").replace("教育/培训","教育经历").strip()
  1038. for word in line.split():
  1039. if word in block.keys():
  1040. chun = block[word]
  1041. page[chun] = []
  1042. elif word:
  1043. page[chun].append(word)
  1044. else:
  1045. for line in data.split("\n"):
  1046. line = line.replace("\xa0", "").replace("【","").replace("】","").replace("教育/培训","教育经历")
  1047. regex = re.compile(u'[\u3000]+',re.UNICODE)
  1048. line = regex.sub('', line.strip())
  1049. if line in block.keys():
  1050. chun = block[line]
  1051. page[chun] = []
  1052. elif line:
  1053. page[chun].append(line)
  1054. result_data = []
  1055. for key in page.keys():
  1056. for index, func in zip([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [get_base_info, get_job_intention, get_edu_list, get_job_list, get_pro_list, get_other_list, get_other_list, get_other_list, get_lag_list, get_cet_list, get_prize_list, get_cultivate_list]):
  1057. if key == index:
  1058. result_data.append({block_rev[index]:func(page[index])})
  1059. filename = os.path.splitext(os.path.split(path)[-1])[0]+'.json'
  1060. with open(os.path.join(save_dir, filename), 'w', encoding="utf-8") as fp:
  1061. json.dump({"result":result_data}, fp, indent=4, ensure_ascii=False)
  1062. # 纯文本 word 解析
  1063. def read_from_word(doc, path, save_dir):
  1064. para_text = []
  1065. for para in doc.paragraphs:
  1066. para_text.append(para.text)
  1067. global block, block_rev
  1068. chun = 1
  1069. page = {1: []}
  1070. for line in para_text:
  1071. regex = re.compile(u'[\uF000-\uF0FF]+',re.UNICODE)
  1072. line = regex.sub('', line)
  1073. if line in block.keys():
  1074. chun = block[line]
  1075. page[chun] = []
  1076. elif line:
  1077. page[chun].append(line)
  1078. result_data = []
  1079. for key in page.keys():
  1080. for index, func in zip([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [get_base_info, get_job_intention, get_edu_list, get_job_list, get_pro_list, get_other_list, get_other_list, get_other_list, get_lag_list, get_cet_list, get_prize_list, get_cultivate_list]):
  1081. if key == index:
  1082. result_data.append({block_rev[index]:func(page[index])})
  1083. filename = os.path.splitext(os.path.split(path)[-1])[0]+'.json'
  1084. with open(os.path.join(save_dir, filename), 'w', encoding="utf-8") as fp:
  1085. json.dump({"result":result_data}, fp, indent=4, ensure_ascii=False)
  1086. # 提取 word 表格(已完成)
  1087. def check_word(path, save_dir):
  1088. doc = Document(path)
  1089. tables = doc.tables
  1090. if not tables:
  1091. logger.info("this is raw text")
  1092. read_from_word(doc, path, save_dir=save_dir)
  1093. logger.info("this is a Table")
  1094. global block
  1095. with open("resources/keys.json", "r", encoding="utf-8") as fp:
  1096. prk = json.load(fp)
  1097. chun = 1
  1098. page = {1: []}
  1099. regex = re.compile(r'(\(\w{2,8}\))?((\w{2,8}))?')
  1100. for table in tables:
  1101. lo = {} # 存储每一行去重后的数据
  1102. for row in range(0, len(table.rows)):
  1103. row_list = []
  1104. for col in range(0, len(table.row_cells(row))): # 提取row行的全部列数据
  1105. if len(''.join(table.cell(row, col).text)) <= 20:
  1106. row_list.append(re.sub(r'(\w)\n', r'\1', table.cell(row, col).text))
  1107. else:
  1108. row_list.append(regex.sub("", table.cell(row, col).text.replace(" ","").replace(":", ":").replace("学历\n学位","学历学位"))) # 去除字符串中的特殊字符,并添加到临时列表中
  1109. lo[row] = (sorted(set(row_list), key=row_list.index)) # 在不变顺序的前提下,去除List中的重复项
  1110. # 去除空项
  1111. for key in list(lo.keys()):
  1112. if "" in lo[key]:
  1113. lo[key].remove("")
  1114. if not lo[key]:
  1115. lo.pop(key)
  1116. for _, line in lo.items():
  1117. if (line[0] in block.keys()) or (line[0] in prk.keys()):
  1118. # 包含大类目名
  1119. if line[0] in block.keys():
  1120. # 指向当前类目
  1121. chun = block[line[0]]
  1122. if not page.get(chun):
  1123. page[chun] = []
  1124. # 去除类目名
  1125. line = '\n'.join(line[1:])
  1126. # 包含小类目
  1127. elif line[0] in prk.keys():
  1128. # 指向当前类目
  1129. chun = prk[line[0]]
  1130. if not page.get(chun):
  1131. page[chun] = []
  1132. # 不去除
  1133. line = '\n'.join(line)
  1134. else:
  1135. line = '\n'.join(line)
  1136. # 标准化小类目
  1137. for k in prk.keys():
  1138. line = line.replace(k+"\n", k+":")
  1139. page[chun].extend(line.split())
  1140. result_data = []
  1141. for key in page.keys():
  1142. for index, func in zip([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [get_base_info, get_job_intention, get_edu_list, get_job_list, get_pro_list, get_other_list, get_other_list, get_other_list, get_lag_list, get_cet_list, get_prize_list, get_cultivate_list]):
  1143. if key == index:
  1144. result_data.append({block_rev[index]:func(page[index])})
  1145. filename = os.path.splitext(os.path.split(path)[-1])[0]+'.json'
  1146. with open(os.path.join(save_dir, filename), 'w', encoding="utf-8") as fp:
  1147. json.dump({"result":result_data}, fp, indent=4, ensure_ascii=False)
  1148. # pdf 解析句子(已完成)
  1149. def parse_line_layout(layout, b):
  1150. texts = []
  1151. """解析页面内容,一行一行的解析"""
  1152. # bbox:
  1153. # x0:从页面左侧到框左边缘的距离。
  1154. # y0:从页面底部到框的下边缘的距离。
  1155. # x1:从页面左侧到方框右边缘的距离。
  1156. # y1:从页面底部到框的上边缘的距离
  1157. for textbox in layout:
  1158. if isinstance(textbox, LTTextBox) or isinstance(textbox, LTTextLine):
  1159. for char in textbox:
  1160. if isinstance(char, LTTextLineHorizontal):
  1161. texts.append([char.bbox[0], char.bbox[3], char.get_text().strip()])
  1162. # 按行排序
  1163. texts.sort(key=lambda x:-x[1])
  1164. global block, block_rev
  1165. chun = b
  1166. page = {chun: []}
  1167. for _, _, line in texts:
  1168. regex = re.compile(u'[\u007F|\u25A0|\u00B7|\uF000-\uF0FF]+',re.UNICODE)
  1169. line = regex.sub('', line)
  1170. regex_tips = re.compile(r'(\(.*?\))?((.*?))?')
  1171. # line = regex_tips.sub('', line)
  1172. line = line.strip()
  1173. if regex_tips.sub('', line).strip() in block.keys():
  1174. chun = block[regex_tips.sub('', line).strip()]
  1175. page[chun] = []
  1176. elif line:
  1177. page[chun].append(line)
  1178. return page, chun
  1179. # pdf 样式解析(已完成)
  1180. def read_from_pdf(path, save_dir):
  1181. result = {}
  1182. global block_rev
  1183. with open(path, 'rb') as in_file:
  1184. parser = PDFParser(in_file) # 用文件对象来创建一个pdf文档分析器
  1185. doc: PDFDocument = PDFDocument(parser) # 创建pdf文档
  1186. rsrcmgr = PDFResourceManager() # 创建PDF,资源管理器,来共享资源
  1187. # 创建一个PDF设备对象
  1188. laparams = LAParams()
  1189. device = PDFPageAggregator(rsrcmgr, laparams=laparams)
  1190. # 创建一个PDF解释其对象
  1191. interpreter = PDFPageInterpreter(rsrcmgr, device)
  1192. # 循环遍历列表,每次处理一个page内容
  1193. # doc.get_pages() 获取page列表
  1194. interpreter = PDFPageInterpreter(rsrcmgr, device)
  1195. # 处理文档对象中每一页的内容
  1196. # 循环遍历列表,每次处理一个page的内容
  1197. b = 1
  1198. for page in PDFPage.create_pages(doc):
  1199. logger.debug('================ 新页面 ================')
  1200. interpreter.process_page(page)
  1201. layout = device.get_result()
  1202. r, b = parse_line_layout(layout, b)
  1203. for key in r.keys():
  1204. if result.get(key):
  1205. result[key].extend(r[key])
  1206. else:
  1207. result[key] = r[key]
  1208. result_data = []
  1209. for key in result.keys():
  1210. for index, func in zip([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [get_base_info, get_job_intention, get_edu_list, get_job_list, get_pro_list, get_other_list, get_other_list, get_other_list, get_lag_list, get_cet_list, get_prize_list, get_cultivate_list]):
  1211. if key == index:
  1212. result_data.append({block_rev[index]:func(result[index])})
  1213. filename = os.path.splitext(os.path.split(path)[-1])[0]+'.json'
  1214. with open(os.path.join(save_dir, filename), 'w', encoding="utf-8") as fp:
  1215. json.dump({"result":result_data}, fp, indent=4, ensure_ascii=False)
  1216. # pdf 表格解析 (已完成)
  1217. def parse_table_from_pdf(path, save_dir):
  1218. global block, block_rev
  1219. lo = {}
  1220. with pdfplumber.open(path) as pdf:
  1221. for page in pdf.pages:
  1222. for table in page.extract_tables():
  1223. for line in table:
  1224. row_list = []
  1225. for word in line:
  1226. row_list.append(word)
  1227. lo[len(lo.keys())] = row_list
  1228. # 去除空项
  1229. for key in list(lo.keys()):
  1230. if "" in lo[key]:
  1231. lo[key].remove("")
  1232. if not lo[key]:
  1233. lo.pop(key)
  1234. for _, line in lo.items():
  1235. if (line[0] in block.keys()) or (line[0] in prk.keys()):
  1236. # 包含大类目名
  1237. if line[0] in block.keys():
  1238. # 指向当前类目
  1239. chun = block[line[0]]
  1240. if not page.get(chun):
  1241. page[chun] = []
  1242. # 去除类目名
  1243. line = '\n'.join(line[1:])
  1244. # 包含小类目
  1245. elif line[0] in prk.keys():
  1246. # 指向当前类目
  1247. chun = prk[line[0]]
  1248. if not page.get(chun):
  1249. page[chun] = []
  1250. # 不去除
  1251. line = '\n'.join(line)
  1252. else:
  1253. line = '\n'.join(line)
  1254. # 标准化小类目
  1255. for k in prk.keys():
  1256. line = line.replace(k+"\n", k+":")
  1257. page[chun].extend(line.split())
  1258. result_data = []
  1259. for key in page.keys():
  1260. for index, func in zip([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [get_base_info, get_job_intention, get_edu_list, get_job_list, get_pro_list, get_other_list, get_other_list, get_other_list, get_lag_list, get_cet_list, get_prize_list, get_cultivate_list]):
  1261. if key == index:
  1262. result_data.append({block_rev[index]:func(page[index])})
  1263. filename = os.path.splitext(os.path.split(path)[-1])[0]+'.json'
  1264. with open(os.path.join(save_dir, filename), 'w', encoding="utf-8") as fp:
  1265. json.dump({"result":result_data}, fp, indent=4, ensure_ascii=False)
  1266. # 检测 pdf 格式 (已完成)
  1267. def check_pdf(path):
  1268. """
  1269. # 输入:
  1270. # pdf 文件路径
  1271. # 输出:
  1272. # 文件包含元素 [Word, Table]
  1273. """
  1274. rst = []
  1275. for page_layout in extract_pages(path):
  1276. for element in page_layout:
  1277. if isinstance(element, LTFigure):
  1278. for cell in element:
  1279. if isinstance(cell, LTChar):
  1280. rst.append("Table")
  1281. break
  1282. elif isinstance(element, LTTextContainer):
  1283. rst.append("Word")
  1284. return set(rst)
  1285. # 检测编码(已完成)
  1286. def decode_path(path):
  1287. '''zipfile解压出现乱码,将乱码的路径编码为UTF8'''
  1288. try:
  1289. path_name = path.decode('utf-8')
  1290. except:
  1291. path_name = path.encode('437').decode('gbk')
  1292. path_name = path_name.encode('utf-8').decode('utf-8')
  1293. return path_name
  1294. # 检测传入格式(已完成)
  1295. def detection_type(path, system):
  1296. tempdir = time.strftime("%Y_%m_%dT%H_%M_%S")
  1297. os.mkdir(tempdir)
  1298. # 传入 rar 压缩文件
  1299. if os.path.isfile(path) and path.endswith('.rar'):
  1300. rar = rarfile.RarFile(path)
  1301. rar.extractall('./cache/' + tempdir)
  1302. path = "./cache/" + tempdir
  1303. # 传入 tar.gz 压缩文件
  1304. if os.path.isfile(path) and path.endswith('.tar.gz'):
  1305. tf = tarfile.open(path)
  1306. tf.extractall('./cache/' + tempdir)
  1307. tf.close()
  1308. path = "./cache/" + tempdir
  1309. # 传入 .zip .7z 压缩文件
  1310. try:
  1311. if os.path.isfile(path) and path.endswith('.zip'):
  1312. ## 解压方式1:存在乱码
  1313. # f = zipfile.ZipFile(file, mode='r')
  1314. # f.extractall(target_dir)
  1315. ## 解压方式2:防止乱码
  1316. with ZipFile(path, allowZip64=True) as zf:
  1317. # 排除目录文件
  1318. print("zf.filelist", zf.filelist)
  1319. file_iter = (filename for filename in zf.filelist if os.path.isfile(path))
  1320. for filename in file_iter:
  1321. # 编码文件名称为 utf 格式
  1322. filename.filename = decode_path(filename.filename) # 防止乱码的操作
  1323. zf.extract(filename, "./cache/" + tempdir)
  1324. path = "./cache/" + tempdir
  1325. elif os.path.isfile(path) and path.endswith('.7z'): # .7z格式文件解压
  1326. zf = py7zr.SevenZipFile(path, mode='r')
  1327. zf.extractall("./cache/" + tempdir)
  1328. path = "./cache/" + tempdir
  1329. except Exception as e:
  1330. logger.error(e)
  1331. # 传入为 doc
  1332. if os.path.isfile(path) and path.endswith('.doc'):
  1333. doc2pdf(docPath = path, pdfPath = './pdf', system=system)
  1334. newfile = './pdf/' + os.path.splitext(os.path.split(path)[-1])[0] + '.pdf'
  1335. if os.path.exists(newfile):
  1336. rst = check_pdf(newfile)
  1337. if "Table" in rst:
  1338. parse_table_from_pdf(newfile, save_dir=tempdir)
  1339. pass
  1340. if "Word" in rst:
  1341. read_from_pdf(newfile, save_dir=tempdir)
  1342. # 传入为 docx
  1343. elif os.path.isfile(path) and path.endswith('.docx'):
  1344. check_word(path, save_dir=tempdir)
  1345. # 传入为 pdf
  1346. elif os.path.isfile(path) and path.endswith('.pdf'):
  1347. rst = check_pdf(path)
  1348. if "Table" in rst:
  1349. parse_table_from_pdf(path, save_dir=tempdir)
  1350. if "Word" in rst:
  1351. read_from_pdf(path, save_dir=tempdir)
  1352. # 传入为 txt
  1353. elif os.path.isfile(path) and path.endswith('.txt'):
  1354. parse_txt(path, save_dir=tempdir)
  1355. # 传入目录
  1356. elif os.path.isdir(path):
  1357. for filename in os.listdir(path):
  1358. filename = os.path.join(path, filename)
  1359. # 传入为 doc
  1360. logger.info(filename)
  1361. if filename.endswith('.doc') and not filename.startswith('.~'):
  1362. doc2pdf(docPath = filename, pdfPath = './pdf', system=system)
  1363. newfile = './pdf/' + os.path.splitext(os.path.split(filename)[-1])[0] + '.pdf'
  1364. if os.path.exists(newfile):
  1365. rst = check_pdf(newfile)
  1366. if "Table" in rst:
  1367. parse_table_from_pdf(newfile, save_dir=tempdir)
  1368. pass
  1369. if "Word" in rst:
  1370. read_from_pdf(newfile, save_dir=tempdir)
  1371. # 传入为 docx
  1372. elif os.path.isfile(filename) and filename.endswith('.docx'):
  1373. check_word(filename, save_dir=tempdir)
  1374. # 传入为 pdf
  1375. if os.path.isfile(filename) and filename.endswith('.pdf'):
  1376. rst = check_pdf(filename)
  1377. if "Table" in rst:
  1378. parse_table_from_pdf(filename, save_dir=tempdir)
  1379. pass
  1380. if "Word" in rst:
  1381. read_from_pdf(filename, save_dir=tempdir)
  1382. # 传入为 txt
  1383. elif os.path.isfile(filename) and filename.endswith('.txt'):
  1384. parse_txt(filename, save_dir=tempdir)
  1385. # 结果返回
  1386. for file in os.listdir(tempdir):
  1387. filename = os.path.join(tempdir, file)
  1388. with open(filename, "r", encoding="utf-8") as ff:
  1389. rst = json.load(ff)
  1390. url = "http://192.168.1.110:9999/talent/getResumeData"
  1391. session = requests.Session()
  1392. session.mount('http://', HTTPAdapter(max_retries = 3))
  1393. try:
  1394. headers = {
  1395. 'contentType':'Application/json'
  1396. }
  1397. response = session.post(url=url, headers=headers, json={"ResumeData":rst}, timeout=10)
  1398. print(response.text)
  1399. except Exception as e:
  1400. print(e)
  1401. console.print(rst, style="red", justify="left")
  1402. @app.post("/resume_parse")
  1403. async def file_upload(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
  1404. """
  1405. 简历上传
  1406. 格式:pdf,docx,doc,txt,tar,zip,7z
  1407. """
  1408. res = await file.read()
  1409. with open('./uploads/' + file.filename, "wb") as f:
  1410. f.write(res)
  1411. background_tasks.add_task(detection_type, './uploads/' + file.filename, system)
  1412. return {"errno": 0, "msg": "Upload Success"}
  1413. if __name__ == '__main__':
  1414. import platform
  1415. system = platform.system()
  1416. if (system == "Windows"):
  1417. logger.info("Windows")
  1418. elif (system == "Linux"):
  1419. logger.info("Linux")
  1420. else:
  1421. logger.error("Unnot support this system")
  1422. if not os.path.exists("./uploads"):
  1423. os.mkdir("./uploads")
  1424. if not os.path.exists("./pdf"):
  1425. os.mkdir("./pdf")
  1426. if not os.path.exists("./cache"):
  1427. os.mkdir("./cache")
  1428. uvicorn.run(app=app, host="0.0.0.0", port=8320)