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.

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