Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

task_executor.py 8.0KB

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