Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

task_broker.py 5.1KB

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