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

document_service.py 29KB

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