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

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