Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

document_service.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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, SVR_CONSUMER_GROUP_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, duration):
  207. num = cls.model.update(token_num=cls.model.token_num + token_num,
  208. chunk_num=cls.model.chunk_num + chunk_num,
  209. process_duration=cls.model.process_duration + duration).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, duration):
  224. num = cls.model.update(token_num=cls.model.token_num - token_num,
  225. chunk_num=cls.model.chunk_num - chunk_num,
  226. process_duration=cls.model.process_duration + duration).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 clear_chunk_num_when_rerun(cls, doc_id):
  256. doc = cls.model.get_by_id(doc_id)
  257. assert doc, "Can't fine document in database."
  258. num = (
  259. Knowledgebase.update(
  260. token_num=Knowledgebase.token_num - doc.token_num,
  261. chunk_num=Knowledgebase.chunk_num - doc.chunk_num,
  262. )
  263. .where(Knowledgebase.id == doc.kb_id)
  264. .execute()
  265. )
  266. return num
  267. @classmethod
  268. @DB.connection_context()
  269. def get_tenant_id(cls, doc_id):
  270. docs = cls.model.select(
  271. Knowledgebase.tenant_id).join(
  272. Knowledgebase, on=(
  273. Knowledgebase.id == cls.model.kb_id)).where(
  274. cls.model.id == doc_id, Knowledgebase.status == StatusEnum.VALID.value)
  275. docs = docs.dicts()
  276. if not docs:
  277. return
  278. return docs[0]["tenant_id"]
  279. @classmethod
  280. @DB.connection_context()
  281. def get_knowledgebase_id(cls, doc_id):
  282. docs = cls.model.select(cls.model.kb_id).where(cls.model.id == doc_id)
  283. docs = docs.dicts()
  284. if not docs:
  285. return
  286. return docs[0]["kb_id"]
  287. @classmethod
  288. @DB.connection_context()
  289. def get_tenant_id_by_name(cls, name):
  290. docs = cls.model.select(
  291. Knowledgebase.tenant_id).join(
  292. Knowledgebase, on=(
  293. Knowledgebase.id == cls.model.kb_id)).where(
  294. cls.model.name == name, Knowledgebase.status == StatusEnum.VALID.value)
  295. docs = docs.dicts()
  296. if not docs:
  297. return
  298. return docs[0]["tenant_id"]
  299. @classmethod
  300. @DB.connection_context()
  301. def accessible(cls, doc_id, user_id):
  302. docs = cls.model.select(
  303. cls.model.id).join(
  304. Knowledgebase, on=(
  305. Knowledgebase.id == cls.model.kb_id)
  306. ).join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  307. ).where(cls.model.id == doc_id, UserTenant.user_id == user_id).paginate(0, 1)
  308. docs = docs.dicts()
  309. if not docs:
  310. return False
  311. return True
  312. @classmethod
  313. @DB.connection_context()
  314. def accessible4deletion(cls, doc_id, user_id):
  315. docs = cls.model.select(cls.model.id
  316. ).join(
  317. Knowledgebase, on=(
  318. Knowledgebase.id == cls.model.kb_id)
  319. ).join(
  320. UserTenant, on=(
  321. (UserTenant.tenant_id == Knowledgebase.created_by) & (UserTenant.user_id == user_id))
  322. ).where(
  323. cls.model.id == doc_id,
  324. UserTenant.status == StatusEnum.VALID.value,
  325. ((UserTenant.role == UserTenantRole.NORMAL) | (UserTenant.role == UserTenantRole.OWNER))
  326. ).paginate(0, 1)
  327. docs = docs.dicts()
  328. if not docs:
  329. return False
  330. return True
  331. @classmethod
  332. @DB.connection_context()
  333. def get_embd_id(cls, doc_id):
  334. docs = cls.model.select(
  335. Knowledgebase.embd_id).join(
  336. Knowledgebase, on=(
  337. Knowledgebase.id == cls.model.kb_id)).where(
  338. cls.model.id == doc_id, Knowledgebase.status == StatusEnum.VALID.value)
  339. docs = docs.dicts()
  340. if not docs:
  341. return
  342. return docs[0]["embd_id"]
  343. @classmethod
  344. @DB.connection_context()
  345. def get_chunking_config(cls, doc_id):
  346. configs = (
  347. cls.model.select(
  348. cls.model.id,
  349. cls.model.kb_id,
  350. cls.model.parser_id,
  351. cls.model.parser_config,
  352. Knowledgebase.language,
  353. Knowledgebase.embd_id,
  354. Tenant.id.alias("tenant_id"),
  355. Tenant.img2txt_id,
  356. Tenant.asr_id,
  357. Tenant.llm_id,
  358. )
  359. .join(Knowledgebase, on=(cls.model.kb_id == Knowledgebase.id))
  360. .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id))
  361. .where(cls.model.id == doc_id)
  362. )
  363. configs = configs.dicts()
  364. if not configs:
  365. return None
  366. return configs[0]
  367. @classmethod
  368. @DB.connection_context()
  369. def get_doc_id_by_doc_name(cls, doc_name):
  370. fields = [cls.model.id]
  371. doc_id = cls.model.select(*fields) \
  372. .where(cls.model.name == doc_name)
  373. doc_id = doc_id.dicts()
  374. if not doc_id:
  375. return
  376. return doc_id[0]["id"]
  377. @classmethod
  378. @DB.connection_context()
  379. def get_doc_ids_by_doc_names(cls, doc_names):
  380. if not doc_names:
  381. return []
  382. query = cls.model.select(cls.model.id).where(cls.model.name.in_(doc_names))
  383. return list(query.scalars().iterator())
  384. @classmethod
  385. @DB.connection_context()
  386. def get_thumbnails(cls, docids):
  387. fields = [cls.model.id, cls.model.kb_id, cls.model.thumbnail]
  388. return list(cls.model.select(
  389. *fields).where(cls.model.id.in_(docids)).dicts())
  390. @classmethod
  391. @DB.connection_context()
  392. def update_parser_config(cls, id, config):
  393. if not config:
  394. return
  395. e, d = cls.get_by_id(id)
  396. if not e:
  397. raise LookupError(f"Document({id}) not found.")
  398. def dfs_update(old, new):
  399. for k, v in new.items():
  400. if k not in old:
  401. old[k] = v
  402. continue
  403. if isinstance(v, dict):
  404. assert isinstance(old[k], dict)
  405. dfs_update(old[k], v)
  406. else:
  407. old[k] = v
  408. dfs_update(d.parser_config, config)
  409. if not config.get("raptor") and d.parser_config.get("raptor"):
  410. del d.parser_config["raptor"]
  411. cls.update_by_id(id, {"parser_config": d.parser_config})
  412. @classmethod
  413. @DB.connection_context()
  414. def get_doc_count(cls, tenant_id):
  415. docs = cls.model.select(cls.model.id).join(Knowledgebase,
  416. on=(Knowledgebase.id == cls.model.kb_id)).where(
  417. Knowledgebase.tenant_id == tenant_id)
  418. return len(docs)
  419. @classmethod
  420. @DB.connection_context()
  421. def begin2parse(cls, docid):
  422. cls.update_by_id(
  423. docid, {"progress": random.random() * 1 / 100.,
  424. "progress_msg": "Task is queued...",
  425. "process_begin_at": get_format_time()
  426. })
  427. @classmethod
  428. @DB.connection_context()
  429. def update_meta_fields(cls, doc_id, meta_fields):
  430. return cls.update_by_id(doc_id, {"meta_fields": meta_fields})
  431. @classmethod
  432. @DB.connection_context()
  433. def update_progress(cls):
  434. docs = cls.get_unfinished_docs()
  435. for d in docs:
  436. try:
  437. tsks = Task.query(doc_id=d["id"], order_by=Task.create_time)
  438. if not tsks:
  439. continue
  440. msg = []
  441. prg = 0
  442. finished = True
  443. bad = 0
  444. has_raptor = False
  445. has_graphrag = False
  446. e, doc = DocumentService.get_by_id(d["id"])
  447. status = doc.run # TaskStatus.RUNNING.value
  448. priority = 0
  449. for t in tsks:
  450. if 0 <= t.progress < 1:
  451. finished = False
  452. if t.progress == -1:
  453. bad += 1
  454. prg += t.progress if t.progress >= 0 else 0
  455. if t.progress_msg.strip():
  456. msg.append(t.progress_msg)
  457. if t.task_type == "raptor":
  458. has_raptor = True
  459. elif t.task_type == "graphrag":
  460. has_graphrag = True
  461. priority = max(priority, t.priority)
  462. prg /= len(tsks)
  463. if finished and bad:
  464. prg = -1
  465. status = TaskStatus.FAIL.value
  466. elif finished:
  467. if d["parser_config"].get("raptor", {}).get("use_raptor") and not has_raptor:
  468. queue_raptor_o_graphrag_tasks(d, "raptor", priority)
  469. prg = 0.98 * len(tsks) / (len(tsks) + 1)
  470. elif d["parser_config"].get("graphrag", {}).get("use_graphrag") and not has_graphrag:
  471. queue_raptor_o_graphrag_tasks(d, "graphrag", priority)
  472. prg = 0.98 * len(tsks) / (len(tsks) + 1)
  473. else:
  474. status = TaskStatus.DONE.value
  475. msg = "\n".join(sorted(msg))
  476. info = {
  477. "process_duration": datetime.timestamp(
  478. datetime.now()) -
  479. d["process_begin_at"].timestamp(),
  480. "run": status}
  481. if prg != 0:
  482. info["progress"] = prg
  483. if msg:
  484. info["progress_msg"] = msg
  485. else:
  486. info["progress_msg"] = "%d tasks are ahead in the queue..."%get_queue_length(priority)
  487. cls.update_by_id(d["id"], info)
  488. except Exception as e:
  489. if str(e).find("'0'") < 0:
  490. logging.exception("fetch task exception")
  491. @classmethod
  492. @DB.connection_context()
  493. def get_kb_doc_count(cls, kb_id):
  494. return len(cls.model.select(cls.model.id).where(
  495. cls.model.kb_id == kb_id).dicts())
  496. @classmethod
  497. @DB.connection_context()
  498. def do_cancel(cls, doc_id):
  499. try:
  500. _, doc = DocumentService.get_by_id(doc_id)
  501. return doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  502. except Exception:
  503. pass
  504. return False
  505. def queue_raptor_o_graphrag_tasks(doc, ty, priority):
  506. chunking_config = DocumentService.get_chunking_config(doc["id"])
  507. hasher = xxhash.xxh64()
  508. for field in sorted(chunking_config.keys()):
  509. hasher.update(str(chunking_config[field]).encode("utf-8"))
  510. def new_task():
  511. nonlocal doc
  512. return {
  513. "id": get_uuid(),
  514. "doc_id": doc["id"],
  515. "from_page": 100000000,
  516. "to_page": 100000000,
  517. "task_type": ty,
  518. "progress_msg": datetime.now().strftime("%H:%M:%S") + " created task " + ty
  519. }
  520. task = new_task()
  521. for field in ["doc_id", "from_page", "to_page"]:
  522. hasher.update(str(task.get(field, "")).encode("utf-8"))
  523. hasher.update(ty.encode("utf-8"))
  524. task["digest"] = hasher.hexdigest()
  525. bulk_insert_into_db(Task, [task], True)
  526. assert REDIS_CONN.queue_product(get_svr_queue_name(priority), message=task), "Can't access Redis. Please check the Redis' status."
  527. def get_queue_length(priority):
  528. group_info = REDIS_CONN.queue_info(get_svr_queue_name(priority), SVR_CONSUMER_GROUP_NAME)
  529. return int(group_info.get("lag", 0))
  530. def doc_upload_and_parse(conversation_id, file_objs, user_id):
  531. from api.db.services.api_service import API4ConversationService
  532. from api.db.services.conversation_service import ConversationService
  533. from api.db.services.dialog_service import DialogService
  534. from api.db.services.file_service import FileService
  535. from api.db.services.llm_service import LLMBundle
  536. from api.db.services.user_service import TenantService
  537. from rag.app import audio, email, naive, picture, presentation
  538. e, conv = ConversationService.get_by_id(conversation_id)
  539. if not e:
  540. e, conv = API4ConversationService.get_by_id(conversation_id)
  541. assert e, "Conversation not found!"
  542. e, dia = DialogService.get_by_id(conv.dialog_id)
  543. if not dia.kb_ids:
  544. raise LookupError("No knowledge base associated with this conversation. "
  545. "Please add a knowledge base before uploading documents")
  546. kb_id = dia.kb_ids[0]
  547. e, kb = KnowledgebaseService.get_by_id(kb_id)
  548. if not e:
  549. raise LookupError("Can't find this knowledgebase!")
  550. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING, llm_name=kb.embd_id, lang=kb.language)
  551. err, files = FileService.upload_document(kb, file_objs, user_id)
  552. assert not err, "\n".join(err)
  553. def dummy(prog=None, msg=""):
  554. pass
  555. FACTORY = {
  556. ParserType.PRESENTATION.value: presentation,
  557. ParserType.PICTURE.value: picture,
  558. ParserType.AUDIO.value: audio,
  559. ParserType.EMAIL.value: email
  560. }
  561. parser_config = {"chunk_token_num": 4096, "delimiter": "\n!?;。;!?", "layout_recognize": "Plain Text"}
  562. exe = ThreadPoolExecutor(max_workers=12)
  563. threads = []
  564. doc_nm = {}
  565. for d, blob in files:
  566. doc_nm[d["id"]] = d["name"]
  567. for d, blob in files:
  568. kwargs = {
  569. "callback": dummy,
  570. "parser_config": parser_config,
  571. "from_page": 0,
  572. "to_page": 100000,
  573. "tenant_id": kb.tenant_id,
  574. "lang": kb.language
  575. }
  576. threads.append(exe.submit(FACTORY.get(d["parser_id"], naive).chunk, d["name"], blob, **kwargs))
  577. for (docinfo, _), th in zip(files, threads):
  578. docs = []
  579. doc = {
  580. "doc_id": docinfo["id"],
  581. "kb_id": [kb.id]
  582. }
  583. for ck in th.result():
  584. d = deepcopy(doc)
  585. d.update(ck)
  586. d["id"] = xxhash.xxh64((ck["content_with_weight"] + str(d["doc_id"])).encode("utf-8")).hexdigest()
  587. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  588. d["create_timestamp_flt"] = datetime.now().timestamp()
  589. if not d.get("image"):
  590. docs.append(d)
  591. continue
  592. output_buffer = BytesIO()
  593. if isinstance(d["image"], bytes):
  594. output_buffer = BytesIO(d["image"])
  595. else:
  596. d["image"].save(output_buffer, format='JPEG')
  597. STORAGE_IMPL.put(kb.id, d["id"], output_buffer.getvalue())
  598. d["img_id"] = "{}-{}".format(kb.id, d["id"])
  599. d.pop("image", None)
  600. docs.append(d)
  601. parser_ids = {d["id"]: d["parser_id"] for d, _ in files}
  602. docids = [d["id"] for d, _ in files]
  603. chunk_counts = {id: 0 for id in docids}
  604. token_counts = {id: 0 for id in docids}
  605. es_bulk_size = 64
  606. def embedding(doc_id, cnts, batch_size=16):
  607. nonlocal embd_mdl, chunk_counts, token_counts
  608. vects = []
  609. for i in range(0, len(cnts), batch_size):
  610. vts, c = embd_mdl.encode(cnts[i: i + batch_size])
  611. vects.extend(vts.tolist())
  612. chunk_counts[doc_id] += len(cnts[i:i + batch_size])
  613. token_counts[doc_id] += c
  614. return vects
  615. idxnm = search.index_name(kb.tenant_id)
  616. try_create_idx = True
  617. _, tenant = TenantService.get_by_id(kb.tenant_id)
  618. llm_bdl = LLMBundle(kb.tenant_id, LLMType.CHAT, tenant.llm_id)
  619. for doc_id in docids:
  620. cks = [c for c in docs if c["doc_id"] == doc_id]
  621. if parser_ids[doc_id] != ParserType.PICTURE.value:
  622. from graphrag.general.mind_map_extractor import MindMapExtractor
  623. mindmap = MindMapExtractor(llm_bdl)
  624. try:
  625. mind_map = trio.run(mindmap, [c["content_with_weight"] for c in docs if c["doc_id"] == doc_id])
  626. mind_map = json.dumps(mind_map.output, ensure_ascii=False, indent=2)
  627. if len(mind_map) < 32:
  628. raise Exception("Few content: " + mind_map)
  629. cks.append({
  630. "id": get_uuid(),
  631. "doc_id": doc_id,
  632. "kb_id": [kb.id],
  633. "docnm_kwd": doc_nm[doc_id],
  634. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc_nm[doc_id])),
  635. "content_ltks": rag_tokenizer.tokenize("summary summarize 总结 概况 file 文件 概括"),
  636. "content_with_weight": mind_map,
  637. "knowledge_graph_kwd": "mind_map"
  638. })
  639. except Exception as e:
  640. logging.exception("Mind map generation error")
  641. vects = embedding(doc_id, [c["content_with_weight"] for c in cks])
  642. assert len(cks) == len(vects)
  643. for i, d in enumerate(cks):
  644. v = vects[i]
  645. d["q_%d_vec" % len(v)] = v
  646. for b in range(0, len(cks), es_bulk_size):
  647. if try_create_idx:
  648. if not settings.docStoreConn.indexExist(idxnm, kb_id):
  649. settings.docStoreConn.createIdx(idxnm, kb_id, len(vects[0]))
  650. try_create_idx = False
  651. settings.docStoreConn.insert(cks[b:b + es_bulk_size], idxnm, kb_id)
  652. DocumentService.increment_chunk_num(
  653. doc_id, kb.id, token_counts[doc_id], chunk_counts[doc_id], 0)
  654. return [d["id"] for d, _ in files]