Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

knowledgebase_service.py 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 api.db import StatusEnum, TenantPermission
  17. from api.db.db_models import Knowledgebase, DB, Tenant, User, UserTenant,Document
  18. from api.db.services.common_service import CommonService
  19. from peewee import fn
  20. class KnowledgebaseService(CommonService):
  21. model = Knowledgebase
  22. @classmethod
  23. @DB.connection_context()
  24. def list_documents_by_ids(cls,kb_ids):
  25. doc_ids=cls.model.select(Document.id.alias("document_id")).join(Document,on=(cls.model.id == Document.kb_id)).where(
  26. cls.model.id.in_(kb_ids)
  27. )
  28. doc_ids =list(doc_ids.dicts())
  29. doc_ids = [doc["document_id"] for doc in doc_ids]
  30. return doc_ids
  31. @classmethod
  32. @DB.connection_context()
  33. def get_by_tenant_ids(cls, joined_tenant_ids, user_id,
  34. page_number, items_per_page,
  35. orderby, desc, keywords,
  36. parser_id=None
  37. ):
  38. fields = [
  39. cls.model.id,
  40. cls.model.avatar,
  41. cls.model.name,
  42. cls.model.language,
  43. cls.model.description,
  44. cls.model.permission,
  45. cls.model.doc_num,
  46. cls.model.token_num,
  47. cls.model.chunk_num,
  48. cls.model.parser_id,
  49. cls.model.embd_id,
  50. User.nickname,
  51. User.avatar.alias('tenant_avatar'),
  52. cls.model.update_time
  53. ]
  54. if keywords:
  55. kbs = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)).where(
  56. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  57. TenantPermission.TEAM.value)) | (
  58. cls.model.tenant_id == user_id))
  59. & (cls.model.status == StatusEnum.VALID.value),
  60. (fn.LOWER(cls.model.name).contains(keywords.lower()))
  61. )
  62. else:
  63. kbs = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)).where(
  64. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  65. TenantPermission.TEAM.value)) | (
  66. cls.model.tenant_id == user_id))
  67. & (cls.model.status == StatusEnum.VALID.value)
  68. )
  69. if parser_id:
  70. kbs = kbs.where(cls.model.parser_id == parser_id)
  71. if desc:
  72. kbs = kbs.order_by(cls.model.getter_by(orderby).desc())
  73. else:
  74. kbs = kbs.order_by(cls.model.getter_by(orderby).asc())
  75. count = kbs.count()
  76. kbs = kbs.paginate(page_number, items_per_page)
  77. return list(kbs.dicts()), count
  78. @classmethod
  79. @DB.connection_context()
  80. def get_kb_ids(cls, tenant_id):
  81. fields = [
  82. cls.model.id,
  83. ]
  84. kbs = cls.model.select(*fields).where(cls.model.tenant_id == tenant_id)
  85. kb_ids = [kb.id for kb in kbs]
  86. return kb_ids
  87. @classmethod
  88. @DB.connection_context()
  89. def get_detail(cls, kb_id):
  90. fields = [
  91. cls.model.id,
  92. # Tenant.embd_id,
  93. cls.model.embd_id,
  94. cls.model.avatar,
  95. cls.model.name,
  96. cls.model.language,
  97. cls.model.description,
  98. cls.model.permission,
  99. cls.model.doc_num,
  100. cls.model.token_num,
  101. cls.model.chunk_num,
  102. cls.model.parser_id,
  103. cls.model.parser_config,
  104. cls.model.pagerank]
  105. kbs = cls.model.select(*fields).join(Tenant, on=(
  106. (Tenant.id == cls.model.tenant_id) & (Tenant.status == StatusEnum.VALID.value))).where(
  107. (cls.model.id == kb_id),
  108. (cls.model.status == StatusEnum.VALID.value)
  109. )
  110. if not kbs:
  111. return
  112. d = kbs[0].to_dict()
  113. # d["embd_id"] = kbs[0].tenant.embd_id
  114. return d
  115. @classmethod
  116. @DB.connection_context()
  117. def update_parser_config(cls, id, config):
  118. e, m = cls.get_by_id(id)
  119. if not e:
  120. raise LookupError(f"knowledgebase({id}) not found.")
  121. def dfs_update(old, new):
  122. for k, v in new.items():
  123. if k not in old:
  124. old[k] = v
  125. continue
  126. if isinstance(v, dict):
  127. assert isinstance(old[k], dict)
  128. dfs_update(old[k], v)
  129. elif isinstance(v, list):
  130. assert isinstance(old[k], list)
  131. old[k] = list(set(old[k] + v))
  132. else:
  133. old[k] = v
  134. dfs_update(m.parser_config, config)
  135. cls.update_by_id(id, {"parser_config": m.parser_config})
  136. @classmethod
  137. @DB.connection_context()
  138. def get_field_map(cls, ids):
  139. conf = {}
  140. for k in cls.get_by_ids(ids):
  141. if k.parser_config and "field_map" in k.parser_config:
  142. conf.update(k.parser_config["field_map"])
  143. return conf
  144. @classmethod
  145. @DB.connection_context()
  146. def get_by_name(cls, kb_name, tenant_id):
  147. kb = cls.model.select().where(
  148. (cls.model.name == kb_name)
  149. & (cls.model.tenant_id == tenant_id)
  150. & (cls.model.status == StatusEnum.VALID.value)
  151. )
  152. if kb:
  153. return True, kb[0]
  154. return False, None
  155. @classmethod
  156. @DB.connection_context()
  157. def get_all_ids(cls):
  158. return [m["id"] for m in cls.model.select(cls.model.id).dicts()]
  159. @classmethod
  160. @DB.connection_context()
  161. def get_list(cls, joined_tenant_ids, user_id,
  162. page_number, items_per_page, orderby, desc, id, name):
  163. kbs = cls.model.select()
  164. if id:
  165. kbs = kbs.where(cls.model.id == id)
  166. if name:
  167. kbs = kbs.where(cls.model.name == name)
  168. kbs = kbs.where(
  169. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  170. TenantPermission.TEAM.value)) | (
  171. cls.model.tenant_id == user_id))
  172. & (cls.model.status == StatusEnum.VALID.value)
  173. )
  174. if desc:
  175. kbs = kbs.order_by(cls.model.getter_by(orderby).desc())
  176. else:
  177. kbs = kbs.order_by(cls.model.getter_by(orderby).asc())
  178. kbs = kbs.paginate(page_number, items_per_page)
  179. return list(kbs.dicts())
  180. @classmethod
  181. @DB.connection_context()
  182. def accessible(cls, kb_id, user_id):
  183. docs = cls.model.select(
  184. cls.model.id).join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  185. ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1)
  186. docs = docs.dicts()
  187. if not docs:
  188. return False
  189. return True
  190. @classmethod
  191. @DB.connection_context()
  192. def get_kb_by_id(cls, kb_id, user_id):
  193. kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  194. ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1)
  195. kbs = kbs.dicts()
  196. return list(kbs)
  197. @classmethod
  198. @DB.connection_context()
  199. def get_kb_by_name(cls, kb_name, user_id):
  200. kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  201. ).where(cls.model.name == kb_name, UserTenant.user_id == user_id).paginate(0, 1)
  202. kbs = kbs.dicts()
  203. return list(kbs)
  204. @classmethod
  205. @DB.connection_context()
  206. def accessible4deletion(cls, kb_id, user_id):
  207. docs = cls.model.select(
  208. cls.model.id).where(cls.model.id == kb_id, cls.model.created_by == user_id).paginate(0, 1)
  209. docs = docs.dicts()
  210. if not docs:
  211. return False
  212. return True