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 4.8KB

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