Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

task_executor.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 concurrent.futures import ThreadPoolExecutor
  27. from functools import partial
  28. from api.db.services.file2document_service import File2DocumentService
  29. from api.settings import retrievaler
  30. from rag.raptor import RecursiveAbstractiveProcessing4TreeOrganizedRetrieval as Raptor
  31. from rag.utils.minio_conn import MINIO
  32. from api.db.db_models import close_connection
  33. from rag.settings import database_logger, SVR_QUEUE_NAME
  34. from rag.settings import cron_logger, DOC_MAXIMUM_SIZE
  35. from multiprocessing import Pool
  36. import numpy as np
  37. from elasticsearch_dsl import Q, Search
  38. from multiprocessing.context import TimeoutError
  39. from api.db.services.task_service import TaskService
  40. from rag.utils.es_conn import ELASTICSEARCH
  41. from timeit import default_timer as timer
  42. from rag.utils import rmSpace, findMaxTm, num_tokens_from_string
  43. from rag.nlp import search, rag_tokenizer
  44. from io import BytesIO
  45. import pandas as pd
  46. from rag.app import laws, paper, presentation, manual, qa, table, book, resume, picture, naive, one, audio, knowledge_graph, email
  47. from api.db import LLMType, ParserType
  48. from api.db.services.document_service import DocumentService
  49. from api.db.services.llm_service import LLMBundle
  50. from api.utils.file_utils import get_project_base_directory
  51. from rag.utils.redis_conn import REDIS_CONN
  52. BATCH_SIZE = 64
  53. FACTORY = {
  54. "general": naive,
  55. ParserType.NAIVE.value: naive,
  56. ParserType.PAPER.value: paper,
  57. ParserType.BOOK.value: book,
  58. ParserType.PRESENTATION.value: presentation,
  59. ParserType.MANUAL.value: manual,
  60. ParserType.LAWS.value: laws,
  61. ParserType.QA.value: qa,
  62. ParserType.TABLE.value: table,
  63. ParserType.RESUME.value: resume,
  64. ParserType.PICTURE.value: picture,
  65. ParserType.ONE.value: one,
  66. ParserType.AUDIO.value: audio,
  67. ParserType.EMAIL.value: email,
  68. ParserType.KG.value: knowledge_graph
  69. }
  70. def set_progress(task_id, from_page=0, to_page=-1,
  71. prog=None, msg="Processing..."):
  72. if prog is not None and prog < 0:
  73. msg = "[ERROR]" + msg
  74. cancel = TaskService.do_cancel(task_id)
  75. if cancel:
  76. msg += " [Canceled]"
  77. prog = -1
  78. if to_page > 0:
  79. if msg:
  80. msg = f"Page({from_page + 1}~{to_page + 1}): " + msg
  81. d = {"progress_msg": msg}
  82. if prog is not None:
  83. d["progress"] = prog
  84. try:
  85. TaskService.update_progress(task_id, d)
  86. except Exception as e:
  87. cron_logger.error("set_progress:({}), {}".format(task_id, str(e)))
  88. close_connection()
  89. if cancel:
  90. sys.exit()
  91. def collect():
  92. try:
  93. payload = REDIS_CONN.queue_consumer(SVR_QUEUE_NAME, "rag_flow_svr_task_broker", "rag_flow_svr_task_consumer")
  94. if not payload:
  95. time.sleep(1)
  96. return pd.DataFrame()
  97. except Exception as e:
  98. cron_logger.error("Get task event from queue exception:" + str(e))
  99. return pd.DataFrame()
  100. msg = payload.get_message()
  101. payload.ack()
  102. if not msg: return pd.DataFrame()
  103. if TaskService.do_cancel(msg["id"]):
  104. cron_logger.info("Task {} has been canceled.".format(msg["id"]))
  105. return pd.DataFrame()
  106. tasks = TaskService.get_tasks(msg["id"])
  107. if not tasks:
  108. cron_logger.warn("{} empty task!".format(msg["id"]))
  109. return []
  110. tasks = pd.DataFrame(tasks)
  111. if msg.get("type", "") == "raptor":
  112. tasks["task_type"] = "raptor"
  113. return tasks
  114. def get_minio_binary(bucket, name):
  115. return MINIO.get(bucket, name)
  116. def build(row):
  117. if row["size"] > DOC_MAXIMUM_SIZE:
  118. set_progress(row["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  119. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  120. return []
  121. callback = partial(
  122. set_progress,
  123. row["id"],
  124. row["from_page"],
  125. row["to_page"])
  126. chunker = FACTORY[row["parser_id"].lower()]
  127. try:
  128. st = timer()
  129. bucket, name = File2DocumentService.get_minio_address(doc_id=row["doc_id"])
  130. binary = get_minio_binary(bucket, name)
  131. cron_logger.info(
  132. "From minio({}) {}/{}".format(timer() - st, row["location"], row["name"]))
  133. except TimeoutError as e:
  134. callback(-1, f"Internal server error: Fetch file from minio timeout. Could you try it again.")
  135. cron_logger.error(
  136. "Minio {}/{}: Fetch file from minio timeout.".format(row["location"], row["name"]))
  137. return
  138. except Exception as e:
  139. if re.search("(No such file|not found)", str(e)):
  140. callback(-1, "Can not find file <%s> from minio. Could you try it again?" % row["name"])
  141. else:
  142. callback(-1, f"Get file from minio: %s" %
  143. str(e).replace("'", ""))
  144. traceback.print_exc()
  145. return
  146. try:
  147. cks = chunker.chunk(row["name"], binary=binary, from_page=row["from_page"],
  148. to_page=row["to_page"], lang=row["language"], callback=callback,
  149. kb_id=row["kb_id"], parser_config=row["parser_config"], tenant_id=row["tenant_id"])
  150. cron_logger.info(
  151. "Chunking({}) {}/{}".format(timer() - st, row["location"], row["name"]))
  152. except Exception as e:
  153. callback(-1, f"Internal server error while chunking: %s" %
  154. str(e).replace("'", ""))
  155. cron_logger.error(
  156. "Chunking {}/{}: {}".format(row["location"], row["name"], str(e)))
  157. traceback.print_exc()
  158. return
  159. docs = []
  160. doc = {
  161. "doc_id": row["doc_id"],
  162. "kb_id": [str(row["kb_id"])]
  163. }
  164. el = 0
  165. for ck in cks:
  166. d = copy.deepcopy(doc)
  167. d.update(ck)
  168. md5 = hashlib.md5()
  169. md5.update((ck["content_with_weight"] +
  170. str(d["doc_id"])).encode("utf-8"))
  171. d["_id"] = md5.hexdigest()
  172. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  173. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  174. if not d.get("image"):
  175. docs.append(d)
  176. continue
  177. output_buffer = BytesIO()
  178. if isinstance(d["image"], bytes):
  179. output_buffer = BytesIO(d["image"])
  180. else:
  181. d["image"].save(output_buffer, format='JPEG')
  182. st = timer()
  183. MINIO.put(row["kb_id"], d["_id"], output_buffer.getvalue())
  184. el += timer() - st
  185. d["img_id"] = "{}-{}".format(row["kb_id"], d["_id"])
  186. del d["image"]
  187. docs.append(d)
  188. cron_logger.info("MINIO PUT({}):{}".format(row["name"], el))
  189. return docs
  190. def init_kb(row):
  191. idxnm = search.index_name(row["tenant_id"])
  192. if ELASTICSEARCH.indexExist(idxnm):
  193. return
  194. return ELASTICSEARCH.createIdx(idxnm, json.load(
  195. open(os.path.join(get_project_base_directory(), "conf", "mapping.json"), "r")))
  196. def embedding(docs, mdl, parser_config={}, callback=None):
  197. batch_size = 32
  198. tts, cnts = [rmSpace(d["title_tks"]) for d in docs if d.get("title_tks")], [
  199. re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", d["content_with_weight"]) for d in docs]
  200. tk_count = 0
  201. if len(tts) == len(cnts):
  202. tts_ = np.array([])
  203. for i in range(0, len(tts), batch_size):
  204. vts, c = mdl.encode(tts[i: i + batch_size])
  205. if len(tts_) == 0:
  206. tts_ = vts
  207. else:
  208. tts_ = np.concatenate((tts_, vts), axis=0)
  209. tk_count += c
  210. callback(prog=0.6 + 0.1 * (i + 1) / len(tts), msg="")
  211. tts = tts_
  212. cnts_ = np.array([])
  213. for i in range(0, len(cnts), batch_size):
  214. vts, c = mdl.encode(cnts[i: i + batch_size])
  215. if len(cnts_) == 0:
  216. cnts_ = vts
  217. else:
  218. cnts_ = np.concatenate((cnts_, vts), axis=0)
  219. tk_count += c
  220. callback(prog=0.7 + 0.2 * (i + 1) / len(cnts), msg="")
  221. cnts = cnts_
  222. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  223. vects = (title_w * tts + (1 - title_w) *
  224. cnts) if len(tts) == len(cnts) else cnts
  225. assert len(vects) == len(docs)
  226. for i, d in enumerate(docs):
  227. v = vects[i].tolist()
  228. d["q_%d_vec" % len(v)] = v
  229. return tk_count
  230. def run_raptor(row, chat_mdl, embd_mdl, callback=None):
  231. vts, _ = embd_mdl.encode(["ok"])
  232. vctr_nm = "q_%d_vec"%len(vts[0])
  233. chunks = []
  234. for d in retrievaler.chunk_list(row["doc_id"], row["tenant_id"], fields=["content_with_weight", vctr_nm]):
  235. chunks.append((d["content_with_weight"], np.array(d[vctr_nm])))
  236. raptor = Raptor(
  237. row["parser_config"]["raptor"].get("max_cluster", 64),
  238. chat_mdl,
  239. embd_mdl,
  240. row["parser_config"]["raptor"]["prompt"],
  241. row["parser_config"]["raptor"]["max_token"],
  242. row["parser_config"]["raptor"]["threshold"]
  243. )
  244. original_length = len(chunks)
  245. raptor(chunks, row["parser_config"]["raptor"]["random_seed"], callback)
  246. doc = {
  247. "doc_id": row["doc_id"],
  248. "kb_id": [str(row["kb_id"])],
  249. "docnm_kwd": row["name"],
  250. "title_tks": rag_tokenizer.tokenize(row["name"])
  251. }
  252. res = []
  253. tk_count = 0
  254. for content, vctr in chunks[original_length:]:
  255. d = copy.deepcopy(doc)
  256. md5 = hashlib.md5()
  257. md5.update((content + str(d["doc_id"])).encode("utf-8"))
  258. d["_id"] = md5.hexdigest()
  259. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  260. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  261. d[vctr_nm] = vctr.tolist()
  262. d["content_with_weight"] = content
  263. d["content_ltks"] = rag_tokenizer.tokenize(content)
  264. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  265. res.append(d)
  266. tk_count += num_tokens_from_string(content)
  267. return res, tk_count
  268. def main():
  269. rows = collect()
  270. if len(rows) == 0:
  271. return
  272. for _, r in rows.iterrows():
  273. callback = partial(set_progress, r["id"], r["from_page"], r["to_page"])
  274. try:
  275. embd_mdl = LLMBundle(r["tenant_id"], LLMType.EMBEDDING, llm_name=r["embd_id"], lang=r["language"])
  276. except Exception as e:
  277. callback(-1, msg=str(e))
  278. cron_logger.error(str(e))
  279. continue
  280. if r.get("task_type", "") == "raptor":
  281. try:
  282. chat_mdl = LLMBundle(r["tenant_id"], LLMType.CHAT, llm_name=r["llm_id"], lang=r["language"])
  283. cks, tk_count = run_raptor(r, chat_mdl, embd_mdl, callback)
  284. except Exception as e:
  285. callback(-1, msg=str(e))
  286. cron_logger.error(str(e))
  287. continue
  288. else:
  289. st = timer()
  290. cks = build(r)
  291. cron_logger.info("Build chunks({}): {}".format(r["name"], timer() - st))
  292. if cks is None:
  293. continue
  294. if not cks:
  295. callback(1., "No chunk! Done!")
  296. continue
  297. # TODO: exception handler
  298. ## set_progress(r["did"], -1, "ERROR: ")
  299. callback(
  300. msg="Finished slicing files(%d). Start to embedding the content." %
  301. len(cks))
  302. st = timer()
  303. try:
  304. tk_count = embedding(cks, embd_mdl, r["parser_config"], callback)
  305. except Exception as e:
  306. callback(-1, "Embedding error:{}".format(str(e)))
  307. cron_logger.error(str(e))
  308. tk_count = 0
  309. cron_logger.info("Embedding elapsed({}): {:.2f}".format(r["name"], timer() - st))
  310. callback(msg="Finished embedding({:.2f})! Start to build index!".format(timer() - st))
  311. init_kb(r)
  312. chunk_count = len(set([c["_id"] for c in cks]))
  313. st = timer()
  314. es_r = ""
  315. es_bulk_size = 4
  316. for b in range(0, len(cks), es_bulk_size):
  317. es_r = ELASTICSEARCH.bulk(cks[b:b + es_bulk_size], search.index_name(r["tenant_id"]))
  318. if b % 128 == 0:
  319. callback(prog=0.8 + 0.1 * (b + 1) / len(cks), msg="")
  320. cron_logger.info("Indexing elapsed({}): {:.2f}".format(r["name"], timer() - st))
  321. if es_r:
  322. callback(-1, f"Insert chunk error, detail info please check ragflow-logs/api/cron_logger.log. Please also check ES status!")
  323. ELASTICSEARCH.deleteByQuery(
  324. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  325. cron_logger.error(str(es_r))
  326. else:
  327. if TaskService.do_cancel(r["id"]):
  328. ELASTICSEARCH.deleteByQuery(
  329. Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  330. continue
  331. callback(1., "Done!")
  332. DocumentService.increment_chunk_num(
  333. r["doc_id"], r["kb_id"], tk_count, chunk_count, 0)
  334. cron_logger.info(
  335. "Chunk doc({}), token({}), chunks({}), elapsed:{:.2f}".format(
  336. r["id"], tk_count, len(cks), timer() - st))
  337. def report_status():
  338. id = "0" if len(sys.argv) < 2 else sys.argv[1]
  339. while True:
  340. try:
  341. obj = REDIS_CONN.get("TASKEXE")
  342. if not obj: obj = {}
  343. else: obj = json.load(obj)
  344. if id not in obj: obj[id] = []
  345. obj[id].append(timer()*1000)
  346. obj[id] = obj[id][-60:]
  347. REDIS_CONN.set_obj("TASKEXE", obj, 60*2)
  348. except Exception as e:
  349. print("[Exception]:", str(e))
  350. time.sleep(60)
  351. if __name__ == "__main__":
  352. peewee_logger = logging.getLogger('peewee')
  353. peewee_logger.propagate = False
  354. peewee_logger.addHandler(database_logger.handlers[0])
  355. peewee_logger.setLevel(database_logger.level)
  356. exe = ThreadPoolExecutor(max_workers=1)
  357. exe.submit(report_status)
  358. while True:
  359. main()