Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

document_service.py 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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 xxhash
  18. import json
  19. import random
  20. import re
  21. from concurrent.futures import ThreadPoolExecutor
  22. from copy import deepcopy
  23. from datetime import datetime
  24. from io import BytesIO
  25. from peewee import fn
  26. from api.db.db_utils import bulk_insert_into_db
  27. from api import settings
  28. from api.utils import current_timestamp, get_format_time, get_uuid
  29. from graphrag.general.mind_map_extractor import MindMapExtractor
  30. from rag.settings import SVR_QUEUE_NAME
  31. from rag.utils.storage_factory import STORAGE_IMPL
  32. from rag.nlp import search, rag_tokenizer
  33. from api.db import FileType, TaskStatus, ParserType, LLMType
  34. from api.db.db_models import DB, Knowledgebase, Tenant, Task, UserTenant
  35. from api.db.db_models import Document
  36. from api.db.services.common_service import CommonService
  37. from api.db.services.knowledgebase_service import KnowledgebaseService
  38. from api.db import StatusEnum
  39. from rag.utils.redis_conn import REDIS_CONN
  40. class DocumentService(CommonService):
  41. model = Document
  42. @classmethod
  43. @DB.connection_context()
  44. def get_list(cls, kb_id, page_number, items_per_page,
  45. orderby, desc, keywords, id, name):
  46. docs = cls.model.select().where(cls.model.kb_id == kb_id)
  47. if id:
  48. docs = docs.where(
  49. cls.model.id == id)
  50. if name:
  51. docs = docs.where(
  52. cls.model.name == name
  53. )
  54. if keywords:
  55. docs = docs.where(
  56. fn.LOWER(cls.model.name).contains(keywords.lower())
  57. )
  58. if desc:
  59. docs = docs.order_by(cls.model.getter_by(orderby).desc())
  60. else:
  61. docs = docs.order_by(cls.model.getter_by(orderby).asc())
  62. count = docs.count()
  63. docs = docs.paginate(page_number, items_per_page)
  64. return list(docs.dicts()), count
  65. @classmethod
  66. @DB.connection_context()
  67. def get_by_kb_id(cls, kb_id, page_number, items_per_page,
  68. orderby, desc, keywords):
  69. if keywords:
  70. docs = cls.model.select().where(
  71. (cls.model.kb_id == kb_id),
  72. (fn.LOWER(cls.model.name).contains(keywords.lower()))
  73. )
  74. else:
  75. docs = cls.model.select().where(cls.model.kb_id == kb_id)
  76. count = docs.count()
  77. if desc:
  78. docs = docs.order_by(cls.model.getter_by(orderby).desc())
  79. else:
  80. docs = docs.order_by(cls.model.getter_by(orderby).asc())
  81. docs = docs.paginate(page_number, items_per_page)
  82. return list(docs.dicts()), count
  83. @classmethod
  84. @DB.connection_context()
  85. def insert(cls, doc):
  86. if not cls.save(**doc):
  87. raise RuntimeError("Database error (Document)!")
  88. e, kb = KnowledgebaseService.get_by_id(doc["kb_id"])
  89. if not KnowledgebaseService.update_by_id(
  90. kb.id, {"doc_num": kb.doc_num + 1}):
  91. raise RuntimeError("Database error (Knowledgebase)!")
  92. return Document(**doc)
  93. @classmethod
  94. @DB.connection_context()
  95. def remove_document(cls, doc, tenant_id):
  96. cls.clear_chunk_num(doc.id)
  97. try:
  98. settings.docStoreConn.delete({"doc_id": doc.id}, search.index_name(tenant_id), doc.kb_id)
  99. settings.docStoreConn.update({"kb_id": doc.kb_id, "knowledge_graph_kwd": ["entity", "relation", "graph", "community_report"], "source_id": doc.id},
  100. {"remove": {"source_id": doc.id}},
  101. search.index_name(tenant_id), doc.kb_id)
  102. settings.docStoreConn.update({"kb_id": doc.kb_id, "knowledge_graph_kwd": ["graph"]},
  103. {"removed_kwd": "Y"},
  104. search.index_name(tenant_id), doc.kb_id)
  105. settings.docStoreConn.delete({"kb_id": doc.kb_id, "knowledge_graph_kwd": ["entity", "relation", "graph", "community_report"], "must_not": {"exists": "source_id"}},
  106. search.index_name(tenant_id), doc.kb_id)
  107. except Exception:
  108. pass
  109. return cls.delete_by_id(doc.id)
  110. @classmethod
  111. @DB.connection_context()
  112. def get_newly_uploaded(cls):
  113. fields = [
  114. cls.model.id,
  115. cls.model.kb_id,
  116. cls.model.parser_id,
  117. cls.model.parser_config,
  118. cls.model.name,
  119. cls.model.type,
  120. cls.model.location,
  121. cls.model.size,
  122. Knowledgebase.tenant_id,
  123. Tenant.embd_id,
  124. Tenant.img2txt_id,
  125. Tenant.asr_id,
  126. cls.model.update_time]
  127. docs = cls.model.select(*fields) \
  128. .join(Knowledgebase, on=(cls.model.kb_id == Knowledgebase.id)) \
  129. .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id)) \
  130. .where(
  131. cls.model.status == StatusEnum.VALID.value,
  132. ~(cls.model.type == FileType.VIRTUAL.value),
  133. cls.model.progress == 0,
  134. cls.model.update_time >= current_timestamp() - 1000 * 600,
  135. cls.model.run == TaskStatus.RUNNING.value) \
  136. .order_by(cls.model.update_time.asc())
  137. return list(docs.dicts())
  138. @classmethod
  139. @DB.connection_context()
  140. def get_unfinished_docs(cls):
  141. fields = [cls.model.id, cls.model.process_begin_at, cls.model.parser_config, cls.model.progress_msg,
  142. cls.model.run, cls.model.parser_id]
  143. docs = cls.model.select(*fields) \
  144. .where(
  145. cls.model.status == StatusEnum.VALID.value,
  146. ~(cls.model.type == FileType.VIRTUAL.value),
  147. cls.model.progress < 1,
  148. cls.model.progress > 0)
  149. return list(docs.dicts())
  150. @classmethod
  151. @DB.connection_context()
  152. def increment_chunk_num(cls, doc_id, kb_id, token_num, chunk_num, duation):
  153. num = cls.model.update(token_num=cls.model.token_num + token_num,
  154. chunk_num=cls.model.chunk_num + chunk_num,
  155. process_duation=cls.model.process_duation + duation).where(
  156. cls.model.id == doc_id).execute()
  157. if num == 0:
  158. raise LookupError(
  159. "Document not found which is supposed to be there")
  160. num = Knowledgebase.update(
  161. token_num=Knowledgebase.token_num +
  162. token_num,
  163. chunk_num=Knowledgebase.chunk_num +
  164. chunk_num).where(
  165. Knowledgebase.id == kb_id).execute()
  166. return num
  167. @classmethod
  168. @DB.connection_context()
  169. def decrement_chunk_num(cls, doc_id, kb_id, token_num, chunk_num, duation):
  170. num = cls.model.update(token_num=cls.model.token_num - token_num,
  171. chunk_num=cls.model.chunk_num - chunk_num,
  172. process_duation=cls.model.process_duation + duation).where(
  173. cls.model.id == doc_id).execute()
  174. if num == 0:
  175. raise LookupError(
  176. "Document not found which is supposed to be there")
  177. num = Knowledgebase.update(
  178. token_num=Knowledgebase.token_num -
  179. token_num,
  180. chunk_num=Knowledgebase.chunk_num -
  181. chunk_num
  182. ).where(
  183. Knowledgebase.id == kb_id).execute()
  184. return num
  185. @classmethod
  186. @DB.connection_context()
  187. def clear_chunk_num(cls, doc_id):
  188. doc = cls.model.get_by_id(doc_id)
  189. assert doc, "Can't fine document in database."
  190. num = Knowledgebase.update(
  191. token_num=Knowledgebase.token_num -
  192. doc.token_num,
  193. chunk_num=Knowledgebase.chunk_num -
  194. doc.chunk_num,
  195. doc_num=Knowledgebase.doc_num - 1
  196. ).where(
  197. Knowledgebase.id == doc.kb_id).execute()
  198. return num
  199. @classmethod
  200. @DB.connection_context()
  201. def get_tenant_id(cls, doc_id):
  202. docs = cls.model.select(
  203. Knowledgebase.tenant_id).join(
  204. Knowledgebase, on=(
  205. Knowledgebase.id == cls.model.kb_id)).where(
  206. cls.model.id == doc_id, Knowledgebase.status == StatusEnum.VALID.value)
  207. docs = docs.dicts()
  208. if not docs:
  209. return
  210. return docs[0]["tenant_id"]
  211. @classmethod
  212. @DB.connection_context()
  213. def get_knowledgebase_id(cls, doc_id):
  214. docs = cls.model.select(cls.model.kb_id).where(cls.model.id == doc_id)
  215. docs = docs.dicts()
  216. if not docs:
  217. return
  218. return docs[0]["kb_id"]
  219. @classmethod
  220. @DB.connection_context()
  221. def get_tenant_id_by_name(cls, name):
  222. docs = cls.model.select(
  223. Knowledgebase.tenant_id).join(
  224. Knowledgebase, on=(
  225. Knowledgebase.id == cls.model.kb_id)).where(
  226. cls.model.name == name, Knowledgebase.status == StatusEnum.VALID.value)
  227. docs = docs.dicts()
  228. if not docs:
  229. return
  230. return docs[0]["tenant_id"]
  231. @classmethod
  232. @DB.connection_context()
  233. def accessible(cls, doc_id, user_id):
  234. docs = cls.model.select(
  235. cls.model.id).join(
  236. Knowledgebase, on=(
  237. Knowledgebase.id == cls.model.kb_id)
  238. ).join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  239. ).where(cls.model.id == doc_id, UserTenant.user_id == user_id).paginate(0, 1)
  240. docs = docs.dicts()
  241. if not docs:
  242. return False
  243. return True
  244. @classmethod
  245. @DB.connection_context()
  246. def accessible4deletion(cls, doc_id, user_id):
  247. docs = cls.model.select(
  248. cls.model.id).join(
  249. Knowledgebase, on=(
  250. Knowledgebase.id == cls.model.kb_id)
  251. ).where(cls.model.id == doc_id, Knowledgebase.created_by == user_id).paginate(0, 1)
  252. docs = docs.dicts()
  253. if not docs:
  254. return False
  255. return True
  256. @classmethod
  257. @DB.connection_context()
  258. def get_embd_id(cls, doc_id):
  259. docs = cls.model.select(
  260. Knowledgebase.embd_id).join(
  261. Knowledgebase, on=(
  262. Knowledgebase.id == cls.model.kb_id)).where(
  263. cls.model.id == doc_id, Knowledgebase.status == StatusEnum.VALID.value)
  264. docs = docs.dicts()
  265. if not docs:
  266. return
  267. return docs[0]["embd_id"]
  268. @classmethod
  269. @DB.connection_context()
  270. def get_chunking_config(cls, doc_id):
  271. configs = (
  272. cls.model.select(
  273. cls.model.id,
  274. cls.model.kb_id,
  275. cls.model.parser_id,
  276. cls.model.parser_config,
  277. Knowledgebase.language,
  278. Knowledgebase.embd_id,
  279. Tenant.id.alias("tenant_id"),
  280. Tenant.img2txt_id,
  281. Tenant.asr_id,
  282. Tenant.llm_id,
  283. )
  284. .join(Knowledgebase, on=(cls.model.kb_id == Knowledgebase.id))
  285. .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id))
  286. .where(cls.model.id == doc_id)
  287. )
  288. configs = configs.dicts()
  289. if not configs:
  290. return None
  291. return configs[0]
  292. @classmethod
  293. @DB.connection_context()
  294. def get_doc_id_by_doc_name(cls, doc_name):
  295. fields = [cls.model.id]
  296. doc_id = cls.model.select(*fields) \
  297. .where(cls.model.name == doc_name)
  298. doc_id = doc_id.dicts()
  299. if not doc_id:
  300. return
  301. return doc_id[0]["id"]
  302. @classmethod
  303. @DB.connection_context()
  304. def get_thumbnails(cls, docids):
  305. fields = [cls.model.id, cls.model.kb_id, cls.model.thumbnail]
  306. return list(cls.model.select(
  307. *fields).where(cls.model.id.in_(docids)).dicts())
  308. @classmethod
  309. @DB.connection_context()
  310. def update_parser_config(cls, id, config):
  311. e, d = cls.get_by_id(id)
  312. if not e:
  313. raise LookupError(f"Document({id}) not found.")
  314. def dfs_update(old, new):
  315. for k, v in new.items():
  316. if k not in old:
  317. old[k] = v
  318. continue
  319. if isinstance(v, dict):
  320. assert isinstance(old[k], dict)
  321. dfs_update(old[k], v)
  322. else:
  323. old[k] = v
  324. dfs_update(d.parser_config, config)
  325. if not config.get("raptor") and d.parser_config.get("raptor"):
  326. del d.parser_config["raptor"]
  327. cls.update_by_id(id, {"parser_config": d.parser_config})
  328. @classmethod
  329. @DB.connection_context()
  330. def get_doc_count(cls, tenant_id):
  331. docs = cls.model.select(cls.model.id).join(Knowledgebase,
  332. on=(Knowledgebase.id == cls.model.kb_id)).where(
  333. Knowledgebase.tenant_id == tenant_id)
  334. return len(docs)
  335. @classmethod
  336. @DB.connection_context()
  337. def begin2parse(cls, docid):
  338. cls.update_by_id(
  339. docid, {"progress": random.random() * 1 / 100.,
  340. "progress_msg": "Task is queued...",
  341. "process_begin_at": get_format_time()
  342. })
  343. @classmethod
  344. @DB.connection_context()
  345. def update_progress(cls):
  346. MSG = {
  347. "raptor": "Start RAPTOR (Recursive Abstractive Processing for Tree-Organized Retrieval).",
  348. "graphrag": "Start Graph Extraction",
  349. "graph_resolution": "Start Graph Resolution",
  350. "graph_community": "Start Graph Community Reports Generation"
  351. }
  352. docs = cls.get_unfinished_docs()
  353. for d in docs:
  354. try:
  355. tsks = Task.query(doc_id=d["id"], order_by=Task.create_time)
  356. if not tsks:
  357. continue
  358. msg = []
  359. prg = 0
  360. finished = True
  361. bad = 0
  362. e, doc = DocumentService.get_by_id(d["id"])
  363. status = doc.run # TaskStatus.RUNNING.value
  364. for t in tsks:
  365. if 0 <= t.progress < 1:
  366. finished = False
  367. prg += t.progress if t.progress >= 0 else 0
  368. if t.progress_msg not in msg:
  369. msg.append(t.progress_msg)
  370. if t.progress == -1:
  371. bad += 1
  372. prg /= len(tsks)
  373. if finished and bad:
  374. prg = -1
  375. status = TaskStatus.FAIL.value
  376. elif finished:
  377. m = "\n".join(sorted(msg))
  378. if d["parser_config"].get("raptor", {}).get("use_raptor") and m.find(MSG["raptor"]) < 0:
  379. queue_raptor_o_graphrag_tasks(d, "raptor", MSG["raptor"])
  380. prg = 0.98 * len(tsks) / (len(tsks) + 1)
  381. elif d["parser_config"].get("graphrag", {}).get("use_graphrag") and m.find(MSG["graphrag"]) < 0:
  382. queue_raptor_o_graphrag_tasks(d, "graphrag", MSG["graphrag"])
  383. prg = 0.98 * len(tsks) / (len(tsks) + 1)
  384. elif d["parser_config"].get("graphrag", {}).get("use_graphrag") \
  385. and d["parser_config"].get("graphrag", {}).get("resolution") \
  386. and m.find(MSG["graph_resolution"]) < 0:
  387. queue_raptor_o_graphrag_tasks(d, "graph_resolution", MSG["graph_resolution"])
  388. prg = 0.98 * len(tsks) / (len(tsks) + 1)
  389. elif d["parser_config"].get("graphrag", {}).get("use_graphrag") \
  390. and d["parser_config"].get("graphrag", {}).get("community") \
  391. and m.find(MSG["graph_community"]) < 0:
  392. queue_raptor_o_graphrag_tasks(d, "graph_community", MSG["graph_community"])
  393. prg = 0.98 * len(tsks) / (len(tsks) + 1)
  394. else:
  395. status = TaskStatus.DONE.value
  396. msg = "\n".join(sorted(msg))
  397. info = {
  398. "process_duation": datetime.timestamp(
  399. datetime.now()) -
  400. d["process_begin_at"].timestamp(),
  401. "run": status}
  402. if prg != 0:
  403. info["progress"] = prg
  404. if msg:
  405. info["progress_msg"] = msg
  406. cls.update_by_id(d["id"], info)
  407. except Exception as e:
  408. if str(e).find("'0'") < 0:
  409. logging.exception("fetch task exception")
  410. @classmethod
  411. @DB.connection_context()
  412. def get_kb_doc_count(cls, kb_id):
  413. return len(cls.model.select(cls.model.id).where(
  414. cls.model.kb_id == kb_id).dicts())
  415. @classmethod
  416. @DB.connection_context()
  417. def do_cancel(cls, doc_id):
  418. try:
  419. _, doc = DocumentService.get_by_id(doc_id)
  420. return doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  421. except Exception:
  422. pass
  423. return False
  424. def queue_raptor_o_graphrag_tasks(doc, ty, msg):
  425. chunking_config = DocumentService.get_chunking_config(doc["id"])
  426. hasher = xxhash.xxh64()
  427. for field in sorted(chunking_config.keys()):
  428. hasher.update(str(chunking_config[field]).encode("utf-8"))
  429. def new_task():
  430. nonlocal doc
  431. return {
  432. "id": get_uuid(),
  433. "doc_id": doc["id"],
  434. "from_page": 100000000,
  435. "to_page": 100000000,
  436. "progress_msg": datetime.now().strftime("%H:%M:%S") + " " + msg
  437. }
  438. task = new_task()
  439. for field in ["doc_id", "from_page", "to_page"]:
  440. hasher.update(str(task.get(field, "")).encode("utf-8"))
  441. hasher.update(ty.encode("utf-8"))
  442. task["digest"] = hasher.hexdigest()
  443. bulk_insert_into_db(Task, [task], True)
  444. task["task_type"] = ty
  445. assert REDIS_CONN.queue_product(SVR_QUEUE_NAME, message=task), "Can't access Redis. Please check the Redis' status."
  446. def doc_upload_and_parse(conversation_id, file_objs, user_id):
  447. from rag.app import presentation, picture, naive, audio, email
  448. from api.db.services.dialog_service import DialogService
  449. from api.db.services.file_service import FileService
  450. from api.db.services.llm_service import LLMBundle
  451. from api.db.services.user_service import TenantService
  452. from api.db.services.api_service import API4ConversationService
  453. from api.db.services.conversation_service import ConversationService
  454. e, conv = ConversationService.get_by_id(conversation_id)
  455. if not e:
  456. e, conv = API4ConversationService.get_by_id(conversation_id)
  457. assert e, "Conversation not found!"
  458. e, dia = DialogService.get_by_id(conv.dialog_id)
  459. kb_id = dia.kb_ids[0]
  460. e, kb = KnowledgebaseService.get_by_id(kb_id)
  461. if not e:
  462. raise LookupError("Can't find this knowledgebase!")
  463. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING, llm_name=kb.embd_id, lang=kb.language)
  464. err, files = FileService.upload_document(kb, file_objs, user_id)
  465. assert not err, "\n".join(err)
  466. def dummy(prog=None, msg=""):
  467. pass
  468. FACTORY = {
  469. ParserType.PRESENTATION.value: presentation,
  470. ParserType.PICTURE.value: picture,
  471. ParserType.AUDIO.value: audio,
  472. ParserType.EMAIL.value: email
  473. }
  474. parser_config = {"chunk_token_num": 4096, "delimiter": "\n!?;。;!?", "layout_recognize": "Plain Text"}
  475. exe = ThreadPoolExecutor(max_workers=12)
  476. threads = []
  477. doc_nm = {}
  478. for d, blob in files:
  479. doc_nm[d["id"]] = d["name"]
  480. for d, blob in files:
  481. kwargs = {
  482. "callback": dummy,
  483. "parser_config": parser_config,
  484. "from_page": 0,
  485. "to_page": 100000,
  486. "tenant_id": kb.tenant_id,
  487. "lang": kb.language
  488. }
  489. threads.append(exe.submit(FACTORY.get(d["parser_id"], naive).chunk, d["name"], blob, **kwargs))
  490. for (docinfo, _), th in zip(files, threads):
  491. docs = []
  492. doc = {
  493. "doc_id": docinfo["id"],
  494. "kb_id": [kb.id]
  495. }
  496. for ck in th.result():
  497. d = deepcopy(doc)
  498. d.update(ck)
  499. d["id"] = xxhash.xxh64((ck["content_with_weight"] + str(d["doc_id"])).encode("utf-8")).hexdigest()
  500. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  501. d["create_timestamp_flt"] = datetime.now().timestamp()
  502. if not d.get("image"):
  503. docs.append(d)
  504. continue
  505. output_buffer = BytesIO()
  506. if isinstance(d["image"], bytes):
  507. output_buffer = BytesIO(d["image"])
  508. else:
  509. d["image"].save(output_buffer, format='JPEG')
  510. STORAGE_IMPL.put(kb.id, d["id"], output_buffer.getvalue())
  511. d["img_id"] = "{}-{}".format(kb.id, d["id"])
  512. d.pop("image", None)
  513. docs.append(d)
  514. parser_ids = {d["id"]: d["parser_id"] for d, _ in files}
  515. docids = [d["id"] for d, _ in files]
  516. chunk_counts = {id: 0 for id in docids}
  517. token_counts = {id: 0 for id in docids}
  518. es_bulk_size = 64
  519. def embedding(doc_id, cnts, batch_size=16):
  520. nonlocal embd_mdl, chunk_counts, token_counts
  521. vects = []
  522. for i in range(0, len(cnts), batch_size):
  523. vts, c = embd_mdl.encode(cnts[i: i + batch_size])
  524. vects.extend(vts.tolist())
  525. chunk_counts[doc_id] += len(cnts[i:i + batch_size])
  526. token_counts[doc_id] += c
  527. return vects
  528. idxnm = search.index_name(kb.tenant_id)
  529. try_create_idx = True
  530. _, tenant = TenantService.get_by_id(kb.tenant_id)
  531. llm_bdl = LLMBundle(kb.tenant_id, LLMType.CHAT, tenant.llm_id)
  532. for doc_id in docids:
  533. cks = [c for c in docs if c["doc_id"] == doc_id]
  534. if parser_ids[doc_id] != ParserType.PICTURE.value:
  535. mindmap = MindMapExtractor(llm_bdl)
  536. try:
  537. mind_map = json.dumps(mindmap([c["content_with_weight"] for c in docs if c["doc_id"] == doc_id]).output,
  538. ensure_ascii=False, indent=2)
  539. if len(mind_map) < 32:
  540. raise Exception("Few content: " + mind_map)
  541. cks.append({
  542. "id": get_uuid(),
  543. "doc_id": doc_id,
  544. "kb_id": [kb.id],
  545. "docnm_kwd": doc_nm[doc_id],
  546. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc_nm[doc_id])),
  547. "content_ltks": rag_tokenizer.tokenize("summary summarize 总结 概况 file 文件 概括"),
  548. "content_with_weight": mind_map,
  549. "knowledge_graph_kwd": "mind_map"
  550. })
  551. except Exception as e:
  552. logging.exception("Mind map generation error")
  553. vects = embedding(doc_id, [c["content_with_weight"] for c in cks])
  554. assert len(cks) == len(vects)
  555. for i, d in enumerate(cks):
  556. v = vects[i]
  557. d["q_%d_vec" % len(v)] = v
  558. for b in range(0, len(cks), es_bulk_size):
  559. if try_create_idx:
  560. if not settings.docStoreConn.indexExist(idxnm, kb_id):
  561. settings.docStoreConn.createIdx(idxnm, kb_id, len(vects[0]))
  562. try_create_idx = False
  563. settings.docStoreConn.insert(cks[b:b + es_bulk_size], idxnm, kb_id)
  564. DocumentService.increment_chunk_num(
  565. doc_id, kb.id, token_counts[doc_id], chunk_counts[doc_id], 0)
  566. return [d["id"] for d, _ in files]