Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

task_service.py 6.1KB

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