選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

task_executor.py 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #
  2. # Copyright 2024 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 datetime
  17. import json
  18. import logging
  19. import os
  20. import hashlib
  21. import copy
  22. import re
  23. import sys
  24. import traceback
  25. from functools import partial
  26. from timeit import default_timer as timer
  27. from elasticsearch_dsl import Q
  28. from api.db.services.task_service import TaskService
  29. from rag.settings import cron_logger, DOC_MAXIMUM_SIZE
  30. from rag.utils import ELASTICSEARCH
  31. from rag.utils import MINIO
  32. from rag.utils import rmSpace, findMaxTm
  33. from rag.nlp import search
  34. from io import BytesIO
  35. import pandas as pd
  36. from rag.app import laws, paper, presentation, manual, qa, table, book, resume, picture, naive
  37. from api.db import LLMType, ParserType
  38. from api.db.services.document_service import DocumentService
  39. from api.db.services.llm_service import LLMBundle
  40. from api.settings import database_logger
  41. from api.utils.file_utils import get_project_base_directory
  42. BATCH_SIZE = 64
  43. FACTORY = {
  44. "general": naive,
  45. ParserType.NAIVE.value: naive,
  46. ParserType.PAPER.value: paper,
  47. ParserType.BOOK.value: book,
  48. ParserType.PRESENTATION.value: presentation,
  49. ParserType.MANUAL.value: manual,
  50. ParserType.LAWS.value: laws,
  51. ParserType.QA.value: qa,
  52. ParserType.TABLE.value: table,
  53. ParserType.RESUME.value: resume,
  54. ParserType.PICTURE.value: picture,
  55. }
  56. def set_progress(task_id, from_page=0, to_page=-1,
  57. prog=None, msg="Processing..."):
  58. if prog is not None and prog < 0:
  59. msg = "[ERROR]"+msg
  60. cancel = TaskService.do_cancel(task_id)
  61. if cancel:
  62. msg += " [Canceled]"
  63. prog = -1
  64. if to_page > 0:
  65. msg = f"Page({from_page}~{to_page}): " + msg
  66. d = {"progress_msg": msg}
  67. if prog is not None:
  68. d["progress"] = prog
  69. try:
  70. TaskService.update_progress(task_id, d)
  71. except Exception as e:
  72. cron_logger.error("set_progress:({}), {}".format(task_id, str(e)))
  73. if cancel:
  74. sys.exit()
  75. def collect(comm, mod, tm):
  76. tasks = TaskService.get_tasks(tm, mod, comm)
  77. if len(tasks) == 0:
  78. return pd.DataFrame()
  79. tasks = pd.DataFrame(tasks)
  80. mtm = tasks["update_time"].max()
  81. cron_logger.info("TOTAL:{}, To:{}".format(len(tasks), mtm))
  82. return tasks
  83. def build(row):
  84. if row["size"] > DOC_MAXIMUM_SIZE:
  85. set_progress(row["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  86. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  87. return []
  88. callback = partial(
  89. set_progress,
  90. row["id"],
  91. row["from_page"],
  92. row["to_page"])
  93. chunker = FACTORY[row["parser_id"].lower()]
  94. try:
  95. cron_logger.info(
  96. "Chunkking {}/{}".format(row["location"], row["name"]))
  97. cks = chunker.chunk(row["name"], binary=MINIO.get(row["kb_id"], row["location"]), from_page=row["from_page"],
  98. to_page=row["to_page"], lang=row["language"], callback=callback,
  99. kb_id=row["kb_id"], parser_config=row["parser_config"], tenant_id=row["tenant_id"])
  100. except Exception as e:
  101. if re.search("(No such file|not found)", str(e)):
  102. callback(-1, "Can not find file <%s>" % row["name"])
  103. else:
  104. callback(-1, f"Internal server error: %s" %
  105. str(e).replace("'", ""))
  106. traceback.print_exc()
  107. cron_logger.warn(
  108. "Chunkking {}/{}: {}".format(row["location"], row["name"], str(e)))
  109. return
  110. callback(msg="Finished slicing files(%d). Start to embedding the content."%len(cks))
  111. docs = []
  112. doc = {
  113. "doc_id": row["doc_id"],
  114. "kb_id": [str(row["kb_id"])]
  115. }
  116. for ck in cks:
  117. d = copy.deepcopy(doc)
  118. d.update(ck)
  119. md5 = hashlib.md5()
  120. md5.update((ck["content_with_weight"] +
  121. str(d["doc_id"])).encode("utf-8"))
  122. d["_id"] = md5.hexdigest()
  123. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  124. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  125. if not d.get("image"):
  126. docs.append(d)
  127. continue
  128. output_buffer = BytesIO()
  129. if isinstance(d["image"], bytes):
  130. output_buffer = BytesIO(d["image"])
  131. else:
  132. d["image"].save(output_buffer, format='JPEG')
  133. MINIO.put(row["kb_id"], d["_id"], output_buffer.getvalue())
  134. d["img_id"] = "{}-{}".format(row["kb_id"], d["_id"])
  135. del d["image"]
  136. docs.append(d)
  137. return docs
  138. def init_kb(row):
  139. idxnm = search.index_name(row["tenant_id"])
  140. if ELASTICSEARCH.indexExist(idxnm):
  141. return
  142. return ELASTICSEARCH.createIdx(idxnm, json.load(
  143. open(os.path.join(get_project_base_directory(), "conf", "mapping.json"), "r")))
  144. def embedding(docs, mdl, parser_config={}):
  145. tts, cnts = [rmSpace(d["title_tks"]) for d in docs if d.get("title_tks")], [
  146. d["content_with_weight"] for d in docs]
  147. tk_count = 0
  148. if len(tts) == len(cnts):
  149. tts, c = mdl.encode(tts)
  150. tk_count += c
  151. cnts, c = mdl.encode(cnts)
  152. tk_count += c
  153. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  154. vects = (title_w * tts + (1 - title_w) *
  155. cnts) if len(tts) == len(cnts) else cnts
  156. assert len(vects) == len(docs)
  157. for i, d in enumerate(docs):
  158. v = vects[i].tolist()
  159. d["q_%d_vec" % len(v)] = v
  160. return tk_count
  161. def main(comm, mod):
  162. tm_fnm = os.path.join(
  163. get_project_base_directory(),
  164. "rag/res",
  165. f"{comm}-{mod}.tm")
  166. tm = findMaxTm(tm_fnm)
  167. rows = collect(comm, mod, tm)
  168. if len(rows) == 0:
  169. return
  170. tmf = open(tm_fnm, "a+")
  171. for _, r in rows.iterrows():
  172. callback = partial(set_progress, r["id"], r["from_page"], r["to_page"])
  173. try:
  174. embd_mdl = LLMBundle(r["tenant_id"], LLMType.EMBEDDING)
  175. except Exception as e:
  176. callback(prog=-1, msg=str(e))
  177. continue
  178. cks = build(r)
  179. if cks is None:
  180. continue
  181. if not cks:
  182. tmf.write(str(r["update_time"]) + "\n")
  183. callback(1., "No chunk! Done!")
  184. continue
  185. # TODO: exception handler
  186. ## set_progress(r["did"], -1, "ERROR: ")
  187. try:
  188. tk_count = embedding(cks, embd_mdl, r["parser_config"])
  189. except Exception as e:
  190. callback(-1, "Embedding error:{}".format(str(e)))
  191. cron_logger.error(str(e))
  192. callback(msg="Finished embedding! Start to build index!")
  193. init_kb(r)
  194. chunk_count = len(set([c["_id"] for c in cks]))
  195. es_r = ELASTICSEARCH.bulk(cks, search.index_name(r["tenant_id"]))
  196. if es_r:
  197. callback(-1, "Index failure!")
  198. ELASTICSEARCH.deleteByQuery(
  199. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  200. cron_logger.error(str(es_r))
  201. else:
  202. if TaskService.do_cancel(r["id"]):
  203. ELASTICSEARCH.deleteByQuery(
  204. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  205. continue
  206. callback(1., "Done!")
  207. DocumentService.increment_chunk_num(
  208. r["doc_id"], r["kb_id"], tk_count, chunk_count, 0)
  209. cron_logger.info(
  210. "Chunk doc({}), token({}), chunks({})".format(
  211. r["id"], tk_count, len(cks)))
  212. tmf.write(str(r["update_time"]) + "\n")
  213. tmf.close()
  214. if __name__ == "__main__":
  215. peewee_logger = logging.getLogger('peewee')
  216. peewee_logger.propagate = False
  217. peewee_logger.addHandler(database_logger.handlers[0])
  218. peewee_logger.setLevel(database_logger.level)
  219. from mpi4py import MPI
  220. comm = MPI.COMM_WORLD
  221. main(comm.Get_size(), comm.Get_rank())