You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

resume.py 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import base64
  18. import datetime
  19. import json
  20. import re
  21. import pandas as pd
  22. import requests
  23. from api.db.services.knowledgebase_service import KnowledgebaseService
  24. from rag.nlp import rag_tokenizer
  25. from deepdoc.parser.resume import refactor
  26. from deepdoc.parser.resume import step_one, step_two
  27. from rag.utils import rmSpace
  28. forbidden_select_fields4resume = [
  29. "name_pinyin_kwd", "edu_first_fea_kwd", "degree_kwd", "sch_rank_kwd", "edu_fea_kwd"
  30. ]
  31. def remote_call(filename, binary):
  32. q = {
  33. "header": {
  34. "uid": 1,
  35. "user": "kevinhu",
  36. "log_id": filename
  37. },
  38. "request": {
  39. "p": {
  40. "request_id": "1",
  41. "encrypt_type": "base64",
  42. "filename": filename,
  43. "langtype": '',
  44. "fileori": base64.b64encode(binary).decode('utf-8')
  45. },
  46. "c": "resume_parse_module",
  47. "m": "resume_parse"
  48. }
  49. }
  50. for _ in range(3):
  51. try:
  52. resume = requests.post(
  53. "http://127.0.0.1:61670/tog",
  54. data=json.dumps(q))
  55. resume = resume.json()["response"]["results"]
  56. resume = refactor(resume)
  57. for k in ["education", "work", "project",
  58. "training", "skill", "certificate", "language"]:
  59. if not resume.get(k) and k in resume:
  60. del resume[k]
  61. resume = step_one.refactor(pd.DataFrame([{"resume_content": json.dumps(resume), "tob_resume_id": "x",
  62. "updated_at": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}]))
  63. resume = step_two.parse(resume)
  64. return resume
  65. except Exception:
  66. logging.exception("Resume parser has not been supported yet!")
  67. return {}
  68. def chunk(filename, binary=None, callback=None, **kwargs):
  69. """
  70. The supported file formats are pdf, docx and txt.
  71. To maximize the effectiveness, parse the resume correctly, please concat us: https://github.com/infiniflow/ragflow
  72. """
  73. if not re.search(r"\.(pdf|doc|docx|txt)$", filename, flags=re.IGNORECASE):
  74. raise NotImplementedError("file type not supported yet(pdf supported)")
  75. if not binary:
  76. with open(filename, "rb") as f:
  77. binary = f.read()
  78. callback(0.2, "Resume parsing is going on...")
  79. resume = remote_call(filename, binary)
  80. if len(resume.keys()) < 7:
  81. callback(-1, "Resume is not successfully parsed.")
  82. raise Exception("Resume parser remote call fail!")
  83. callback(0.6, "Done parsing. Chunking...")
  84. logging.debug("chunking resume: " + json.dumps(resume, ensure_ascii=False, indent=2))
  85. field_map = {
  86. "name_kwd": "姓名/名字",
  87. "name_pinyin_kwd": "姓名拼音/名字拼音",
  88. "gender_kwd": "性别(男,女)",
  89. "age_int": "年龄/岁/年纪",
  90. "phone_kwd": "电话/手机/微信",
  91. "email_tks": "email/e-mail/邮箱",
  92. "position_name_tks": "职位/职能/岗位/职责",
  93. "expect_city_names_tks": "期望城市",
  94. "work_exp_flt": "工作年限/工作年份/N年经验/毕业了多少年",
  95. "corporation_name_tks": "最近就职(上班)的公司/上一家公司",
  96. "first_school_name_tks": "第一学历毕业学校",
  97. "first_degree_kwd": "第一学历(高中,职高,硕士,本科,博士,初中,中技,中专,专科,专升本,MPA,MBA,EMBA)",
  98. "highest_degree_kwd": "最高学历(高中,职高,硕士,本科,博士,初中,中技,中专,专科,专升本,MPA,MBA,EMBA)",
  99. "first_major_tks": "第一学历专业",
  100. "edu_first_fea_kwd": "第一学历标签(211,留学,双一流,985,海外知名,重点大学,中专,专升本,专科,本科,大专)",
  101. "degree_kwd": "过往学历(高中,职高,硕士,本科,博士,初中,中技,中专,专科,专升本,MPA,MBA,EMBA)",
  102. "major_tks": "学过的专业/过往专业",
  103. "school_name_tks": "学校/毕业院校",
  104. "sch_rank_kwd": "学校标签(顶尖学校,精英学校,优质学校,一般学校)",
  105. "edu_fea_kwd": "教育标签(211,留学,双一流,985,海外知名,重点大学,中专,专升本,专科,本科,大专)",
  106. "corp_nm_tks": "就职过的公司/之前的公司/上过班的公司",
  107. "edu_end_int": "毕业年份",
  108. "industry_name_tks": "所在行业",
  109. "birth_dt": "生日/出生年份",
  110. "expect_position_name_tks": "期望职位/期望职能/期望岗位",
  111. }
  112. titles = []
  113. for n in ["name_kwd", "gender_kwd", "position_name_tks", "age_int"]:
  114. v = resume.get(n, "")
  115. if isinstance(v, list):
  116. v = v[0]
  117. if n.find("tks") > 0:
  118. v = rmSpace(v)
  119. titles.append(str(v))
  120. doc = {
  121. "docnm_kwd": filename,
  122. "title_tks": rag_tokenizer.tokenize("-".join(titles) + "-简历")
  123. }
  124. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  125. pairs = []
  126. for n, m in field_map.items():
  127. if not resume.get(n):
  128. continue
  129. v = resume[n]
  130. if isinstance(v, list):
  131. v = " ".join(v)
  132. if n.find("tks") > 0:
  133. v = rmSpace(v)
  134. pairs.append((m, str(v)))
  135. doc["content_with_weight"] = "\n".join(
  136. ["{}: {}".format(re.sub(r"([^()]+)", "", k), v) for k, v in pairs])
  137. doc["content_ltks"] = rag_tokenizer.tokenize(doc["content_with_weight"])
  138. doc["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(doc["content_ltks"])
  139. for n, _ in field_map.items():
  140. if n not in resume:
  141. continue
  142. if isinstance(resume[n], list) and (
  143. len(resume[n]) == 1 or n not in forbidden_select_fields4resume):
  144. resume[n] = resume[n][0]
  145. if n.find("_tks") > 0:
  146. resume[n] = rag_tokenizer.fine_grained_tokenize(resume[n])
  147. doc[n] = resume[n]
  148. logging.debug("chunked resume to " + str(doc))
  149. KnowledgebaseService.update_parser_config(
  150. kwargs["kb_id"], {"field_map": field_map})
  151. return [doc]
  152. if __name__ == "__main__":
  153. import sys
  154. def dummy(a, b):
  155. pass
  156. chunk(sys.argv[1], callback=dummy)