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

knowledgebase_service.py 8.1KB

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