Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

task_executor.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. # from beartype import BeartypeConf
  16. # from beartype.claw import beartype_all # <-- you didn't sign up for this
  17. # beartype_all(conf=BeartypeConf(violation_type=UserWarning)) # <-- emit warnings from all code
  18. import sys
  19. from api.utils.log_utils import initRootLogger
  20. CONSUMER_NO = "0" if len(sys.argv) < 2 else sys.argv[1]
  21. CONSUMER_NAME = "task_executor_" + CONSUMER_NO
  22. initRootLogger(CONSUMER_NAME)
  23. import logging
  24. import os
  25. from datetime import datetime
  26. import json
  27. import hashlib
  28. import copy
  29. import re
  30. import time
  31. import threading
  32. from functools import partial
  33. from io import BytesIO
  34. from multiprocessing.context import TimeoutError
  35. from timeit import default_timer as timer
  36. import tracemalloc
  37. import numpy as np
  38. from api.db import LLMType, ParserType
  39. from api.db.services.dialog_service import keyword_extraction, question_proposal
  40. from api.db.services.document_service import DocumentService
  41. from api.db.services.llm_service import LLMBundle
  42. from api.db.services.task_service import TaskService
  43. from api.db.services.file2document_service import File2DocumentService
  44. from api import settings
  45. from api.versions import get_ragflow_version
  46. from api.db.db_models import close_connection
  47. from rag.app import laws, paper, presentation, manual, qa, table, book, resume, picture, naive, one, audio, \
  48. knowledge_graph, email
  49. from rag.nlp import search, rag_tokenizer
  50. from rag.raptor import RecursiveAbstractiveProcessing4TreeOrganizedRetrieval as Raptor
  51. from rag.settings import DOC_MAXIMUM_SIZE, SVR_QUEUE_NAME, print_rag_settings
  52. from rag.utils import rmSpace, num_tokens_from_string
  53. from rag.utils.redis_conn import REDIS_CONN, Payload
  54. from rag.utils.storage_factory import STORAGE_IMPL
  55. BATCH_SIZE = 64
  56. FACTORY = {
  57. "general": naive,
  58. ParserType.NAIVE.value: naive,
  59. ParserType.PAPER.value: paper,
  60. ParserType.BOOK.value: book,
  61. ParserType.PRESENTATION.value: presentation,
  62. ParserType.MANUAL.value: manual,
  63. ParserType.LAWS.value: laws,
  64. ParserType.QA.value: qa,
  65. ParserType.TABLE.value: table,
  66. ParserType.RESUME.value: resume,
  67. ParserType.PICTURE.value: picture,
  68. ParserType.ONE.value: one,
  69. ParserType.AUDIO.value: audio,
  70. ParserType.EMAIL.value: email,
  71. ParserType.KG.value: knowledge_graph
  72. }
  73. CONSUMER_NAME = "task_consumer_" + CONSUMER_NO
  74. PAYLOAD: Payload | None = None
  75. BOOT_AT = datetime.now().isoformat()
  76. PENDING_TASKS = 0
  77. LAG_TASKS = 0
  78. mt_lock = threading.Lock()
  79. DONE_TASKS = 0
  80. FAILED_TASKS = 0
  81. CURRENT_TASK = None
  82. def set_progress(task_id, from_page=0, to_page=-1, prog=None, msg="Processing..."):
  83. global PAYLOAD
  84. if prog is not None and prog < 0:
  85. msg = "[ERROR]" + msg
  86. cancel = TaskService.do_cancel(task_id)
  87. if cancel:
  88. msg += " [Canceled]"
  89. prog = -1
  90. if to_page > 0:
  91. if msg:
  92. msg = f"Page({from_page + 1}~{to_page + 1}): " + msg
  93. d = {"progress_msg": msg}
  94. if prog is not None:
  95. d["progress"] = prog
  96. try:
  97. logging.info(f"set_progress({task_id}), progress: {prog}, progress_msg: {msg}")
  98. TaskService.update_progress(task_id, d)
  99. except Exception:
  100. logging.exception(f"set_progress({task_id}) got exception")
  101. close_connection()
  102. if cancel:
  103. if PAYLOAD:
  104. PAYLOAD.ack()
  105. PAYLOAD = None
  106. os._exit(0)
  107. def collect():
  108. global CONSUMER_NAME, PAYLOAD, DONE_TASKS, FAILED_TASKS
  109. try:
  110. PAYLOAD = REDIS_CONN.get_unacked_for(CONSUMER_NAME, SVR_QUEUE_NAME, "rag_flow_svr_task_broker")
  111. if not PAYLOAD:
  112. PAYLOAD = REDIS_CONN.queue_consumer(SVR_QUEUE_NAME, "rag_flow_svr_task_broker", CONSUMER_NAME)
  113. if not PAYLOAD:
  114. time.sleep(1)
  115. return None
  116. except Exception:
  117. logging.exception("Get task event from queue exception")
  118. return None
  119. msg = PAYLOAD.get_message()
  120. if not msg:
  121. return None
  122. if TaskService.do_cancel(msg["id"]):
  123. with mt_lock:
  124. DONE_TASKS += 1
  125. logging.info("Task {} has been canceled.".format(msg["id"]))
  126. return None
  127. task = TaskService.get_task(msg["id"])
  128. if not task:
  129. with mt_lock:
  130. DONE_TASKS += 1
  131. logging.warning("{} empty task!".format(msg["id"]))
  132. return None
  133. if msg.get("type", "") == "raptor":
  134. task["task_type"] = "raptor"
  135. return task
  136. def get_storage_binary(bucket, name):
  137. return STORAGE_IMPL.get(bucket, name)
  138. def build_chunks(task, progress_callback):
  139. if task["size"] > DOC_MAXIMUM_SIZE:
  140. set_progress(task["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  141. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  142. return []
  143. chunker = FACTORY[task["parser_id"].lower()]
  144. try:
  145. st = timer()
  146. bucket, name = File2DocumentService.get_storage_address(doc_id=task["doc_id"])
  147. binary = get_storage_binary(bucket, name)
  148. logging.info("From minio({}) {}/{}".format(timer() - st, task["location"], task["name"]))
  149. except TimeoutError:
  150. progress_callback(-1, "Internal server error: Fetch file from minio timeout. Could you try it again.")
  151. logging.exception("Minio {}/{} got timeout: Fetch file from minio timeout.".format(task["location"], task["name"]))
  152. raise
  153. except Exception as e:
  154. if re.search("(No such file|not found)", str(e)):
  155. progress_callback(-1, "Can not find file <%s> from minio. Could you try it again?" % task["name"])
  156. else:
  157. progress_callback(-1, "Get file from minio: %s" % str(e).replace("'", ""))
  158. logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
  159. raise
  160. try:
  161. cks = chunker.chunk(task["name"], binary=binary, from_page=task["from_page"],
  162. to_page=task["to_page"], lang=task["language"], callback=progress_callback,
  163. kb_id=task["kb_id"], parser_config=task["parser_config"], tenant_id=task["tenant_id"])
  164. logging.info("Chunking({}) {}/{} done".format(timer() - st, task["location"], task["name"]))
  165. except Exception as e:
  166. progress_callback(-1, "Internal server error while chunking: %s" % str(e).replace("'", ""))
  167. logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
  168. raise
  169. docs = []
  170. doc = {
  171. "doc_id": task["doc_id"],
  172. "kb_id": str(task["kb_id"])
  173. }
  174. if task["pagerank"]:
  175. doc["pagerank_fea"] = int(task["pagerank"])
  176. el = 0
  177. for ck in cks:
  178. d = copy.deepcopy(doc)
  179. d.update(ck)
  180. md5 = hashlib.md5()
  181. md5.update((ck["content_with_weight"] +
  182. str(d["doc_id"])).encode("utf-8"))
  183. d["id"] = md5.hexdigest()
  184. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  185. d["create_timestamp_flt"] = datetime.now().timestamp()
  186. if not d.get("image"):
  187. _ = d.pop("image", None)
  188. d["img_id"] = ""
  189. d["page_num_list"] = json.dumps([])
  190. d["position_list"] = json.dumps([])
  191. d["top_list"] = json.dumps([])
  192. docs.append(d)
  193. continue
  194. try:
  195. output_buffer = BytesIO()
  196. if isinstance(d["image"], bytes):
  197. output_buffer = BytesIO(d["image"])
  198. else:
  199. d["image"].save(output_buffer, format='JPEG')
  200. st = timer()
  201. STORAGE_IMPL.put(task["kb_id"], d["id"], output_buffer.getvalue())
  202. el += timer() - st
  203. except Exception:
  204. logging.exception("Saving image of chunk {}/{}/{} got exception".format(task["location"], task["name"], d["_id"]))
  205. raise
  206. d["img_id"] = "{}-{}".format(task["kb_id"], d["id"])
  207. del d["image"]
  208. docs.append(d)
  209. logging.info("MINIO PUT({}):{}".format(task["name"], el))
  210. if task["parser_config"].get("auto_keywords", 0):
  211. st = timer()
  212. progress_callback(msg="Start to generate keywords for every chunk ...")
  213. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  214. for d in docs:
  215. d["important_kwd"] = keyword_extraction(chat_mdl, d["content_with_weight"],
  216. task["parser_config"]["auto_keywords"]).split(",")
  217. d["important_tks"] = rag_tokenizer.tokenize(" ".join(d["important_kwd"]))
  218. progress_callback(msg="Keywords generation completed in {:.2f}s".format(timer() - st))
  219. if task["parser_config"].get("auto_questions", 0):
  220. st = timer()
  221. progress_callback(msg="Start to generate questions for every chunk ...")
  222. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  223. for d in docs:
  224. d["question_kwd"] = question_proposal(chat_mdl, d["content_with_weight"], task["parser_config"]["auto_questions"]).split("\n")
  225. d["question_tks"] = rag_tokenizer.tokenize("\n".join(d["question_kwd"]))
  226. progress_callback(msg="Question generation completed in {:.2f}s".format(timer() - st))
  227. return docs
  228. def init_kb(row, vector_size: int):
  229. idxnm = search.index_name(row["tenant_id"])
  230. return settings.docStoreConn.createIdx(idxnm, row.get("kb_id",""), vector_size)
  231. def embedding(docs, mdl, parser_config=None, callback=None):
  232. if parser_config is None:
  233. parser_config = {}
  234. batch_size = 16
  235. tts, cnts = [], []
  236. for d in docs:
  237. tts.append(rmSpace(d.get("docnm_kwd", "Title")))
  238. c = "\n".join(d.get("question_kwd", []))
  239. if not c:
  240. c = d["content_with_weight"]
  241. c = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", c)
  242. cnts.append(c)
  243. tk_count = 0
  244. if len(tts) == len(cnts):
  245. tts_ = np.array([])
  246. for i in range(0, len(tts), batch_size):
  247. vts, c = mdl.encode(tts[i: i + batch_size])
  248. if len(tts_) == 0:
  249. tts_ = vts
  250. else:
  251. tts_ = np.concatenate((tts_, vts), axis=0)
  252. tk_count += c
  253. callback(prog=0.6 + 0.1 * (i + 1) / len(tts), msg="")
  254. tts = tts_
  255. cnts_ = np.array([])
  256. for i in range(0, len(cnts), batch_size):
  257. vts, c = mdl.encode(cnts[i: i + batch_size])
  258. if len(cnts_) == 0:
  259. cnts_ = vts
  260. else:
  261. cnts_ = np.concatenate((cnts_, vts), axis=0)
  262. tk_count += c
  263. callback(prog=0.7 + 0.2 * (i + 1) / len(cnts), msg="")
  264. cnts = cnts_
  265. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  266. vects = (title_w * tts + (1 - title_w) *
  267. cnts) if len(tts) == len(cnts) else cnts
  268. assert len(vects) == len(docs)
  269. vector_size = 0
  270. for i, d in enumerate(docs):
  271. v = vects[i].tolist()
  272. vector_size = len(v)
  273. d["q_%d_vec" % len(v)] = v
  274. return tk_count, vector_size
  275. def run_raptor(row, chat_mdl, embd_mdl, callback=None):
  276. vts, _ = embd_mdl.encode(["ok"])
  277. vector_size = len(vts[0])
  278. vctr_nm = "q_%d_vec" % vector_size
  279. chunks = []
  280. for d in settings.retrievaler.chunk_list(row["doc_id"], row["tenant_id"], [str(row["kb_id"])],
  281. fields=["content_with_weight", vctr_nm]):
  282. chunks.append((d["content_with_weight"], np.array(d[vctr_nm])))
  283. raptor = Raptor(
  284. row["parser_config"]["raptor"].get("max_cluster", 64),
  285. chat_mdl,
  286. embd_mdl,
  287. row["parser_config"]["raptor"]["prompt"],
  288. row["parser_config"]["raptor"]["max_token"],
  289. row["parser_config"]["raptor"]["threshold"]
  290. )
  291. original_length = len(chunks)
  292. chunks = raptor(chunks, row["parser_config"]["raptor"]["random_seed"], callback)
  293. doc = {
  294. "doc_id": row["doc_id"],
  295. "kb_id": [str(row["kb_id"])],
  296. "docnm_kwd": row["name"],
  297. "title_tks": rag_tokenizer.tokenize(row["name"])
  298. }
  299. if row["pagerank"]:
  300. doc["pagerank_fea"] = int(row["pagerank"])
  301. res = []
  302. tk_count = 0
  303. for content, vctr in chunks[original_length:]:
  304. d = copy.deepcopy(doc)
  305. md5 = hashlib.md5()
  306. md5.update((content + str(d["doc_id"])).encode("utf-8"))
  307. d["id"] = md5.hexdigest()
  308. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  309. d["create_timestamp_flt"] = datetime.now().timestamp()
  310. d[vctr_nm] = vctr.tolist()
  311. d["content_with_weight"] = content
  312. d["content_ltks"] = rag_tokenizer.tokenize(content)
  313. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  314. res.append(d)
  315. tk_count += num_tokens_from_string(content)
  316. return res, tk_count, vector_size
  317. def do_handle_task(task):
  318. task_id = task["id"]
  319. task_from_page = task["from_page"]
  320. task_to_page = task["to_page"]
  321. task_tenant_id = task["tenant_id"]
  322. task_embedding_id = task["embd_id"]
  323. task_language = task["language"]
  324. task_llm_id = task["llm_id"]
  325. task_dataset_id = task["kb_id"]
  326. task_doc_id = task["doc_id"]
  327. task_document_name = task["name"]
  328. task_parser_config = task["parser_config"]
  329. # prepare the progress callback function
  330. progress_callback = partial(set_progress, task_id, task_from_page, task_to_page)
  331. try:
  332. # bind embedding model
  333. embedding_model = LLMBundle(task_tenant_id, LLMType.EMBEDDING, llm_name=task_embedding_id, lang=task_language)
  334. except Exception as e:
  335. error_message = f'Fail to bind embedding model: {str(e)}'
  336. progress_callback(-1, msg=error_message)
  337. logging.exception(error_message)
  338. raise
  339. # Either using RAPTOR or Standard chunking methods
  340. if task.get("task_type", "") == "raptor":
  341. try:
  342. # bind LLM for raptor
  343. chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
  344. # run RAPTOR
  345. chunks, token_count, vector_size = run_raptor(task, chat_model, embedding_model, progress_callback)
  346. except Exception as e:
  347. error_message = f'Fail to bind LLM used by RAPTOR: {str(e)}'
  348. progress_callback(-1, msg=error_message)
  349. logging.exception(error_message)
  350. raise
  351. else:
  352. # Standard chunking methods
  353. start_ts = timer()
  354. chunks = build_chunks(task, progress_callback)
  355. logging.info("Build document {}: {:.2f}s".format(task_document_name, timer() - start_ts))
  356. if chunks is None:
  357. return
  358. if not chunks:
  359. progress_callback(1., msg=f"No chunk built from {task_document_name}")
  360. return
  361. # TODO: exception handler
  362. ## set_progress(task["did"], -1, "ERROR: ")
  363. progress_callback(msg="Generate {} chunks".format(len(chunks)))
  364. start_ts = timer()
  365. try:
  366. token_count, vector_size = embedding(chunks, embedding_model, task_parser_config, progress_callback)
  367. except Exception as e:
  368. error_message = "Generate embedding error:{}".format(str(e))
  369. progress_callback(-1, error_message)
  370. logging.exception(error_message)
  371. token_count = 0
  372. raise
  373. progress_message = "Embedding chunks ({:.2f}s)".format(timer() - start_ts)
  374. logging.info(progress_message)
  375. progress_callback(msg=progress_message)
  376. # logging.info(f"task_executor init_kb index {search.index_name(task_tenant_id)} embedding_model {embedding_model.llm_name} vector length {vector_size}")
  377. init_kb(task, vector_size)
  378. chunk_count = len(set([chunk["id"] for chunk in chunks]))
  379. start_ts = timer()
  380. doc_store_result = ""
  381. es_bulk_size = 4
  382. for b in range(0, len(chunks), es_bulk_size):
  383. doc_store_result = settings.docStoreConn.insert(chunks[b:b + es_bulk_size], search.index_name(task_tenant_id), task_dataset_id)
  384. if b % 128 == 0:
  385. progress_callback(prog=0.8 + 0.1 * (b + 1) / len(chunks), msg="")
  386. logging.info("Indexing {} elapsed: {:.2f}".format(task_document_name, timer() - start_ts))
  387. if doc_store_result:
  388. error_message = f"Insert chunk error: {doc_store_result}, please check log file and Elasticsearch/Infinity status!"
  389. progress_callback(-1, msg=error_message)
  390. settings.docStoreConn.delete({"doc_id": task_doc_id}, search.index_name(task_tenant_id), task_dataset_id)
  391. logging.error(error_message)
  392. raise Exception(error_message)
  393. if TaskService.do_cancel(task_id):
  394. settings.docStoreConn.delete({"doc_id": task_doc_id}, search.index_name(task_tenant_id), task_dataset_id)
  395. return
  396. DocumentService.increment_chunk_num(task_doc_id, task_dataset_id, token_count, chunk_count, 0)
  397. time_cost = timer() - start_ts
  398. progress_callback(prog=1.0, msg="Done ({:.2f}s)".format(time_cost))
  399. logging.info("Chunk doc({}), token({}), chunks({}), elapsed:{:.2f}".format(task_id, token_count, len(chunks), time_cost))
  400. def handle_task():
  401. global PAYLOAD, mt_lock, DONE_TASKS, FAILED_TASKS, CURRENT_TASK
  402. task = collect()
  403. if task:
  404. try:
  405. logging.info(f"handle_task begin for task {json.dumps(task)}")
  406. with mt_lock:
  407. CURRENT_TASK = copy.deepcopy(task)
  408. do_handle_task(task)
  409. with mt_lock:
  410. DONE_TASKS += 1
  411. CURRENT_TASK = None
  412. logging.info(f"handle_task done for task {json.dumps(task)}")
  413. except Exception:
  414. with mt_lock:
  415. FAILED_TASKS += 1
  416. CURRENT_TASK = None
  417. logging.exception(f"handle_task got exception for task {json.dumps(task)}")
  418. if PAYLOAD:
  419. PAYLOAD.ack()
  420. PAYLOAD = None
  421. def report_status():
  422. global CONSUMER_NAME, BOOT_AT, PENDING_TASKS, LAG_TASKS, mt_lock, DONE_TASKS, FAILED_TASKS, CURRENT_TASK
  423. REDIS_CONN.sadd("TASKEXE", CONSUMER_NAME)
  424. while True:
  425. try:
  426. now = datetime.now()
  427. group_info = REDIS_CONN.queue_info(SVR_QUEUE_NAME, "rag_flow_svr_task_broker")
  428. if group_info is not None:
  429. PENDING_TASKS = int(group_info["pending"])
  430. LAG_TASKS = int(group_info["lag"])
  431. with mt_lock:
  432. heartbeat = json.dumps({
  433. "name": CONSUMER_NAME,
  434. "now": now.isoformat(),
  435. "boot_at": BOOT_AT,
  436. "pending": PENDING_TASKS,
  437. "lag": LAG_TASKS,
  438. "done": DONE_TASKS,
  439. "failed": FAILED_TASKS,
  440. "current": CURRENT_TASK,
  441. })
  442. REDIS_CONN.zadd(CONSUMER_NAME, heartbeat, now.timestamp())
  443. logging.info(f"{CONSUMER_NAME} reported heartbeat: {heartbeat}")
  444. expired = REDIS_CONN.zcount(CONSUMER_NAME, 0, now.timestamp() - 60 * 30)
  445. if expired > 0:
  446. REDIS_CONN.zpopmin(CONSUMER_NAME, expired)
  447. except Exception:
  448. logging.exception("report_status got exception")
  449. time.sleep(30)
  450. def analyze_heap(snapshot1: tracemalloc.Snapshot, snapshot2: tracemalloc.Snapshot, snapshot_id: int, dump_full: bool):
  451. msg = ""
  452. if dump_full:
  453. stats2 = snapshot2.statistics('lineno')
  454. msg += f"{CONSUMER_NAME} memory usage of snapshot {snapshot_id}:\n"
  455. for stat in stats2[:10]:
  456. msg += f"{stat}\n"
  457. stats1_vs_2 = snapshot2.compare_to(snapshot1, 'lineno')
  458. msg += f"{CONSUMER_NAME} memory usage increase from snapshot {snapshot_id - 1} to snapshot {snapshot_id}:\n"
  459. for stat in stats1_vs_2[:10]:
  460. msg += f"{stat}\n"
  461. msg += f"{CONSUMER_NAME} detailed traceback for the top memory consumers:\n"
  462. for stat in stats1_vs_2[:3]:
  463. msg += '\n'.join(stat.traceback.format())
  464. logging.info(msg)
  465. def main():
  466. logging.info(r"""
  467. ______ __ ______ __
  468. /_ __/___ ______/ /__ / ____/ _____ _______ __/ /_____ _____
  469. / / / __ `/ ___/ //_/ / __/ | |/_/ _ \/ ___/ / / / __/ __ \/ ___/
  470. / / / /_/ (__ ) ,< / /____> </ __/ /__/ /_/ / /_/ /_/ / /
  471. /_/ \__,_/____/_/|_| /_____/_/|_|\___/\___/\__,_/\__/\____/_/
  472. """)
  473. logging.info(f'TaskExecutor: RAGFlow version: {get_ragflow_version()}')
  474. settings.init_settings()
  475. print_rag_settings()
  476. background_thread = threading.Thread(target=report_status)
  477. background_thread.daemon = True
  478. background_thread.start()
  479. TRACE_MALLOC_DELTA = int(os.environ.get('TRACE_MALLOC_DELTA', "0"))
  480. TRACE_MALLOC_FULL = int(os.environ.get('TRACE_MALLOC_FULL', "0"))
  481. if TRACE_MALLOC_DELTA > 0:
  482. if TRACE_MALLOC_FULL < TRACE_MALLOC_DELTA:
  483. TRACE_MALLOC_FULL = TRACE_MALLOC_DELTA
  484. tracemalloc.start()
  485. snapshot1 = tracemalloc.take_snapshot()
  486. while True:
  487. handle_task()
  488. num_tasks = DONE_TASKS + FAILED_TASKS
  489. if TRACE_MALLOC_DELTA > 0 and num_tasks > 0 and num_tasks % TRACE_MALLOC_DELTA == 0:
  490. snapshot2 = tracemalloc.take_snapshot()
  491. analyze_heap(snapshot1, snapshot2, int(num_tasks / TRACE_MALLOC_DELTA), num_tasks % TRACE_MALLOC_FULL == 0)
  492. snapshot1 = snapshot2
  493. snapshot2 = None
  494. if __name__ == "__main__":
  495. main()