Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 time
  23. import random
  24. import re
  25. from timeit import default_timer as timer
  26. from rag.llm import EmbeddingModel, CvModel
  27. from rag.settings import cron_logger, DOC_MAXIMUM_SIZE
  28. from rag.utils import ELASTICSEARCH
  29. from rag.utils import MINIO
  30. from rag.utils import rmSpace, findMaxTm
  31. from rag.nlp import huchunk, huqie, search
  32. from io import BytesIO
  33. import pandas as pd
  34. from elasticsearch_dsl import Q
  35. from PIL import Image
  36. from rag.parser import (
  37. PdfParser,
  38. DocxParser,
  39. ExcelParser
  40. )
  41. from rag.nlp.huchunk import (
  42. PdfChunker,
  43. DocxChunker,
  44. ExcelChunker,
  45. PptChunker,
  46. TextChunker
  47. )
  48. from api.db import LLMType
  49. from api.db.services.document_service import DocumentService
  50. from api.db.services.llm_service import TenantLLMService
  51. from api.settings import database_logger
  52. from api.utils import get_format_time
  53. from api.utils.file_utils import get_project_base_directory
  54. BATCH_SIZE = 64
  55. PDF = PdfChunker(PdfParser())
  56. DOC = DocxChunker(DocxParser())
  57. EXC = ExcelChunker(ExcelParser())
  58. PPT = PptChunker()
  59. def chuck_doc(name, binary, cvmdl=None):
  60. suff = os.path.split(name)[-1].lower().split(".")[-1]
  61. if suff.find("pdf") >= 0:
  62. return PDF(binary)
  63. if suff.find("doc") >= 0:
  64. return DOC(binary)
  65. if re.match(r"(xlsx|xlsm|xltx|xltm)", suff):
  66. return EXC(binary)
  67. if suff.find("ppt") >= 0:
  68. return PPT(binary)
  69. 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)$",
  70. name.lower()):
  71. txt = cvmdl.describe(binary)
  72. field = TextChunker.Fields()
  73. field.text_chunks = [(txt, binary)]
  74. field.table_chunks = []
  75. return field
  76. return TextChunker()(binary)
  77. def collect(comm, mod, tm):
  78. docs = DocumentService.get_newly_uploaded(tm, mod, comm)
  79. if len(docs) == 0:
  80. return pd.DataFrame()
  81. docs = pd.DataFrame(docs)
  82. mtm = docs["update_time"].max()
  83. cron_logger.info("TOTAL:{}, To:{}".format(len(docs), mtm))
  84. return docs
  85. def set_progress(docid, prog, msg="Processing...", begin=False):
  86. d = {"progress": prog, "progress_msg": msg}
  87. if begin:
  88. d["process_begin_at"] = get_format_time()
  89. try:
  90. DocumentService.update_by_id(
  91. docid, {"progress": prog, "progress_msg": msg})
  92. except Exception as e:
  93. cron_logger.error("set_progress:({}), {}".format(docid, str(e)))
  94. def build(row, cvmdl):
  95. if row["size"] > DOC_MAXIMUM_SIZE:
  96. set_progress(row["id"], -1, "File size exceeds( <= %dMb )" %
  97. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  98. return []
  99. # res = ELASTICSEARCH.search(Q("term", doc_id=row["id"]))
  100. # if ELASTICSEARCH.getTotal(res) > 0:
  101. # ELASTICSEARCH.updateScriptByQuery(Q("term", doc_id=row["id"]),
  102. # scripts="""
  103. # if(!ctx._source.kb_id.contains('%s'))
  104. # ctx._source.kb_id.add('%s');
  105. # """ % (str(row["kb_id"]), str(row["kb_id"])),
  106. # idxnm=search.index_name(row["tenant_id"])
  107. # )
  108. # set_progress(row["id"], 1, "Done")
  109. # return []
  110. random.seed(time.time())
  111. set_progress(row["id"], random.randint(0, 20) /
  112. 100., "Finished preparing! Start to slice file!", True)
  113. try:
  114. cron_logger.info("Chunkking {}/{}".format(row["location"], row["name"]))
  115. obj = chuck_doc(row["name"], MINIO.get(row["kb_id"], row["location"]), cvmdl)
  116. except Exception as e:
  117. if re.search("(No such file|not found)", str(e)):
  118. set_progress(
  119. row["id"], -1, "Can not find file <%s>" %
  120. row["doc_name"])
  121. else:
  122. set_progress(
  123. row["id"], -1, f"Internal server error: %s" %
  124. str(e).replace(
  125. "'", ""))
  126. cron_logger.warn("Chunkking {}/{}: {}".format(row["location"], row["name"], str(e)))
  127. return []
  128. if not obj.text_chunks and not obj.table_chunks:
  129. set_progress(
  130. row["id"],
  131. 1,
  132. "Nothing added! Mostly, file type unsupported yet.")
  133. return []
  134. set_progress(row["id"], random.randint(20, 60) / 100.,
  135. "Finished slicing files. Start to embedding the content.")
  136. doc = {
  137. "doc_id": row["id"],
  138. "kb_id": [str(row["kb_id"])],
  139. "docnm_kwd": os.path.split(row["location"])[-1],
  140. "title_tks": huqie.qie(row["name"])
  141. }
  142. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  143. output_buffer = BytesIO()
  144. docs = []
  145. for txt, img in obj.text_chunks:
  146. d = copy.deepcopy(doc)
  147. md5 = hashlib.md5()
  148. md5.update((txt + str(d["doc_id"])).encode("utf-8"))
  149. d["_id"] = md5.hexdigest()
  150. d["content_ltks"] = huqie.qie(txt)
  151. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  152. if not img:
  153. docs.append(d)
  154. continue
  155. if isinstance(img, bytes):
  156. output_buffer = BytesIO(img)
  157. else:
  158. img.save(output_buffer, format='JPEG')
  159. MINIO.put(row["kb_id"], d["_id"], output_buffer.getvalue())
  160. d["img_id"] = "{}-{}".format(row["kb_id"], d["_id"])
  161. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  162. docs.append(d)
  163. for arr, img in obj.table_chunks:
  164. for i, txt in enumerate(arr):
  165. d = copy.deepcopy(doc)
  166. d["content_ltks"] = huqie.qie(txt)
  167. md5 = hashlib.md5()
  168. md5.update((txt + str(d["doc_id"])).encode("utf-8"))
  169. d["_id"] = md5.hexdigest()
  170. if not img:
  171. docs.append(d)
  172. continue
  173. img.save(output_buffer, format='JPEG')
  174. MINIO.put(row["kb_id"], d["_id"], output_buffer.getvalue())
  175. d["img_id"] = "{}-{}".format(row["kb_id"], d["_id"])
  176. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  177. docs.append(d)
  178. set_progress(row["id"], random.randint(60, 70) /
  179. 100., "Continue embedding the content.")
  180. return docs
  181. def init_kb(row):
  182. idxnm = search.index_name(row["tenant_id"])
  183. if ELASTICSEARCH.indexExist(idxnm):
  184. return
  185. return ELASTICSEARCH.createIdx(idxnm, json.load(
  186. open(os.path.join(get_project_base_directory(), "conf", "mapping.json"), "r")))
  187. def embedding(docs, mdl):
  188. tts, cnts = [rmSpace(d["title_tks"]) for d in docs], [rmSpace(d["content_ltks"]) for d in docs]
  189. tk_count = 0
  190. tts, c = mdl.encode(tts)
  191. tk_count += c
  192. cnts, c = mdl.encode(cnts)
  193. tk_count += c
  194. vects = 0.1 * tts + 0.9 * cnts
  195. assert len(vects) == len(docs)
  196. for i, d in enumerate(docs):
  197. v = vects[i].tolist()
  198. d["q_%d_vec"%len(v)] = v
  199. return tk_count
  200. def main(comm, mod):
  201. tm_fnm = os.path.join(get_project_base_directory(), "rag/res", f"{comm}-{mod}.tm")
  202. tm = findMaxTm(tm_fnm)
  203. rows = collect(comm, mod, tm)
  204. if len(rows) == 0:
  205. return
  206. tmf = open(tm_fnm, "a+")
  207. for _, r in rows.iterrows():
  208. embd_mdl = TenantLLMService.model_instance(r["tenant_id"], LLMType.EMBEDDING)
  209. if not embd_mdl:
  210. set_progress(r["id"], -1, "Can't find embedding model!")
  211. cron_logger.error("Tenant({}) can't find embedding model!".format(r["tenant_id"]))
  212. continue
  213. cv_mdl = TenantLLMService.model_instance(r["tenant_id"], LLMType.IMAGE2TEXT)
  214. st_tm = timer()
  215. cks = build(r, cv_mdl)
  216. if not cks:
  217. tmf.write(str(r["update_time"]) + "\n")
  218. continue
  219. # TODO: exception handler
  220. ## set_progress(r["did"], -1, "ERROR: ")
  221. try:
  222. tk_count = embedding(cks, embd_mdl)
  223. except Exception as e:
  224. set_progress(r["id"], -1, "Embedding error:{}".format(str(e)))
  225. cron_logger.error(str(e))
  226. continue
  227. set_progress(r["id"], random.randint(70, 95) / 100.,
  228. "Finished embedding! Start to build index!")
  229. init_kb(r)
  230. chunk_count = len(set([c["_id"] for c in cks]))
  231. es_r = ELASTICSEARCH.bulk(cks, search.index_name(r["tenant_id"]))
  232. if es_r:
  233. set_progress(r["id"], -1, "Index failure!")
  234. cron_logger.error(str(es_r))
  235. else:
  236. set_progress(r["id"], 1., "Done!")
  237. DocumentService.increment_chunk_num(r["id"], r["kb_id"], tk_count, chunk_count, timer()-st_tm)
  238. cron_logger.info("Chunk doc({}), token({}), chunks({})".format(r["id"], tk_count, len(cks)))
  239. tmf.write(str(r["update_time"]) + "\n")
  240. tmf.close()
  241. if __name__ == "__main__":
  242. peewee_logger = logging.getLogger('peewee')
  243. peewee_logger.propagate = False
  244. peewee_logger.addHandler(database_logger.handlers[0])
  245. peewee_logger.setLevel(database_logger.level)
  246. from mpi4py import MPI
  247. comm = MPI.COMM_WORLD
  248. main(comm.Get_size(), comm.Get_rank())