Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

task_executor.py 7.9KB

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