Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

task_executor.py 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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, one
  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. ParserType.ONE.value: one,
  56. }
  57. def set_progress(task_id, from_page=0, to_page=-1,
  58. prog=None, msg="Processing..."):
  59. if prog is not None and prog < 0:
  60. msg = "[ERROR]"+msg
  61. cancel = TaskService.do_cancel(task_id)
  62. if cancel:
  63. msg += " [Canceled]"
  64. prog = -1
  65. if to_page > 0:
  66. if msg:
  67. msg = f"Page({from_page}~{to_page}): " + msg
  68. d = {"progress_msg": msg}
  69. if prog is not None:
  70. d["progress"] = prog
  71. try:
  72. TaskService.update_progress(task_id, d)
  73. except Exception as e:
  74. cron_logger.error("set_progress:({}), {}".format(task_id, str(e)))
  75. if cancel:
  76. sys.exit()
  77. def collect(comm, mod, tm):
  78. tasks = TaskService.get_tasks(tm, mod, comm)
  79. if len(tasks) == 0:
  80. return pd.DataFrame()
  81. tasks = pd.DataFrame(tasks)
  82. mtm = tasks["update_time"].max()
  83. cron_logger.info("TOTAL:{}, To:{}".format(len(tasks), mtm))
  84. return tasks
  85. def build(row):
  86. if row["size"] > DOC_MAXIMUM_SIZE:
  87. set_progress(row["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  88. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  89. return []
  90. callback = partial(
  91. set_progress,
  92. row["id"],
  93. row["from_page"],
  94. row["to_page"])
  95. chunker = FACTORY[row["parser_id"].lower()]
  96. try:
  97. cron_logger.info(
  98. "Chunkking {}/{}".format(row["location"], row["name"]))
  99. cks = chunker.chunk(row["name"], binary=MINIO.get(row["kb_id"], row["location"]), from_page=row["from_page"],
  100. to_page=row["to_page"], lang=row["language"], callback=callback,
  101. kb_id=row["kb_id"], parser_config=row["parser_config"], tenant_id=row["tenant_id"])
  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["name"])
  105. else:
  106. callback(-1, f"Internal server error: %s" %
  107. str(e).replace("'", ""))
  108. traceback.print_exc()
  109. cron_logger.warn(
  110. "Chunkking {}/{}: {}".format(row["location"], row["name"], str(e)))
  111. return
  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. batch_size = 32
  147. tts, cnts = [rmSpace(d["title_tks"]) for d in docs if d.get("title_tks")], [
  148. d["content_with_weight"] for d in docs]
  149. tk_count = 0
  150. if len(tts) == len(cnts):
  151. tts_ = np.array([])
  152. for i in range(0, len(tts), batch_size):
  153. vts, c = mdl.encode(tts[i: i + batch_size])
  154. if len(tts_) == 0:
  155. tts_ = vts
  156. else:
  157. tts_ = np.concatenate((tts_, vts), axis=0)
  158. tk_count += c
  159. callback(prog=0.6 + 0.1 * (i + 1) / len(tts), msg="")
  160. tts = tts_
  161. cnts_ = np.array([])
  162. for i in range(0, len(cnts), batch_size):
  163. vts, c = mdl.encode(cnts[i: i+batch_size])
  164. if len(cnts_) == 0: cnts_ = vts
  165. else: cnts_ = np.concatenate((cnts_, vts), axis=0)
  166. tk_count += c
  167. callback(prog=0.7+0.2*(i+1)/len(cnts), msg="")
  168. cnts = cnts_
  169. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  170. vects = (title_w * tts + (1 - title_w) *
  171. cnts) if len(tts) == len(cnts) else cnts
  172. assert len(vects) == len(docs)
  173. for i, d in enumerate(docs):
  174. v = vects[i].tolist()
  175. d["q_%d_vec" % len(v)] = v
  176. return tk_count
  177. def main(comm, mod):
  178. tm_fnm = os.path.join(
  179. get_project_base_directory(),
  180. "rag/res",
  181. f"{comm}-{mod}.tm")
  182. tm = findMaxTm(tm_fnm)
  183. rows = collect(comm, mod, tm)
  184. if len(rows) == 0:
  185. return
  186. tmf = open(tm_fnm, "a+")
  187. for _, r in rows.iterrows():
  188. callback = partial(set_progress, r["id"], r["from_page"], r["to_page"])
  189. try:
  190. embd_mdl = LLMBundle(r["tenant_id"], LLMType.EMBEDDING)
  191. except Exception as e:
  192. callback(prog=-1, msg=str(e))
  193. continue
  194. cks = build(r)
  195. if cks is None:
  196. continue
  197. if not cks:
  198. tmf.write(str(r["update_time"]) + "\n")
  199. callback(1., "No chunk! Done!")
  200. continue
  201. # TODO: exception handler
  202. ## set_progress(r["did"], -1, "ERROR: ")
  203. callback(msg="Finished slicing files(%d). Start to embedding the content."%len(cks))
  204. try:
  205. tk_count = embedding(cks, embd_mdl, r["parser_config"], callback)
  206. except Exception as e:
  207. callback(-1, "Embedding error:{}".format(str(e)))
  208. cron_logger.error(str(e))
  209. tk_count = 0
  210. callback(msg="Finished embedding! Start to build index!")
  211. init_kb(r)
  212. chunk_count = len(set([c["_id"] for c in cks]))
  213. es_r = ELASTICSEARCH.bulk(cks, search.index_name(r["tenant_id"]))
  214. if es_r:
  215. callback(-1, "Index failure!")
  216. ELASTICSEARCH.deleteByQuery(
  217. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  218. cron_logger.error(str(es_r))
  219. else:
  220. if TaskService.do_cancel(r["id"]):
  221. ELASTICSEARCH.deleteByQuery(
  222. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  223. continue
  224. callback(1., "Done!")
  225. DocumentService.increment_chunk_num(
  226. r["doc_id"], r["kb_id"], tk_count, chunk_count, 0)
  227. cron_logger.info(
  228. "Chunk doc({}), token({}), chunks({})".format(
  229. r["id"], tk_count, len(cks)))
  230. tmf.write(str(r["update_time"]) + "\n")
  231. tmf.close()
  232. if __name__ == "__main__":
  233. peewee_logger = logging.getLogger('peewee')
  234. peewee_logger.propagate = False
  235. peewee_logger.addHandler(database_logger.handlers[0])
  236. peewee_logger.setLevel(database_logger.level)
  237. from mpi4py import MPI
  238. comm = MPI.COMM_WORLD
  239. main(int(sys.argv[2]), int(sys.argv[1]))