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 8.5KB

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