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.6KB

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