Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

task_broker.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 logging
  17. import os
  18. import time
  19. import random
  20. from datetime import datetime
  21. from api.db.db_models import Task
  22. from api.db.db_utils import bulk_insert_into_db
  23. from api.db.services.file2document_service import File2DocumentService
  24. from api.db.services.task_service import TaskService
  25. from deepdoc.parser import PdfParser
  26. from deepdoc.parser.excel_parser import RAGFlowExcelParser
  27. from rag.settings import cron_logger
  28. from rag.utils.minio_conn import MINIO
  29. from rag.utils import findMaxTm
  30. import pandas as pd
  31. from api.db import FileType, TaskStatus
  32. from api.db.services.document_service import DocumentService
  33. from api.settings import database_logger
  34. from api.utils import get_format_time, get_uuid
  35. from api.utils.file_utils import get_project_base_directory
  36. from rag.utils.redis_conn import REDIS_CONN
  37. from api.db.db_models import init_database_tables as init_web_db
  38. from api.db.init_data import init_web_data
  39. def collect(tm):
  40. docs = DocumentService.get_newly_uploaded(tm)
  41. if len(docs) == 0:
  42. return pd.DataFrame()
  43. docs = pd.DataFrame(docs)
  44. mtm = docs["update_time"].max()
  45. cron_logger.info("TOTAL:{}, To:{}".format(len(docs), mtm))
  46. return docs
  47. def set_dispatching(docid):
  48. try:
  49. DocumentService.update_by_id(
  50. docid, {"progress": random.random() * 1 / 100.,
  51. "progress_msg": "Task dispatched...",
  52. "process_begin_at": get_format_time()
  53. })
  54. except Exception as e:
  55. cron_logger.error("set_dispatching:({}), {}".format(docid, str(e)))
  56. def dispatch():
  57. tm_fnm = os.path.join(
  58. get_project_base_directory(),
  59. "rag/res",
  60. f"broker.tm")
  61. tm = findMaxTm(tm_fnm)
  62. rows = collect(tm)
  63. if len(rows) == 0:
  64. return
  65. tmf = open(tm_fnm, "a+")
  66. for _, r in rows.iterrows():
  67. try:
  68. tsks = TaskService.query(doc_id=r["id"])
  69. if tsks:
  70. for t in tsks:
  71. TaskService.delete_by_id(t.id)
  72. except Exception as e:
  73. cron_logger.exception(e)
  74. def new_task():
  75. nonlocal r
  76. return {
  77. "id": get_uuid(),
  78. "doc_id": r["id"]
  79. }
  80. tsks = []
  81. try:
  82. bucket, name = File2DocumentService.get_minio_address(doc_id=r["id"])
  83. file_bin = MINIO.get(bucket, name)
  84. if REDIS_CONN.is_alive():
  85. try:
  86. REDIS_CONN.set("{}/{}".format(bucket, name), file_bin, 12*60)
  87. except Exception as e:
  88. cron_logger.warning("Put into redis[EXCEPTION]:" + str(e))
  89. if r["type"] == FileType.PDF.value:
  90. do_layout = r["parser_config"].get("layout_recognize", True)
  91. pages = PdfParser.total_page_number(r["name"], file_bin)
  92. page_size = r["parser_config"].get("task_page_size", 12)
  93. if r["parser_id"] == "paper":
  94. page_size = r["parser_config"].get("task_page_size", 22)
  95. if r["parser_id"] == "one":
  96. page_size = 1000000000
  97. if not do_layout:
  98. page_size = 1000000000
  99. page_ranges = r["parser_config"].get("pages")
  100. if not page_ranges:
  101. page_ranges = [(1, 100000)]
  102. for s, e in page_ranges:
  103. s -= 1
  104. s = max(0, s)
  105. e = min(e - 1, pages)
  106. for p in range(s, e, page_size):
  107. task = new_task()
  108. task["from_page"] = p
  109. task["to_page"] = min(p + page_size, e)
  110. tsks.append(task)
  111. elif r["parser_id"] == "table":
  112. rn = RAGFlowExcelParser.row_number(
  113. r["name"], file_bin)
  114. for i in range(0, rn, 3000):
  115. task = new_task()
  116. task["from_page"] = i
  117. task["to_page"] = min(i + 3000, rn)
  118. tsks.append(task)
  119. else:
  120. tsks.append(new_task())
  121. bulk_insert_into_db(Task, tsks, True)
  122. set_dispatching(r["id"])
  123. except Exception as e:
  124. cron_logger.exception(e)
  125. tmf.write(str(r["update_time"]) + "\n")
  126. tmf.close()
  127. def update_progress():
  128. docs = DocumentService.get_unfinished_docs()
  129. for d in docs:
  130. try:
  131. tsks = TaskService.query(doc_id=d["id"], order_by=Task.create_time)
  132. if not tsks:
  133. continue
  134. msg = []
  135. prg = 0
  136. finished = True
  137. bad = 0
  138. status = TaskStatus.RUNNING.value
  139. for t in tsks:
  140. if 0 <= t.progress < 1:
  141. finished = False
  142. prg += t.progress if t.progress >= 0 else 0
  143. msg.append(t.progress_msg)
  144. if t.progress == -1:
  145. bad += 1
  146. prg /= len(tsks)
  147. if finished and bad:
  148. prg = -1
  149. status = TaskStatus.FAIL.value
  150. elif finished:
  151. status = TaskStatus.DONE.value
  152. msg = "\n".join(msg)
  153. info = {
  154. "process_duation": datetime.timestamp(
  155. datetime.now()) -
  156. d["process_begin_at"].timestamp(),
  157. "run": status}
  158. if prg != 0:
  159. info["progress"] = prg
  160. if msg:
  161. info["progress_msg"] = msg
  162. DocumentService.update_by_id(d["id"], info)
  163. except Exception as e:
  164. cron_logger.error("fetch task exception:" + str(e))
  165. if __name__ == "__main__":
  166. peewee_logger = logging.getLogger('peewee')
  167. peewee_logger.propagate = False
  168. peewee_logger.addHandler(database_logger.handlers[0])
  169. peewee_logger.setLevel(database_logger.level)
  170. # init db
  171. init_web_db()
  172. init_web_data()
  173. while True:
  174. dispatch()
  175. time.sleep(1)
  176. update_progress()