選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

task_broker.py 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. pages = PdfParser.total_page_number(r["name"], MINIO.get(r["kb_id"], r["location"]))
  76. page_size = 12
  77. if r["parser_id"] == "paper": page_size = 22
  78. if r["parser_id"] == "one": page_size = 1000000000
  79. for s,e in r["parser_config"].get("pages", [(0,100000)]):
  80. e = min(e, pages)
  81. for p in range(s, e, page_size):
  82. task = new_task()
  83. task["from_page"] = p
  84. task["to_page"] = min(p + page_size, e)
  85. tsks.append(task)
  86. elif r["parser_id"] == "table":
  87. rn = HuExcelParser.row_number(r["name"], MINIO.get(r["kb_id"], r["location"]))
  88. for i in range(0, rn, 3000):
  89. task = new_task()
  90. task["from_page"] = i
  91. task["to_page"] = min(i + 3000, rn)
  92. tsks.append(task)
  93. else:
  94. tsks.append(new_task())
  95. bulk_insert_into_db(Task, tsks, True)
  96. set_dispatching(r["id"])
  97. tmf.write(str(r["update_time"]) + "\n")
  98. tmf.close()
  99. def update_progress():
  100. docs = DocumentService.get_unfinished_docs()
  101. for d in docs:
  102. try:
  103. tsks = TaskService.query(doc_id=d["id"], order_by=Task.create_time)
  104. if not tsks:continue
  105. msg = []
  106. prg = 0
  107. finished = True
  108. bad = 0
  109. status = TaskStatus.RUNNING.value
  110. for t in tsks:
  111. if 0 <= t.progress < 1: finished = False
  112. prg += t.progress if t.progress >= 0 else 0
  113. msg.append(t.progress_msg)
  114. if t.progress == -1: bad += 1
  115. prg /= len(tsks)
  116. if finished and bad:
  117. prg = -1
  118. status = TaskStatus.FAIL.value
  119. elif finished: status = TaskStatus.DONE.value
  120. msg = "\n".join(msg)
  121. info = {"process_duation": datetime.timestamp(datetime.now())-d["process_begin_at"].timestamp(), "run": status}
  122. if prg !=0 : info["progress"] = prg
  123. if msg: info["progress_msg"] = msg
  124. DocumentService.update_by_id(d["id"], info)
  125. except Exception as e:
  126. cron_logger.error("fetch task exception:" + str(e))
  127. if __name__ == "__main__":
  128. peewee_logger = logging.getLogger('peewee')
  129. peewee_logger.propagate = False
  130. peewee_logger.addHandler(database_logger.handlers[0])
  131. peewee_logger.setLevel(database_logger.level)
  132. while True:
  133. dispatch()
  134. time.sleep(1)
  135. update_progress()