您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

document_service.py 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. import trio
  26. from peewee import fn
  27. from api.db.db_utils import bulk_insert_into_db
  28. from api import settings
  29. from api.utils import current_timestamp, get_format_time, get_uuid
  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_meta_fields(cls, doc_id, meta_fields):
  346. return cls.update_by_id(doc_id, {"meta_fields": meta_fields})
  347. @classmethod
  348. @DB.connection_context()
  349. def update_progress(cls):
  350. docs = cls.get_unfinished_docs()
  351. for d in docs:
  352. try:
  353. tsks = Task.query(doc_id=d["id"], order_by=Task.create_time)
  354. if not tsks:
  355. continue
  356. msg = []
  357. prg = 0
  358. finished = True
  359. bad = 0
  360. has_raptor = False
  361. has_graphrag = False
  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. if t.progress == -1:
  368. bad += 1
  369. prg += t.progress if t.progress >= 0 else 0
  370. msg.append(t.progress_msg)
  371. if t.task_type == "raptor":
  372. has_raptor = True
  373. elif t.task_type == "graphrag":
  374. has_graphrag = True
  375. prg /= len(tsks)
  376. if finished and bad:
  377. prg = -1
  378. status = TaskStatus.FAIL.value
  379. elif finished:
  380. if d["parser_config"].get("raptor", {}).get("use_raptor") and not has_raptor:
  381. queue_raptor_o_graphrag_tasks(d, "raptor")
  382. prg = 0.98 * len(tsks) / (len(tsks) + 1)
  383. elif d["parser_config"].get("graphrag", {}).get("use_graphrag") and not has_graphrag:
  384. queue_raptor_o_graphrag_tasks(d, "graphrag")
  385. prg = 0.98 * len(tsks) / (len(tsks) + 1)
  386. else:
  387. status = TaskStatus.DONE.value
  388. msg = "\n".join(sorted(msg))
  389. info = {
  390. "process_duation": datetime.timestamp(
  391. datetime.now()) -
  392. d["process_begin_at"].timestamp(),
  393. "run": status}
  394. if prg != 0:
  395. info["progress"] = prg
  396. if msg:
  397. info["progress_msg"] = msg
  398. cls.update_by_id(d["id"], info)
  399. except Exception as e:
  400. if str(e).find("'0'") < 0:
  401. logging.exception("fetch task exception")
  402. @classmethod
  403. @DB.connection_context()
  404. def get_kb_doc_count(cls, kb_id):
  405. return len(cls.model.select(cls.model.id).where(
  406. cls.model.kb_id == kb_id).dicts())
  407. @classmethod
  408. @DB.connection_context()
  409. def do_cancel(cls, doc_id):
  410. try:
  411. _, doc = DocumentService.get_by_id(doc_id)
  412. return doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  413. except Exception:
  414. pass
  415. return False
  416. def queue_raptor_o_graphrag_tasks(doc, ty):
  417. chunking_config = DocumentService.get_chunking_config(doc["id"])
  418. hasher = xxhash.xxh64()
  419. for field in sorted(chunking_config.keys()):
  420. hasher.update(str(chunking_config[field]).encode("utf-8"))
  421. def new_task():
  422. nonlocal doc
  423. return {
  424. "id": get_uuid(),
  425. "doc_id": doc["id"],
  426. "from_page": 100000000,
  427. "to_page": 100000000,
  428. "task_type": ty,
  429. "progress_msg": datetime.now().strftime("%H:%M:%S") + " created task " + ty
  430. }
  431. task = new_task()
  432. for field in ["doc_id", "from_page", "to_page"]:
  433. hasher.update(str(task.get(field, "")).encode("utf-8"))
  434. hasher.update(ty.encode("utf-8"))
  435. task["digest"] = hasher.hexdigest()
  436. bulk_insert_into_db(Task, [task], True)
  437. assert REDIS_CONN.queue_product(SVR_QUEUE_NAME, message=task), "Can't access Redis. Please check the Redis' status."
  438. def doc_upload_and_parse(conversation_id, file_objs, user_id):
  439. from rag.app import presentation, picture, naive, audio, email
  440. from api.db.services.dialog_service import DialogService
  441. from api.db.services.file_service import FileService
  442. from api.db.services.llm_service import LLMBundle
  443. from api.db.services.user_service import TenantService
  444. from api.db.services.api_service import API4ConversationService
  445. from api.db.services.conversation_service import ConversationService
  446. e, conv = ConversationService.get_by_id(conversation_id)
  447. if not e:
  448. e, conv = API4ConversationService.get_by_id(conversation_id)
  449. assert e, "Conversation not found!"
  450. e, dia = DialogService.get_by_id(conv.dialog_id)
  451. if not dia.kb_ids:
  452. raise LookupError("No knowledge base associated with this conversation. "
  453. "Please add a knowledge base before uploading documents")
  454. kb_id = dia.kb_ids[0]
  455. e, kb = KnowledgebaseService.get_by_id(kb_id)
  456. if not e:
  457. raise LookupError("Can't find this knowledgebase!")
  458. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING, llm_name=kb.embd_id, lang=kb.language)
  459. err, files = FileService.upload_document(kb, file_objs, user_id)
  460. assert not err, "\n".join(err)
  461. def dummy(prog=None, msg=""):
  462. pass
  463. FACTORY = {
  464. ParserType.PRESENTATION.value: presentation,
  465. ParserType.PICTURE.value: picture,
  466. ParserType.AUDIO.value: audio,
  467. ParserType.EMAIL.value: email
  468. }
  469. parser_config = {"chunk_token_num": 4096, "delimiter": "\n!?;。;!?", "layout_recognize": "Plain Text"}
  470. exe = ThreadPoolExecutor(max_workers=12)
  471. threads = []
  472. doc_nm = {}
  473. for d, blob in files:
  474. doc_nm[d["id"]] = d["name"]
  475. for d, blob in files:
  476. kwargs = {
  477. "callback": dummy,
  478. "parser_config": parser_config,
  479. "from_page": 0,
  480. "to_page": 100000,
  481. "tenant_id": kb.tenant_id,
  482. "lang": kb.language
  483. }
  484. threads.append(exe.submit(FACTORY.get(d["parser_id"], naive).chunk, d["name"], blob, **kwargs))
  485. for (docinfo, _), th in zip(files, threads):
  486. docs = []
  487. doc = {
  488. "doc_id": docinfo["id"],
  489. "kb_id": [kb.id]
  490. }
  491. for ck in th.result():
  492. d = deepcopy(doc)
  493. d.update(ck)
  494. d["id"] = xxhash.xxh64((ck["content_with_weight"] + str(d["doc_id"])).encode("utf-8")).hexdigest()
  495. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  496. d["create_timestamp_flt"] = datetime.now().timestamp()
  497. if not d.get("image"):
  498. docs.append(d)
  499. continue
  500. output_buffer = BytesIO()
  501. if isinstance(d["image"], bytes):
  502. output_buffer = BytesIO(d["image"])
  503. else:
  504. d["image"].save(output_buffer, format='JPEG')
  505. STORAGE_IMPL.put(kb.id, d["id"], output_buffer.getvalue())
  506. d["img_id"] = "{}-{}".format(kb.id, d["id"])
  507. d.pop("image", None)
  508. docs.append(d)
  509. parser_ids = {d["id"]: d["parser_id"] for d, _ in files}
  510. docids = [d["id"] for d, _ in files]
  511. chunk_counts = {id: 0 for id in docids}
  512. token_counts = {id: 0 for id in docids}
  513. es_bulk_size = 64
  514. def embedding(doc_id, cnts, batch_size=16):
  515. nonlocal embd_mdl, chunk_counts, token_counts
  516. vects = []
  517. for i in range(0, len(cnts), batch_size):
  518. vts, c = embd_mdl.encode(cnts[i: i + batch_size])
  519. vects.extend(vts.tolist())
  520. chunk_counts[doc_id] += len(cnts[i:i + batch_size])
  521. token_counts[doc_id] += c
  522. return vects
  523. idxnm = search.index_name(kb.tenant_id)
  524. try_create_idx = True
  525. _, tenant = TenantService.get_by_id(kb.tenant_id)
  526. llm_bdl = LLMBundle(kb.tenant_id, LLMType.CHAT, tenant.llm_id)
  527. for doc_id in docids:
  528. cks = [c for c in docs if c["doc_id"] == doc_id]
  529. if parser_ids[doc_id] != ParserType.PICTURE.value:
  530. from graphrag.general.mind_map_extractor import MindMapExtractor
  531. mindmap = MindMapExtractor(llm_bdl)
  532. try:
  533. mind_map = trio.run(mindmap, [c["content_with_weight"] for c in docs if c["doc_id"] == doc_id])
  534. mind_map = json.dumps(mind_map.output, ensure_ascii=False, indent=2)
  535. if len(mind_map) < 32:
  536. raise Exception("Few content: " + mind_map)
  537. cks.append({
  538. "id": get_uuid(),
  539. "doc_id": doc_id,
  540. "kb_id": [kb.id],
  541. "docnm_kwd": doc_nm[doc_id],
  542. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc_nm[doc_id])),
  543. "content_ltks": rag_tokenizer.tokenize("summary summarize 总结 概况 file 文件 概括"),
  544. "content_with_weight": mind_map,
  545. "knowledge_graph_kwd": "mind_map"
  546. })
  547. except Exception as e:
  548. logging.exception("Mind map generation error")
  549. vects = embedding(doc_id, [c["content_with_weight"] for c in cks])
  550. assert len(cks) == len(vects)
  551. for i, d in enumerate(cks):
  552. v = vects[i]
  553. d["q_%d_vec" % len(v)] = v
  554. for b in range(0, len(cks), es_bulk_size):
  555. if try_create_idx:
  556. if not settings.docStoreConn.indexExist(idxnm, kb_id):
  557. settings.docStoreConn.createIdx(idxnm, kb_id, len(vects[0]))
  558. try_create_idx = False
  559. settings.docStoreConn.insert(cks[b:b + es_bulk_size], idxnm, kb_id)
  560. DocumentService.increment_chunk_num(
  561. doc_id, kb.id, token_counts[doc_id], chunk_counts[doc_id], 0)
  562. return [d["id"] for d, _ in files]