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_service.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 os
  17. import random
  18. import xxhash
  19. import bisect
  20. from api.db.db_utils import bulk_insert_into_db
  21. from deepdoc.parser import PdfParser
  22. from peewee import JOIN
  23. from api.db.db_models import DB, File2Document, File
  24. from api.db import StatusEnum, FileType, TaskStatus
  25. from api.db.db_models import Task, Document, Knowledgebase, Tenant
  26. from api.db.services.common_service import CommonService
  27. from api.db.services.document_service import DocumentService
  28. from api.utils import current_timestamp, get_uuid
  29. from deepdoc.parser.excel_parser import RAGFlowExcelParser
  30. from rag.settings import SVR_QUEUE_NAME
  31. from rag.utils.storage_factory import STORAGE_IMPL
  32. from rag.utils.redis_conn import REDIS_CONN
  33. from api import settings
  34. from rag.nlp import search
  35. def trim_header_by_lines(text: str, max_length) -> str:
  36. len_text = len(text)
  37. if len_text <= max_length:
  38. return text
  39. for i in range(len_text):
  40. if text[i] == '\n' and len_text - i <= max_length:
  41. return text[i+1:]
  42. return text
  43. class TaskService(CommonService):
  44. model = Task
  45. @classmethod
  46. @DB.connection_context()
  47. def get_task(cls, task_id):
  48. fields = [
  49. cls.model.id,
  50. cls.model.doc_id,
  51. cls.model.from_page,
  52. cls.model.to_page,
  53. cls.model.retry_count,
  54. Document.kb_id,
  55. Document.parser_id,
  56. Document.parser_config,
  57. Document.name,
  58. Document.type,
  59. Document.location,
  60. Document.size,
  61. Knowledgebase.tenant_id,
  62. Knowledgebase.language,
  63. Knowledgebase.embd_id,
  64. Knowledgebase.pagerank,
  65. Tenant.img2txt_id,
  66. Tenant.asr_id,
  67. Tenant.llm_id,
  68. cls.model.update_time,
  69. ]
  70. docs = (
  71. cls.model.select(*fields)
  72. .join(Document, on=(cls.model.doc_id == Document.id))
  73. .join(Knowledgebase, on=(Document.kb_id == Knowledgebase.id))
  74. .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id))
  75. .where(cls.model.id == task_id)
  76. )
  77. docs = list(docs.dicts())
  78. if not docs:
  79. return None
  80. msg = "\nTask has been received."
  81. prog = random.random() / 10.0
  82. if docs[0]["retry_count"] >= 3:
  83. msg = "\nERROR: Task is abandoned after 3 times attempts."
  84. prog = -1
  85. cls.model.update(
  86. progress_msg=cls.model.progress_msg + msg,
  87. progress=prog,
  88. retry_count=docs[0]["retry_count"] + 1,
  89. ).where(cls.model.id == docs[0]["id"]).execute()
  90. if docs[0]["retry_count"] >= 3:
  91. return None
  92. return docs[0]
  93. @classmethod
  94. @DB.connection_context()
  95. def get_tasks(cls, doc_id: str):
  96. fields = [
  97. cls.model.id,
  98. cls.model.from_page,
  99. cls.model.progress,
  100. cls.model.digest,
  101. cls.model.chunk_ids,
  102. ]
  103. tasks = (
  104. cls.model.select(*fields).order_by(cls.model.from_page.asc(), cls.model.create_time.desc())
  105. .where(cls.model.doc_id == doc_id)
  106. )
  107. tasks = list(tasks.dicts())
  108. if not tasks:
  109. return None
  110. return tasks
  111. @classmethod
  112. @DB.connection_context()
  113. def update_chunk_ids(cls, id: str, chunk_ids: str):
  114. cls.model.update(chunk_ids=chunk_ids).where(cls.model.id == id).execute()
  115. @classmethod
  116. @DB.connection_context()
  117. def get_ongoing_doc_name(cls):
  118. with DB.lock("get_task", -1):
  119. docs = (
  120. cls.model.select(
  121. *[Document.id, Document.kb_id, Document.location, File.parent_id]
  122. )
  123. .join(Document, on=(cls.model.doc_id == Document.id))
  124. .join(
  125. File2Document,
  126. on=(File2Document.document_id == Document.id),
  127. join_type=JOIN.LEFT_OUTER,
  128. )
  129. .join(
  130. File,
  131. on=(File2Document.file_id == File.id),
  132. join_type=JOIN.LEFT_OUTER,
  133. )
  134. .where(
  135. Document.status == StatusEnum.VALID.value,
  136. Document.run == TaskStatus.RUNNING.value,
  137. ~(Document.type == FileType.VIRTUAL.value),
  138. cls.model.progress < 1,
  139. cls.model.create_time >= current_timestamp() - 1000 * 600,
  140. )
  141. )
  142. docs = list(docs.dicts())
  143. if not docs:
  144. return []
  145. return list(
  146. set(
  147. [
  148. (
  149. d["parent_id"] if d["parent_id"] else d["kb_id"],
  150. d["location"],
  151. )
  152. for d in docs
  153. ]
  154. )
  155. )
  156. @classmethod
  157. @DB.connection_context()
  158. def do_cancel(cls, id):
  159. task = cls.model.get_by_id(id)
  160. _, doc = DocumentService.get_by_id(task.doc_id)
  161. return doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  162. @classmethod
  163. @DB.connection_context()
  164. def update_progress(cls, id, info):
  165. if os.environ.get("MACOS"):
  166. if info["progress_msg"]:
  167. task = cls.model.get_by_id(id)
  168. progress_msg = trim_header_by_lines(task.progress_msg + "\n" + info["progress_msg"], 1000)
  169. cls.model.update(progress_msg=progress_msg).where(cls.model.id == id).execute()
  170. if "progress" in info:
  171. cls.model.update(progress=info["progress"]).where(
  172. cls.model.id == id
  173. ).execute()
  174. return
  175. with DB.lock("update_progress", -1):
  176. if info["progress_msg"]:
  177. task = cls.model.get_by_id(id)
  178. progress_msg = trim_header_by_lines(task.progress_msg + "\n" + info["progress_msg"], 1000)
  179. cls.model.update(progress_msg=progress_msg).where(cls.model.id == id).execute()
  180. if "progress" in info:
  181. cls.model.update(progress=info["progress"]).where(
  182. cls.model.id == id
  183. ).execute()
  184. def queue_tasks(doc: dict, bucket: str, name: str):
  185. def new_task():
  186. return {"id": get_uuid(), "doc_id": doc["id"], "progress": 0.0}
  187. tsks = []
  188. if doc["type"] == FileType.PDF.value:
  189. file_bin = STORAGE_IMPL.get(bucket, name)
  190. do_layout = doc["parser_config"].get("layout_recognize", True)
  191. pages = PdfParser.total_page_number(doc["name"], file_bin)
  192. page_size = doc["parser_config"].get("task_page_size", 12)
  193. if doc["parser_id"] == "paper":
  194. page_size = doc["parser_config"].get("task_page_size", 22)
  195. if doc["parser_id"] in ["one", "knowledge_graph"] or not do_layout:
  196. page_size = 10**9
  197. page_ranges = doc["parser_config"].get("pages") or [(1, 10**5)]
  198. for s, e in page_ranges:
  199. s -= 1
  200. s = max(0, s)
  201. e = min(e - 1, pages)
  202. for p in range(s, e, page_size):
  203. task = new_task()
  204. task["from_page"] = p
  205. task["to_page"] = min(p + page_size, e)
  206. tsks.append(task)
  207. elif doc["parser_id"] == "table":
  208. file_bin = STORAGE_IMPL.get(bucket, name)
  209. rn = RAGFlowExcelParser.row_number(doc["name"], file_bin)
  210. for i in range(0, rn, 3000):
  211. task = new_task()
  212. task["from_page"] = i
  213. task["to_page"] = min(i + 3000, rn)
  214. tsks.append(task)
  215. else:
  216. tsks.append(new_task())
  217. chunking_config = DocumentService.get_chunking_config(doc["id"])
  218. for task in tsks:
  219. hasher = xxhash.xxh64()
  220. for field in sorted(chunking_config.keys()):
  221. hasher.update(str(chunking_config[field]).encode("utf-8"))
  222. for field in ["doc_id", "from_page", "to_page"]:
  223. hasher.update(str(task.get(field, "")).encode("utf-8"))
  224. task_digest = hasher.hexdigest()
  225. task["digest"] = task_digest
  226. task["progress"] = 0.0
  227. prev_tasks = TaskService.get_tasks(doc["id"])
  228. if prev_tasks:
  229. ck_num = 0
  230. for task in tsks:
  231. ck_num += reuse_prev_task_chunks(task, prev_tasks, chunking_config)
  232. TaskService.filter_delete([Task.doc_id == doc["id"]])
  233. chunk_ids = []
  234. for task in prev_tasks:
  235. if task["chunk_ids"]:
  236. chunk_ids.extend(task["chunk_ids"].split())
  237. if chunk_ids:
  238. settings.docStoreConn.delete({"id": chunk_ids}, search.index_name(chunking_config["tenant_id"]), chunking_config["kb_id"])
  239. DocumentService.update_by_id(doc["id"], {"chunk_num": ck_num})
  240. bulk_insert_into_db(Task, tsks, True)
  241. DocumentService.begin2parse(doc["id"])
  242. tsks = [task for task in tsks if task["progress"] < 1.0]
  243. for t in tsks:
  244. assert REDIS_CONN.queue_product(
  245. SVR_QUEUE_NAME, message=t
  246. ), "Can't access Redis. Please check the Redis' status."
  247. def reuse_prev_task_chunks(task: dict, prev_tasks: list[dict], chunking_config: dict):
  248. idx = bisect.bisect_left(prev_tasks, task.get("from_page", 0), key=lambda x: x.get("from_page",0))
  249. if idx >= len(prev_tasks):
  250. return 0
  251. prev_task = prev_tasks[idx]
  252. if prev_task["progress"] < 1.0 or prev_task["digest"] != task["digest"] or not prev_task["chunk_ids"]:
  253. return 0
  254. task["chunk_ids"] = prev_task["chunk_ids"]
  255. task["progress"] = 1.0
  256. if "from_page" in task and "to_page" in task:
  257. task["progress_msg"] = f"Page({task['from_page']}~{task['to_page']}): "
  258. else:
  259. task["progress_msg"] = ""
  260. task["progress_msg"] += "reused previous task's chunks."
  261. prev_task["chunk_ids"] = ""
  262. return len(task["chunk_ids"].split())