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.

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