您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

task_service.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. from api.db.db_utils import bulk_insert_into_db
  19. from deepdoc.parser import PdfParser
  20. from peewee import JOIN
  21. from api.db.db_models import DB, File2Document, File
  22. from api.db import StatusEnum, FileType, TaskStatus
  23. from api.db.db_models import Task, Document, Knowledgebase, Tenant
  24. from api.db.services.common_service import CommonService
  25. from api.db.services.document_service import DocumentService
  26. from api.utils import current_timestamp, get_uuid
  27. from deepdoc.parser.excel_parser import RAGFlowExcelParser
  28. from rag.settings import SVR_QUEUE_NAME
  29. from rag.utils.minio_conn import MINIO
  30. from rag.utils.redis_conn import REDIS_CONN
  31. class TaskService(CommonService):
  32. model = Task
  33. @classmethod
  34. @DB.connection_context()
  35. def get_tasks(cls, task_id):
  36. fields = [
  37. cls.model.id,
  38. cls.model.doc_id,
  39. cls.model.from_page,
  40. cls.model.to_page,
  41. Document.kb_id,
  42. Document.parser_id,
  43. Document.parser_config,
  44. Document.name,
  45. Document.type,
  46. Document.location,
  47. Document.size,
  48. Knowledgebase.tenant_id,
  49. Knowledgebase.language,
  50. Knowledgebase.embd_id,
  51. Tenant.img2txt_id,
  52. Tenant.asr_id,
  53. Tenant.llm_id,
  54. cls.model.update_time]
  55. docs = cls.model.select(*fields) \
  56. .join(Document, on=(cls.model.doc_id == Document.id)) \
  57. .join(Knowledgebase, on=(Document.kb_id == Knowledgebase.id)) \
  58. .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id)) \
  59. .where(cls.model.id == task_id)
  60. docs = list(docs.dicts())
  61. if not docs: return []
  62. msg = "\nTask has been received."
  63. prog = random.random() / 10.
  64. if docs[0]["retry_count"] >= 3:
  65. msg = "\nERROR: Task is abandoned after 3 times attempts."
  66. prog = -1
  67. cls.model.update(progress_msg=cls.model.progress_msg + msg,
  68. progress=prog,
  69. retry_count=docs[0]["retry_count"]+1
  70. ).where(
  71. cls.model.id == docs[0]["id"]).execute()
  72. if docs[0]["retry_count"] >= 3: return []
  73. return docs
  74. @classmethod
  75. @DB.connection_context()
  76. def get_ongoing_doc_name(cls):
  77. with DB.lock("get_task", -1):
  78. docs = cls.model.select(*[Document.id, Document.kb_id, Document.location, File.parent_id]) \
  79. .join(Document, on=(cls.model.doc_id == Document.id)) \
  80. .join(File2Document, on=(File2Document.document_id == Document.id), join_type=JOIN.LEFT_OUTER) \
  81. .join(File, on=(File2Document.file_id == File.id), join_type=JOIN.LEFT_OUTER) \
  82. .where(
  83. Document.status == StatusEnum.VALID.value,
  84. Document.run == TaskStatus.RUNNING.value,
  85. ~(Document.type == FileType.VIRTUAL.value),
  86. cls.model.progress < 1,
  87. cls.model.create_time >= current_timestamp() - 1000 * 600
  88. )
  89. docs = list(docs.dicts())
  90. if not docs: return []
  91. return list(set([(d["parent_id"] if d["parent_id"] else d["kb_id"], d["location"]) for d in docs]))
  92. @classmethod
  93. @DB.connection_context()
  94. def do_cancel(cls, id):
  95. try:
  96. task = cls.model.get_by_id(id)
  97. _, doc = DocumentService.get_by_id(task.doc_id)
  98. return doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  99. except Exception as e:
  100. pass
  101. return False
  102. @classmethod
  103. @DB.connection_context()
  104. def update_progress(cls, id, info):
  105. if os.environ.get("MACOS"):
  106. if info["progress_msg"]:
  107. cls.model.update(progress_msg=cls.model.progress_msg + "\n" + info["progress_msg"]).where(
  108. cls.model.id == id).execute()
  109. if "progress" in info:
  110. cls.model.update(progress=info["progress"]).where(
  111. cls.model.id == id).execute()
  112. return
  113. with DB.lock("update_progress", -1):
  114. if info["progress_msg"]:
  115. cls.model.update(progress_msg=cls.model.progress_msg + "\n" + info["progress_msg"]).where(
  116. cls.model.id == id).execute()
  117. if "progress" in info:
  118. cls.model.update(progress=info["progress"]).where(
  119. cls.model.id == id).execute()
  120. def queue_tasks(doc, bucket, name):
  121. def new_task():
  122. nonlocal doc
  123. return {
  124. "id": get_uuid(),
  125. "doc_id": doc["id"]
  126. }
  127. tsks = []
  128. if doc["type"] == FileType.PDF.value:
  129. file_bin = MINIO.get(bucket, name)
  130. do_layout = doc["parser_config"].get("layout_recognize", True)
  131. pages = PdfParser.total_page_number(doc["name"], file_bin)
  132. page_size = doc["parser_config"].get("task_page_size", 12)
  133. if doc["parser_id"] == "paper":
  134. page_size = doc["parser_config"].get("task_page_size", 22)
  135. if doc["parser_id"] == "one":
  136. page_size = 1000000000
  137. if doc["parser_id"] == "knowledge_graph":
  138. page_size = 1000000000
  139. if not do_layout:
  140. page_size = 1000000000
  141. page_ranges = doc["parser_config"].get("pages")
  142. if not page_ranges:
  143. page_ranges = [(1, 100000)]
  144. for s, e in page_ranges:
  145. s -= 1
  146. s = max(0, s)
  147. e = min(e - 1, pages)
  148. for p in range(s, e, page_size):
  149. task = new_task()
  150. task["from_page"] = p
  151. task["to_page"] = min(p + page_size, e)
  152. tsks.append(task)
  153. elif doc["parser_id"] == "table":
  154. file_bin = MINIO.get(bucket, name)
  155. rn = RAGFlowExcelParser.row_number(
  156. doc["name"], file_bin)
  157. for i in range(0, rn, 3000):
  158. task = new_task()
  159. task["from_page"] = i
  160. task["to_page"] = min(i + 3000, rn)
  161. tsks.append(task)
  162. else:
  163. tsks.append(new_task())
  164. bulk_insert_into_db(Task, tsks, True)
  165. DocumentService.begin2parse(doc["id"])
  166. for t in tsks:
  167. assert REDIS_CONN.queue_product(SVR_QUEUE_NAME, message=t), "Can't access Redis. Please check the Redis' status."