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

document_service.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 random
  17. from datetime import datetime
  18. from elasticsearch_dsl import Q
  19. from peewee import fn
  20. from api.db.db_utils import bulk_insert_into_db
  21. from api.settings import stat_logger
  22. from api.utils import current_timestamp, get_format_time, get_uuid
  23. from rag.settings import SVR_QUEUE_NAME
  24. from rag.utils.es_conn import ELASTICSEARCH
  25. from rag.utils.minio_conn import MINIO
  26. from rag.nlp import search
  27. from api.db import FileType, TaskStatus
  28. from api.db.db_models import DB, Knowledgebase, Tenant, Task
  29. from api.db.db_models import Document
  30. from api.db.services.common_service import CommonService
  31. from api.db.services.knowledgebase_service import KnowledgebaseService
  32. from api.db import StatusEnum
  33. from rag.utils.redis_conn import REDIS_CONN
  34. class DocumentService(CommonService):
  35. model = Document
  36. @classmethod
  37. @DB.connection_context()
  38. def get_by_kb_id(cls, kb_id, page_number, items_per_page,
  39. orderby, desc, keywords):
  40. if keywords:
  41. docs = cls.model.select().where(
  42. (cls.model.kb_id == kb_id),
  43. (fn.LOWER(cls.model.name).contains(keywords.lower()))
  44. )
  45. else:
  46. docs = cls.model.select().where(cls.model.kb_id == kb_id)
  47. count = docs.count()
  48. if desc:
  49. docs = docs.order_by(cls.model.getter_by(orderby).desc())
  50. else:
  51. docs = docs.order_by(cls.model.getter_by(orderby).asc())
  52. docs = docs.paginate(page_number, items_per_page)
  53. return list(docs.dicts()), count
  54. @classmethod
  55. @DB.connection_context()
  56. def insert(cls, doc):
  57. if not cls.save(**doc):
  58. raise RuntimeError("Database error (Document)!")
  59. e, doc = cls.get_by_id(doc["id"])
  60. if not e:
  61. raise RuntimeError("Database error (Document retrieval)!")
  62. e, kb = KnowledgebaseService.get_by_id(doc.kb_id)
  63. if not KnowledgebaseService.update_by_id(
  64. kb.id, {"doc_num": kb.doc_num + 1}):
  65. raise RuntimeError("Database error (Knowledgebase)!")
  66. return doc
  67. @classmethod
  68. @DB.connection_context()
  69. def remove_document(cls, doc, tenant_id):
  70. ELASTICSEARCH.deleteByQuery(
  71. Q("match", doc_id=doc.id), idxnm=search.index_name(tenant_id))
  72. cls.clear_chunk_num(doc.id)
  73. return cls.delete_by_id(doc.id)
  74. @classmethod
  75. @DB.connection_context()
  76. def get_newly_uploaded(cls):
  77. fields = [
  78. cls.model.id,
  79. cls.model.kb_id,
  80. cls.model.parser_id,
  81. cls.model.parser_config,
  82. cls.model.name,
  83. cls.model.type,
  84. cls.model.location,
  85. cls.model.size,
  86. Knowledgebase.tenant_id,
  87. Tenant.embd_id,
  88. Tenant.img2txt_id,
  89. Tenant.asr_id,
  90. cls.model.update_time]
  91. docs = cls.model.select(*fields) \
  92. .join(Knowledgebase, on=(cls.model.kb_id == Knowledgebase.id)) \
  93. .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id))\
  94. .where(
  95. cls.model.status == StatusEnum.VALID.value,
  96. ~(cls.model.type == FileType.VIRTUAL.value),
  97. cls.model.progress == 0,
  98. cls.model.update_time >= current_timestamp() - 1000 * 600,
  99. cls.model.run == TaskStatus.RUNNING.value)\
  100. .order_by(cls.model.update_time.asc())
  101. return list(docs.dicts())
  102. @classmethod
  103. @DB.connection_context()
  104. def get_unfinished_docs(cls):
  105. fields = [cls.model.id, cls.model.process_begin_at, cls.model.parser_config, cls.model.progress_msg]
  106. docs = cls.model.select(*fields) \
  107. .where(
  108. cls.model.status == StatusEnum.VALID.value,
  109. ~(cls.model.type == FileType.VIRTUAL.value),
  110. cls.model.progress < 1,
  111. cls.model.progress > 0)
  112. return list(docs.dicts())
  113. @classmethod
  114. @DB.connection_context()
  115. def increment_chunk_num(cls, doc_id, kb_id, token_num, chunk_num, duation):
  116. num = cls.model.update(token_num=cls.model.token_num + token_num,
  117. chunk_num=cls.model.chunk_num + chunk_num,
  118. process_duation=cls.model.process_duation + duation).where(
  119. cls.model.id == doc_id).execute()
  120. if num == 0:
  121. raise LookupError(
  122. "Document not found which is supposed to be there")
  123. num = Knowledgebase.update(
  124. token_num=Knowledgebase.token_num +
  125. token_num,
  126. chunk_num=Knowledgebase.chunk_num +
  127. chunk_num).where(
  128. Knowledgebase.id == kb_id).execute()
  129. return num
  130. @classmethod
  131. @DB.connection_context()
  132. def clear_chunk_num(cls, doc_id):
  133. doc = cls.model.get_by_id(doc_id)
  134. assert doc, "Can't fine document in database."
  135. num = Knowledgebase.update(
  136. token_num=Knowledgebase.token_num -
  137. doc.token_num,
  138. chunk_num=Knowledgebase.chunk_num -
  139. doc.chunk_num,
  140. doc_num=Knowledgebase.doc_num-1
  141. ).where(
  142. Knowledgebase.id == doc.kb_id).execute()
  143. return num
  144. @classmethod
  145. @DB.connection_context()
  146. def get_tenant_id(cls, doc_id):
  147. docs = cls.model.select(
  148. Knowledgebase.tenant_id).join(
  149. Knowledgebase, on=(
  150. Knowledgebase.id == cls.model.kb_id)).where(
  151. cls.model.id == doc_id, Knowledgebase.status == StatusEnum.VALID.value)
  152. docs = docs.dicts()
  153. if not docs:
  154. return
  155. return docs[0]["tenant_id"]
  156. @classmethod
  157. @DB.connection_context()
  158. def get_tenant_id_by_name(cls, name):
  159. docs = cls.model.select(
  160. Knowledgebase.tenant_id).join(
  161. Knowledgebase, on=(
  162. Knowledgebase.id == cls.model.kb_id)).where(
  163. cls.model.name == name, Knowledgebase.status == StatusEnum.VALID.value)
  164. docs = docs.dicts()
  165. if not docs:
  166. return
  167. return docs[0]["tenant_id"]
  168. @classmethod
  169. @DB.connection_context()
  170. def get_doc_id_by_doc_name(cls, doc_name):
  171. fields = [cls.model.id]
  172. doc_id = cls.model.select(*fields) \
  173. .where(cls.model.name == doc_name)
  174. doc_id = doc_id.dicts()
  175. if not doc_id:
  176. return
  177. return doc_id[0]["id"]
  178. @classmethod
  179. @DB.connection_context()
  180. def get_thumbnails(cls, docids):
  181. fields = [cls.model.id, cls.model.thumbnail]
  182. return list(cls.model.select(
  183. *fields).where(cls.model.id.in_(docids)).dicts())
  184. @classmethod
  185. @DB.connection_context()
  186. def update_parser_config(cls, id, config):
  187. e, d = cls.get_by_id(id)
  188. if not e:
  189. raise LookupError(f"Document({id}) not found.")
  190. def dfs_update(old, new):
  191. for k, v in new.items():
  192. if k not in old:
  193. old[k] = v
  194. continue
  195. if isinstance(v, dict):
  196. assert isinstance(old[k], dict)
  197. dfs_update(old[k], v)
  198. else:
  199. old[k] = v
  200. dfs_update(d.parser_config, config)
  201. cls.update_by_id(id, {"parser_config": d.parser_config})
  202. @classmethod
  203. @DB.connection_context()
  204. def get_doc_count(cls, tenant_id):
  205. docs = cls.model.select(cls.model.id).join(Knowledgebase,
  206. on=(Knowledgebase.id == cls.model.kb_id)).where(
  207. Knowledgebase.tenant_id == tenant_id)
  208. return len(docs)
  209. @classmethod
  210. @DB.connection_context()
  211. def begin2parse(cls, docid):
  212. cls.update_by_id(
  213. docid, {"progress": random.random() * 1 / 100.,
  214. "progress_msg": "Task dispatched...",
  215. "process_begin_at": get_format_time()
  216. })
  217. @classmethod
  218. @DB.connection_context()
  219. def update_progress(cls):
  220. docs = cls.get_unfinished_docs()
  221. for d in docs:
  222. try:
  223. tsks = Task.query(doc_id=d["id"], order_by=Task.create_time)
  224. if not tsks:
  225. continue
  226. msg = []
  227. prg = 0
  228. finished = True
  229. bad = 0
  230. status = TaskStatus.RUNNING.value
  231. for t in tsks:
  232. if 0 <= t.progress < 1:
  233. finished = False
  234. prg += t.progress if t.progress >= 0 else 0
  235. msg.append(t.progress_msg)
  236. if t.progress == -1:
  237. bad += 1
  238. prg /= len(tsks)
  239. if finished and bad:
  240. prg = -1
  241. status = TaskStatus.FAIL.value
  242. elif finished:
  243. if d["parser_config"].get("raptor", {}).get("use_raptor") and d["progress_msg"].lower().find(" raptor")<0:
  244. queue_raptor_tasks(d)
  245. prg *= 0.98
  246. msg.append("------ RAPTOR -------")
  247. else:
  248. status = TaskStatus.DONE.value
  249. msg = "\n".join(msg)
  250. info = {
  251. "process_duation": datetime.timestamp(
  252. datetime.now()) -
  253. d["process_begin_at"].timestamp(),
  254. "run": status}
  255. if prg != 0:
  256. info["progress"] = prg
  257. if msg:
  258. info["progress_msg"] = msg
  259. cls.update_by_id(d["id"], info)
  260. except Exception as e:
  261. stat_logger.error("fetch task exception:" + str(e))
  262. @classmethod
  263. @DB.connection_context()
  264. def get_kb_doc_count(cls, kb_id):
  265. return len(cls.model.select(cls.model.id).where(
  266. cls.model.kb_id == kb_id).dicts())
  267. def queue_raptor_tasks(doc):
  268. def new_task():
  269. nonlocal doc
  270. return {
  271. "id": get_uuid(),
  272. "doc_id": doc["id"],
  273. "from_page": 0,
  274. "to_page": -1,
  275. "progress_msg": "Start to do RAPTOR (Recursive Abstractive Processing For Tree-Organized Retrieval)."
  276. }
  277. task = new_task()
  278. bulk_insert_into_db(Task, [task], True)
  279. task["type"] = "raptor"
  280. assert REDIS_CONN.queue_product(SVR_QUEUE_NAME, message=task), "Can't access Redis. Please check the Redis' status."