Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

document_service.py 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. from peewee import Expression
  17. from elasticsearch_dsl import Q
  18. from rag.utils.es_conn import ELASTICSEARCH
  19. from rag.utils.minio_conn import MINIO
  20. from rag.nlp import search
  21. from api.db import FileType, TaskStatus
  22. from api.db.db_models import DB, Knowledgebase, Tenant
  23. from api.db.db_models import Document
  24. from api.db.services.common_service import CommonService
  25. from api.db.services.knowledgebase_service import KnowledgebaseService
  26. from api.db import StatusEnum
  27. class DocumentService(CommonService):
  28. model = Document
  29. @classmethod
  30. @DB.connection_context()
  31. def get_by_kb_id(cls, kb_id, page_number, items_per_page,
  32. orderby, desc, keywords):
  33. if keywords:
  34. docs = cls.model.select().where(
  35. cls.model.kb_id == kb_id,
  36. cls.model.name.like(f"%%{keywords}%%"))
  37. else:
  38. docs = cls.model.select().where(cls.model.kb_id == kb_id)
  39. count = docs.count()
  40. if desc:
  41. docs = docs.order_by(cls.model.getter_by(orderby).desc())
  42. else:
  43. docs = docs.order_by(cls.model.getter_by(orderby).asc())
  44. docs = docs.paginate(page_number, items_per_page)
  45. return list(docs.dicts()), count
  46. @classmethod
  47. @DB.connection_context()
  48. def insert(cls, doc):
  49. if not cls.save(**doc):
  50. raise RuntimeError("Database error (Document)!")
  51. e, doc = cls.get_by_id(doc["id"])
  52. if not e:
  53. raise RuntimeError("Database error (Document retrieval)!")
  54. e, kb = KnowledgebaseService.get_by_id(doc.kb_id)
  55. if not KnowledgebaseService.update_by_id(
  56. kb.id, {"doc_num": kb.doc_num + 1}):
  57. raise RuntimeError("Database error (Knowledgebase)!")
  58. return doc
  59. @classmethod
  60. @DB.connection_context()
  61. def delete(cls, doc):
  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 cls.delete_by_id(doc.id)
  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.increment_chunk_num(
  73. doc.id, doc.kb_id, doc.token_num * -1, doc.chunk_num * -1, 0)
  74. if not cls.delete(doc):
  75. raise RuntimeError("Database error (Document removal)!")
  76. MINIO.rm(doc.kb_id, doc.location)
  77. return cls.delete_by_id(doc.id)
  78. @classmethod
  79. @DB.connection_context()
  80. def get_newly_uploaded(cls, tm, mod=0, comm=1, items_per_page=64):
  81. fields = [
  82. cls.model.id,
  83. cls.model.kb_id,
  84. cls.model.parser_id,
  85. cls.model.parser_config,
  86. cls.model.name,
  87. cls.model.type,
  88. cls.model.location,
  89. cls.model.size,
  90. Knowledgebase.tenant_id,
  91. Tenant.embd_id,
  92. Tenant.img2txt_id,
  93. Tenant.asr_id,
  94. cls.model.update_time]
  95. docs = cls.model.select(*fields) \
  96. .join(Knowledgebase, on=(cls.model.kb_id == Knowledgebase.id)) \
  97. .join(Tenant, on=(Knowledgebase.tenant_id == Tenant.id))\
  98. .where(
  99. cls.model.status == StatusEnum.VALID.value,
  100. ~(cls.model.type == FileType.VIRTUAL.value),
  101. cls.model.progress == 0,
  102. cls.model.update_time >= tm,
  103. cls.model.run == TaskStatus.RUNNING.value,
  104. (Expression(cls.model.create_time, "%%", comm) == mod))\
  105. .order_by(cls.model.update_time.asc())\
  106. .paginate(1, items_per_page)
  107. return list(docs.dicts())
  108. @classmethod
  109. @DB.connection_context()
  110. def get_unfinished_docs(cls):
  111. fields = [cls.model.id, cls.model.process_begin_at]
  112. docs = cls.model.select(*fields) \
  113. .where(
  114. cls.model.status == StatusEnum.VALID.value,
  115. ~(cls.model.type == FileType.VIRTUAL.value),
  116. cls.model.progress < 1,
  117. cls.model.progress > 0)
  118. return list(docs.dicts())
  119. @classmethod
  120. @DB.connection_context()
  121. def increment_chunk_num(cls, doc_id, kb_id, token_num, chunk_num, duation):
  122. num = cls.model.update(token_num=cls.model.token_num + token_num,
  123. chunk_num=cls.model.chunk_num + chunk_num,
  124. process_duation=cls.model.process_duation + duation).where(
  125. cls.model.id == doc_id).execute()
  126. if num == 0:
  127. raise LookupError(
  128. "Document not found which is supposed to be there")
  129. num = Knowledgebase.update(
  130. token_num=Knowledgebase.token_num +
  131. token_num,
  132. chunk_num=Knowledgebase.chunk_num +
  133. chunk_num).where(
  134. Knowledgebase.id == kb_id).execute()
  135. return num
  136. @classmethod
  137. @DB.connection_context()
  138. def get_tenant_id(cls, doc_id):
  139. docs = cls.model.select(
  140. Knowledgebase.tenant_id).join(
  141. Knowledgebase, on=(
  142. Knowledgebase.id == cls.model.kb_id)).where(
  143. cls.model.id == doc_id, Knowledgebase.status == StatusEnum.VALID.value)
  144. docs = docs.dicts()
  145. if not docs:
  146. return
  147. return docs[0]["tenant_id"]
  148. @classmethod
  149. @DB.connection_context()
  150. def get_thumbnails(cls, docids):
  151. fields = [cls.model.id, cls.model.thumbnail]
  152. return list(cls.model.select(
  153. *fields).where(cls.model.id.in_(docids)).dicts())
  154. @classmethod
  155. @DB.connection_context()
  156. def update_parser_config(cls, id, config):
  157. e, d = cls.get_by_id(id)
  158. if not e:
  159. raise LookupError(f"Document({id}) not found.")
  160. def dfs_update(old, new):
  161. for k, v in new.items():
  162. if k not in old:
  163. old[k] = v
  164. continue
  165. if isinstance(v, dict):
  166. assert isinstance(old[k], dict)
  167. dfs_update(old[k], v)
  168. else:
  169. old[k] = v
  170. dfs_update(d.parser_config, config)
  171. cls.update_by_id(id, {"parser_config": d.parser_config})
  172. @classmethod
  173. @DB.connection_context()
  174. def get_doc_count(cls, tenant_id):
  175. docs = cls.model.select(cls.model.id).join(Knowledgebase,
  176. on=(Knowledgebase.id == cls.model.kb_id)).where(
  177. Knowledgebase.tenant_id == tenant_id)
  178. return len(docs)