Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

document_service.py 9.7KB

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