Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

task_executor.py 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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+1}~{to_page+1}): " + 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. re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", 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:
  165. cnts_ = vts
  166. else:
  167. cnts_ = np.concatenate((cnts_, vts), axis=0)
  168. tk_count += c
  169. callback(prog=0.7 + 0.2 * (i + 1) / len(cnts), msg="")
  170. cnts = cnts_
  171. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  172. vects = (title_w * tts + (1 - title_w) *
  173. cnts) if len(tts) == len(cnts) else cnts
  174. assert len(vects) == len(docs)
  175. for i, d in enumerate(docs):
  176. v = vects[i].tolist()
  177. d["q_%d_vec" % len(v)] = v
  178. return tk_count
  179. def main(comm, mod):
  180. tm_fnm = os.path.join(
  181. get_project_base_directory(),
  182. "rag/res",
  183. f"{comm}-{mod}.tm")
  184. tm = findMaxTm(tm_fnm)
  185. rows = collect(comm, mod, tm)
  186. if len(rows) == 0:
  187. return
  188. tmf = open(tm_fnm, "a+")
  189. for _, r in rows.iterrows():
  190. callback = partial(set_progress, r["id"], r["from_page"], r["to_page"])
  191. try:
  192. embd_mdl = LLMBundle(r["tenant_id"], LLMType.EMBEDDING)
  193. except Exception as e:
  194. callback(prog=-1, msg=str(e))
  195. continue
  196. cks = build(r)
  197. if cks is None:
  198. continue
  199. if not cks:
  200. tmf.write(str(r["update_time"]) + "\n")
  201. callback(1., "No chunk! Done!")
  202. continue
  203. # TODO: exception handler
  204. ## set_progress(r["did"], -1, "ERROR: ")
  205. callback(
  206. msg="Finished slicing files(%d). Start to embedding the content." %
  207. len(cks))
  208. try:
  209. tk_count = embedding(cks, embd_mdl, r["parser_config"], callback)
  210. except Exception as e:
  211. callback(-1, "Embedding error:{}".format(str(e)))
  212. cron_logger.error(str(e))
  213. tk_count = 0
  214. callback(msg="Finished embedding! Start to build index!")
  215. init_kb(r)
  216. chunk_count = len(set([c["_id"] for c in cks]))
  217. es_r = ELASTICSEARCH.bulk(cks, search.index_name(r["tenant_id"]))
  218. if es_r:
  219. callback(-1, "Index failure!")
  220. ELASTICSEARCH.deleteByQuery(
  221. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  222. cron_logger.error(str(es_r))
  223. else:
  224. if TaskService.do_cancel(r["id"]):
  225. ELASTICSEARCH.deleteByQuery(
  226. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  227. continue
  228. callback(1., "Done!")
  229. DocumentService.increment_chunk_num(
  230. r["doc_id"], r["kb_id"], tk_count, chunk_count, 0)
  231. cron_logger.info(
  232. "Chunk doc({}), token({}), chunks({})".format(
  233. r["id"], tk_count, len(cks)))
  234. tmf.write(str(r["update_time"]) + "\n")
  235. tmf.close()
  236. if __name__ == "__main__":
  237. peewee_logger = logging.getLogger('peewee')
  238. peewee_logger.propagate = False
  239. peewee_logger.addHandler(database_logger.handlers[0])
  240. peewee_logger.setLevel(database_logger.level)
  241. from mpi4py import MPI
  242. comm = MPI.COMM_WORLD
  243. while True:
  244. main(int(sys.argv[2]), int(sys.argv[1]))