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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 datetime
  17. import json
  18. import logging
  19. import os
  20. import hashlib
  21. import copy
  22. import re
  23. import sys
  24. from functools import partial
  25. from timeit import default_timer as timer
  26. from elasticsearch_dsl import Q
  27. from api.db.services.task_service import TaskService
  28. from rag.settings import cron_logger, DOC_MAXIMUM_SIZE
  29. from rag.utils import ELASTICSEARCH
  30. from rag.utils import MINIO
  31. from rag.utils import rmSpace, findMaxTm
  32. from rag.nlp import search
  33. from io import BytesIO
  34. import pandas as pd
  35. from rag.app import laws, paper, presentation, manual, qa, table, book, resume
  36. from api.db import LLMType, ParserType
  37. from api.db.services.document_service import DocumentService
  38. from api.db.services.llm_service import LLMBundle
  39. from api.settings import database_logger
  40. from api.utils.file_utils import get_project_base_directory
  41. BATCH_SIZE = 64
  42. FACTORY = {
  43. ParserType.GENERAL.value: laws,
  44. ParserType.PAPER.value: paper,
  45. ParserType.BOOK.value: book,
  46. ParserType.PRESENTATION.value: presentation,
  47. ParserType.MANUAL.value: manual,
  48. ParserType.LAWS.value: laws,
  49. ParserType.QA.value: qa,
  50. ParserType.TABLE.value: table,
  51. ParserType.RESUME.value: resume,
  52. }
  53. def set_progress(task_id, from_page=0, to_page=-1, prog=None, msg="Processing..."):
  54. cancel = TaskService.do_cancel(task_id)
  55. if cancel:
  56. msg += " [Canceled]"
  57. prog = -1
  58. if to_page > 0: msg = f"Page({from_page}~{to_page}): " + msg
  59. d = {"progress_msg": msg}
  60. if prog is not None: d["progress"] = prog
  61. try:
  62. TaskService.update_progress(task_id, d)
  63. except Exception as e:
  64. cron_logger.error("set_progress:({}), {}".format(task_id, str(e)))
  65. if cancel:sys.exit()
  66. """
  67. def chuck_doc(name, binary, tenant_id, cvmdl=None):
  68. suff = os.path.split(name)[-1].lower().split(".")[-1]
  69. if suff.find("pdf") >= 0:
  70. return PDF(binary)
  71. if suff.find("doc") >= 0:
  72. return DOC(binary)
  73. if re.match(r"(xlsx|xlsm|xltx|xltm)", suff):
  74. return EXC(binary)
  75. if suff.find("ppt") >= 0:
  76. return PPT(binary)
  77. if cvmdl and re.search(r"\.(jpg|jpeg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|avif|apng|icon|ico)$",
  78. name.lower()):
  79. txt = cvmdl.describe(binary)
  80. field = TextChunker.Fields()
  81. field.text_chunks = [(txt, binary)]
  82. field.table_chunks = []
  83. return field
  84. return TextChunker()(binary)
  85. """
  86. def collect(comm, mod, tm):
  87. tasks = TaskService.get_tasks(tm, mod, comm)
  88. if len(tasks) == 0:
  89. return pd.DataFrame()
  90. tasks = pd.DataFrame(tasks)
  91. mtm = tasks["update_time"].max()
  92. cron_logger.info("TOTAL:{}, To:{}".format(len(tasks), mtm))
  93. return tasks
  94. def build(row, cvmdl):
  95. if row["size"] > DOC_MAXIMUM_SIZE:
  96. set_progress(row["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  97. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  98. return []
  99. callback = partial(set_progress, row["id"], row["from_page"], row["to_page"])
  100. chunker = FACTORY[row["parser_id"].lower()]
  101. try:
  102. cron_logger.info("Chunkking {}/{}".format(row["location"], row["name"]))
  103. cks = chunker.chunk(row["name"], MINIO.get(row["kb_id"], row["location"]), row["from_page"], row["to_page"],
  104. callback, kb_id=row["kb_id"], parser_config=row["parser_config"])
  105. except Exception as e:
  106. if re.search("(No such file|not found)", str(e)):
  107. callback(-1, "Can not find file <%s>" % row["doc_name"])
  108. else:
  109. callback(-1, f"Internal server error: %s" % str(e).replace("'", ""))
  110. cron_logger.warn("Chunkking {}/{}: {}".format(row["location"], row["name"], str(e)))
  111. return []
  112. callback(msg="Finished slicing files. Start to embedding the content.")
  113. docs = []
  114. doc = {
  115. "doc_id": row["doc_id"],
  116. "kb_id": [str(row["kb_id"])]
  117. }
  118. for ck in cks:
  119. d = copy.deepcopy(doc)
  120. d.update(ck)
  121. md5 = hashlib.md5()
  122. md5.update((ck["content_with_weight"] + str(d["doc_id"])).encode("utf-8"))
  123. d["_id"] = md5.hexdigest()
  124. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  125. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  126. if not d.get("image"):
  127. docs.append(d)
  128. continue
  129. output_buffer = BytesIO()
  130. if isinstance(d["image"], bytes):
  131. output_buffer = BytesIO(d["image"])
  132. else:
  133. d["image"].save(output_buffer, format='JPEG')
  134. MINIO.put(row["kb_id"], d["_id"], output_buffer.getvalue())
  135. d["img_id"] = "{}-{}".format(row["kb_id"], d["_id"])
  136. del d["image"]
  137. docs.append(d)
  138. return docs
  139. def init_kb(row):
  140. idxnm = search.index_name(row["tenant_id"])
  141. if ELASTICSEARCH.indexExist(idxnm):
  142. return
  143. return ELASTICSEARCH.createIdx(idxnm, json.load(
  144. open(os.path.join(get_project_base_directory(), "conf", "mapping.json"), "r")))
  145. def embedding(docs, mdl, parser_config={}):
  146. tts, cnts = [rmSpace(d["title_tks"]) for d in docs if d.get("title_tks")], [d["content_with_weight"] for d in docs]
  147. tk_count = 0
  148. if len(tts) == len(cnts):
  149. tts, c = mdl.encode(tts)
  150. tk_count += c
  151. cnts, c = mdl.encode(cnts)
  152. tk_count += c
  153. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  154. vects = (title_w * tts + (1-title_w) * cnts) if len(tts) == len(cnts) else cnts
  155. assert len(vects) == len(docs)
  156. for i, d in enumerate(docs):
  157. v = vects[i].tolist()
  158. d["q_%d_vec" % len(v)] = v
  159. return tk_count
  160. def main(comm, mod):
  161. tm_fnm = os.path.join(get_project_base_directory(), "rag/res", f"{comm}-{mod}.tm")
  162. tm = findMaxTm(tm_fnm)
  163. rows = collect(comm, mod, tm)
  164. if len(rows) == 0:
  165. return
  166. tmf = open(tm_fnm, "a+")
  167. for _, r in rows.iterrows():
  168. callback = partial(set_progress, r["id"], r["from_page"], r["to_page"])
  169. try:
  170. embd_mdl = LLMBundle(r["tenant_id"], LLMType.EMBEDDING)
  171. cv_mdl = LLMBundle(r["tenant_id"], LLMType.IMAGE2TEXT)
  172. # TODO: sequence2text model
  173. except Exception as e:
  174. callback(prog=-1, msg=str(e))
  175. continue
  176. st_tm = timer()
  177. cks = build(r, cv_mdl)
  178. if not cks:
  179. tmf.write(str(r["update_time"]) + "\n")
  180. callback(1., "No chunk! Done!")
  181. continue
  182. # TODO: exception handler
  183. ## set_progress(r["did"], -1, "ERROR: ")
  184. try:
  185. tk_count = embedding(cks, embd_mdl, r["parser_config"])
  186. except Exception as e:
  187. callback(-1, "Embedding error:{}".format(str(e)))
  188. cron_logger.error(str(e))
  189. callback(msg="Finished embedding! Start to build index!")
  190. init_kb(r)
  191. chunk_count = len(set([c["_id"] for c in cks]))
  192. es_r = ELASTICSEARCH.bulk(cks, search.index_name(r["tenant_id"]))
  193. if es_r:
  194. callback(-1, "Index failure!")
  195. cron_logger.error(str(es_r))
  196. else:
  197. if TaskService.do_cancel(r["id"]):
  198. ELASTICSEARCH.deleteByQuery(Q("match", doc_id=r["doc_id"]), idxnm=search.index_name(r["tenant_id"]))
  199. continue
  200. callback(1., "Done!")
  201. DocumentService.increment_chunk_num(r["doc_id"], r["kb_id"], tk_count, chunk_count, 0)
  202. cron_logger.info("Chunk doc({}), token({}), chunks({})".format(r["id"], tk_count, len(cks)))
  203. tmf.write(str(r["update_time"]) + "\n")
  204. tmf.close()
  205. if __name__ == "__main__":
  206. peewee_logger = logging.getLogger('peewee')
  207. peewee_logger.propagate = False
  208. peewee_logger.addHandler(database_logger.handlers[0])
  209. peewee_logger.setLevel(database_logger.level)
  210. from mpi4py import MPI
  211. comm = MPI.COMM_WORLD
  212. main(comm.Get_size(), comm.Get_rank())