Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. cls.model.update(progress_msg=cls.model.progress_msg + "\n" + "Task has been received.",
  63. progress=random.random() / 10.).where(
  64. cls.model.id == docs[0]["id"]).execute()
  65. return docs
  66. @classmethod
  67. @DB.connection_context()
  68. def get_ongoing_doc_name(cls):
  69. with DB.lock("get_task", -1):
  70. docs = cls.model.select(*[Document.id, Document.kb_id, Document.location, File.parent_id]) \
  71. .join(Document, on=(cls.model.doc_id == Document.id)) \
  72. .join(File2Document, on=(File2Document.document_id == Document.id), join_type=JOIN.LEFT_OUTER) \
  73. .join(File, on=(File2Document.file_id == File.id), join_type=JOIN.LEFT_OUTER) \
  74. .where(
  75. Document.status == StatusEnum.VALID.value,
  76. Document.run == TaskStatus.RUNNING.value,
  77. ~(Document.type == FileType.VIRTUAL.value),
  78. cls.model.progress < 1,
  79. cls.model.create_time >= current_timestamp() - 1000 * 600
  80. )
  81. docs = list(docs.dicts())
  82. if not docs: return []
  83. return list(set([(d["parent_id"] if d["parent_id"] else d["kb_id"], d["location"]) for d in docs]))
  84. @classmethod
  85. @DB.connection_context()
  86. def do_cancel(cls, id):
  87. try:
  88. task = cls.model.get_by_id(id)
  89. _, doc = DocumentService.get_by_id(task.doc_id)
  90. return doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  91. except Exception as e:
  92. pass
  93. return False
  94. @classmethod
  95. @DB.connection_context()
  96. def update_progress(cls, id, info):
  97. if os.environ.get("MACOS"):
  98. if info["progress_msg"]:
  99. cls.model.update(progress_msg=cls.model.progress_msg + "\n" + info["progress_msg"]).where(
  100. cls.model.id == id).execute()
  101. if "progress" in info:
  102. cls.model.update(progress=info["progress"]).where(
  103. cls.model.id == id).execute()
  104. return
  105. with DB.lock("update_progress", -1):
  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. def queue_tasks(doc, bucket, name):
  113. def new_task():
  114. nonlocal doc
  115. return {
  116. "id": get_uuid(),
  117. "doc_id": doc["id"]
  118. }
  119. tsks = []
  120. if doc["type"] == FileType.PDF.value:
  121. file_bin = MINIO.get(bucket, name)
  122. do_layout = doc["parser_config"].get("layout_recognize", True)
  123. pages = PdfParser.total_page_number(doc["name"], file_bin)
  124. page_size = doc["parser_config"].get("task_page_size", 12)
  125. if doc["parser_id"] == "paper":
  126. page_size = doc["parser_config"].get("task_page_size", 22)
  127. if doc["parser_id"] == "one":
  128. page_size = 1000000000
  129. if doc["parser_id"] == "knowledge_graph":
  130. page_size = 1000000000
  131. if not do_layout:
  132. page_size = 1000000000
  133. page_ranges = doc["parser_config"].get("pages")
  134. if not page_ranges:
  135. page_ranges = [(1, 100000)]
  136. for s, e in page_ranges:
  137. s -= 1
  138. s = max(0, s)
  139. e = min(e - 1, pages)
  140. for p in range(s, e, page_size):
  141. task = new_task()
  142. task["from_page"] = p
  143. task["to_page"] = min(p + page_size, e)
  144. tsks.append(task)
  145. elif doc["parser_id"] == "table":
  146. file_bin = MINIO.get(bucket, name)
  147. rn = RAGFlowExcelParser.row_number(
  148. doc["name"], file_bin)
  149. for i in range(0, rn, 3000):
  150. task = new_task()
  151. task["from_page"] = i
  152. task["to_page"] = min(i + 3000, rn)
  153. tsks.append(task)
  154. else:
  155. tsks.append(new_task())
  156. bulk_insert_into_db(Task, tsks, True)
  157. DocumentService.begin2parse(doc["id"])
  158. for t in tsks:
  159. assert REDIS_CONN.queue_product(SVR_QUEUE_NAME, message=t), "Can't access Redis. Please check the Redis' status."