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

document_service.py 6.7KB

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