You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

task_executor.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 time
  25. import traceback
  26. from functools import partial
  27. from rag.utils import MINIO
  28. from api.db.db_models import close_connection
  29. from rag.settings import database_logger
  30. from rag.settings import cron_logger, DOC_MAXIMUM_SIZE
  31. from multiprocessing import Pool
  32. import numpy as np
  33. from elasticsearch_dsl import Q
  34. from multiprocessing.context import TimeoutError
  35. from api.db.services.task_service import TaskService
  36. from rag.utils import ELASTICSEARCH
  37. from timeit import default_timer as timer
  38. from rag.utils import rmSpace, findMaxTm
  39. from rag.nlp import search
  40. from io import BytesIO
  41. import pandas as pd
  42. from rag.app import laws, paper, presentation, manual, qa, table, book, resume, picture, naive, one
  43. from api.db import LLMType, ParserType
  44. from api.db.services.document_service import DocumentService
  45. from api.db.services.llm_service import LLMBundle
  46. from api.utils.file_utils import get_project_base_directory
  47. from rag.utils.redis_conn import REDIS_CONN
  48. BATCH_SIZE = 64
  49. FACTORY = {
  50. "general": naive,
  51. ParserType.NAIVE.value: naive,
  52. ParserType.PAPER.value: paper,
  53. ParserType.BOOK.value: book,
  54. ParserType.PRESENTATION.value: presentation,
  55. ParserType.MANUAL.value: manual,
  56. ParserType.LAWS.value: laws,
  57. ParserType.QA.value: qa,
  58. ParserType.TABLE.value: table,
  59. ParserType.RESUME.value: resume,
  60. ParserType.PICTURE.value: picture,
  61. ParserType.ONE.value: one,
  62. }
  63. def set_progress(task_id, from_page=0, to_page=-1,
  64. prog=None, msg="Processing..."):
  65. if prog is not None and prog < 0:
  66. msg = "[ERROR]" + msg
  67. cancel = TaskService.do_cancel(task_id)
  68. if cancel:
  69. msg += " [Canceled]"
  70. prog = -1
  71. if to_page > 0:
  72. if msg:
  73. msg = f"Page({from_page+1}~{to_page+1}): " + msg
  74. d = {"progress_msg": msg}
  75. if prog is not None:
  76. d["progress"] = prog
  77. try:
  78. TaskService.update_progress(task_id, d)
  79. except Exception as e:
  80. cron_logger.error("set_progress:({}), {}".format(task_id, str(e)))
  81. if cancel:
  82. sys.exit()
  83. def collect(comm, mod, tm):
  84. tasks = TaskService.get_tasks(tm, mod, comm)
  85. #print(tasks)
  86. if len(tasks) == 0:
  87. time.sleep(1)
  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 get_minio_binary(bucket, name):
  94. global MINIO
  95. if REDIS_CONN.is_alive():
  96. try:
  97. for _ in range(30):
  98. if REDIS_CONN.exist("{}/{}".format(bucket, name)):
  99. time.sleep(1)
  100. break
  101. time.sleep(1)
  102. r = REDIS_CONN.get("{}/{}".format(bucket, name))
  103. if r: return r
  104. cron_logger.warning("Cache missing: {}".format(name))
  105. except Exception as e:
  106. cron_logger.warning("Get redis[EXCEPTION]:" + str(e))
  107. return MINIO.get(bucket, name)
  108. def build(row):
  109. if row["size"] > DOC_MAXIMUM_SIZE:
  110. set_progress(row["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  111. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  112. return []
  113. callback = partial(
  114. set_progress,
  115. row["id"],
  116. row["from_page"],
  117. row["to_page"])
  118. chunker = FACTORY[row["parser_id"].lower()]
  119. pool = Pool(processes=1)
  120. try:
  121. st = timer()
  122. thr = pool.apply_async(get_minio_binary, args=(row["kb_id"], row["location"]))
  123. binary = thr.get(timeout=90)
  124. pool.terminate()
  125. cron_logger.info(
  126. "From minio({}) {}/{}".format(timer()-st, row["location"], row["name"]))
  127. cks = chunker.chunk(row["name"], binary=binary, from_page=row["from_page"],
  128. to_page=row["to_page"], lang=row["language"], callback=callback,
  129. kb_id=row["kb_id"], parser_config=row["parser_config"], tenant_id=row["tenant_id"])
  130. cron_logger.info(
  131. "Chunkking({}) {}/{}".format(timer()-st, row["location"], row["name"]))
  132. except TimeoutError as e:
  133. callback(-1, f"Internal server error: Fetch file timeout. Could you try it again.")
  134. cron_logger.error(
  135. "Chunkking {}/{}: Fetch file timeout.".format(row["location"], row["name"]))
  136. return
  137. except Exception as e:
  138. if re.search("(No such file|not found)", str(e)):
  139. callback(-1, "Can not find file <%s>" % row["name"])
  140. else:
  141. callback(-1, f"Internal server error: %s" %
  142. str(e).replace("'", ""))
  143. pool.terminate()
  144. traceback.print_exc()
  145. cron_logger.error(
  146. "Chunkking {}/{}: {}".format(row["location"], row["name"], str(e)))
  147. return
  148. docs = []
  149. doc = {
  150. "doc_id": row["doc_id"],
  151. "kb_id": [str(row["kb_id"])]
  152. }
  153. el = 0
  154. for ck in cks:
  155. d = copy.deepcopy(doc)
  156. d.update(ck)
  157. md5 = hashlib.md5()
  158. md5.update((ck["content_with_weight"] +
  159. str(d["doc_id"])).encode("utf-8"))
  160. d["_id"] = md5.hexdigest()
  161. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  162. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  163. if not d.get("image"):
  164. docs.append(d)
  165. continue
  166. output_buffer = BytesIO()
  167. if isinstance(d["image"], bytes):
  168. output_buffer = BytesIO(d["image"])
  169. else:
  170. d["image"].save(output_buffer, format='JPEG')
  171. st = timer()
  172. MINIO.put(row["kb_id"], d["_id"], output_buffer.getvalue())
  173. el += timer() - st
  174. d["img_id"] = "{}-{}".format(row["kb_id"], d["_id"])
  175. del d["image"]
  176. docs.append(d)
  177. cron_logger.info("MINIO PUT({}):{}".format(row["name"], el))
  178. return docs
  179. def init_kb(row):
  180. idxnm = search.index_name(row["tenant_id"])
  181. if ELASTICSEARCH.indexExist(idxnm):
  182. return
  183. return ELASTICSEARCH.createIdx(idxnm, json.load(
  184. open(os.path.join(get_project_base_directory(), "conf", "mapping.json"), "r")))
  185. def embedding(docs, mdl, parser_config={}, callback=None):
  186. batch_size = 32
  187. tts, cnts = [rmSpace(d["title_tks"]) for d in docs if d.get("title_tks")], [
  188. re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", d["content_with_weight"]) for d in docs]
  189. tk_count = 0
  190. if len(tts) == len(cnts):
  191. tts_ = np.array([])
  192. for i in range(0, len(tts), batch_size):
  193. vts, c = mdl.encode(tts[i: i + batch_size])
  194. if len(tts_) == 0:
  195. tts_ = vts
  196. else:
  197. tts_ = np.concatenate((tts_, vts), axis=0)
  198. tk_count += c
  199. callback(prog=0.6 + 0.1 * (i + 1) / len(tts), msg="")
  200. tts = tts_
  201. cnts_ = np.array([])
  202. for i in range(0, len(cnts), batch_size):
  203. vts, c = mdl.encode(cnts[i: i + batch_size])
  204. if len(cnts_) == 0:
  205. cnts_ = vts
  206. else:
  207. cnts_ = np.concatenate((cnts_, vts), axis=0)
  208. tk_count += c
  209. callback(prog=0.7 + 0.2 * (i + 1) / len(cnts), msg="")
  210. cnts = cnts_
  211. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  212. vects = (title_w * tts + (1 - title_w) *
  213. cnts) if len(tts) == len(cnts) else cnts
  214. assert len(vects) == len(docs)
  215. for i, d in enumerate(docs):
  216. v = vects[i].tolist()
  217. d["q_%d_vec" % len(v)] = v
  218. return tk_count
  219. def main(comm, mod):
  220. tm_fnm = os.path.join(
  221. get_project_base_directory(),
  222. "rag/res",
  223. f"{comm}-{mod}.tm")
  224. tm = findMaxTm(tm_fnm)
  225. rows = collect(comm, mod, tm)
  226. if len(rows) == 0:
  227. return
  228. tmf = open(tm_fnm, "a+")
  229. for _, r in rows.iterrows():
  230. callback = partial(set_progress, r["id"], r["from_page"], r["to_page"])
  231. #callback(random.random()/10., "Task has been received.")
  232. try:
  233. embd_mdl = LLMBundle(r["tenant_id"], LLMType.EMBEDDING, llm_name=r["embd_id"], lang=r["language"])
  234. except Exception as e:
  235. traceback.print_stack(e)
  236. callback(prog=-1, msg=str(e))
  237. continue
  238. st = timer()
  239. cks = build(r)
  240. cron_logger.info("Build chunks({}): {}".format(r["name"], timer()-st))
  241. if cks is None:
  242. continue
  243. if not cks:
  244. tmf.write(str(r["update_time"]) + "\n")
  245. callback(1., "No chunk! Done!")
  246. continue
  247. # TODO: exception handler
  248. ## set_progress(r["did"], -1, "ERROR: ")
  249. callback(
  250. msg="Finished slicing files(%d). Start to embedding the content." %
  251. len(cks))
  252. st = timer()
  253. try:
  254. tk_count = embedding(cks, embd_mdl, r["parser_config"], callback)
  255. except Exception as e:
  256. callback(-1, "Embedding error:{}".format(str(e)))
  257. cron_logger.error(str(e))
  258. tk_count = 0
  259. cron_logger.info("Embedding elapsed({}): {}".format(r["name"], timer()-st))
  260. callback(msg="Finished embedding({})! Start to build index!".format(timer()-st))
  261. init_kb(r)
  262. chunk_count = len(set([c["_id"] for c in cks]))
  263. st = timer()
  264. es_r = ELASTICSEARCH.bulk(cks, search.index_name(r["tenant_id"]))
  265. cron_logger.info("Indexing elapsed({}): {}".format(r["name"], timer()-st))
  266. if es_r:
  267. callback(-1, "Index failure!")
  268. ELASTICSEARCH.deleteByQuery(
  269. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  270. cron_logger.error(str(es_r))
  271. else:
  272. if TaskService.do_cancel(r["id"]):
  273. ELASTICSEARCH.deleteByQuery(
  274. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  275. continue
  276. callback(1., "Done!")
  277. DocumentService.increment_chunk_num(
  278. r["doc_id"], r["kb_id"], tk_count, chunk_count, 0)
  279. cron_logger.info(
  280. "Chunk doc({}), token({}), chunks({}), elapsed:{}".format(
  281. r["id"], tk_count, len(cks), timer()-st))
  282. tmf.write(str(r["update_time"]) + "\n")
  283. tmf.close()
  284. if __name__ == "__main__":
  285. peewee_logger = logging.getLogger('peewee')
  286. peewee_logger.propagate = False
  287. peewee_logger.addHandler(database_logger.handlers[0])
  288. peewee_logger.setLevel(database_logger.level)
  289. #from mpi4py import MPI
  290. #comm = MPI.COMM_WORLD
  291. while True:
  292. main(int(sys.argv[2]), int(sys.argv[1]))
  293. close_connection()