You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

task_broker.py 6.8KB

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