Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

document_service.py 26KB

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