Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

knowledgebase_service.py 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. kbs = cls.model.select(*fields).join(Tenant, on=(
  100. (Tenant.id == cls.model.tenant_id) & (Tenant.status == StatusEnum.VALID.value))).where(
  101. (cls.model.id == kb_id),
  102. (cls.model.status == StatusEnum.VALID.value)
  103. )
  104. if not kbs:
  105. return
  106. d = kbs[0].to_dict()
  107. # d["embd_id"] = kbs[0].tenant.embd_id
  108. return d
  109. @classmethod
  110. @DB.connection_context()
  111. def update_parser_config(cls, id, config):
  112. e, m = cls.get_by_id(id)
  113. if not e:
  114. raise LookupError(f"knowledgebase({id}) not found.")
  115. def dfs_update(old, new):
  116. for k, v in new.items():
  117. if k not in old:
  118. old[k] = v
  119. continue
  120. if isinstance(v, dict):
  121. assert isinstance(old[k], dict)
  122. dfs_update(old[k], v)
  123. elif isinstance(v, list):
  124. assert isinstance(old[k], list)
  125. old[k] = list(set(old[k] + v))
  126. else:
  127. old[k] = v
  128. dfs_update(m.parser_config, config)
  129. cls.update_by_id(id, {"parser_config": m.parser_config})
  130. @classmethod
  131. @DB.connection_context()
  132. def get_field_map(cls, ids):
  133. conf = {}
  134. for k in cls.get_by_ids(ids):
  135. if k.parser_config and "field_map" in k.parser_config:
  136. conf.update(k.parser_config["field_map"])
  137. return conf
  138. @classmethod
  139. @DB.connection_context()
  140. def get_by_name(cls, kb_name, tenant_id):
  141. kb = cls.model.select().where(
  142. (cls.model.name == kb_name)
  143. & (cls.model.tenant_id == tenant_id)
  144. & (cls.model.status == StatusEnum.VALID.value)
  145. )
  146. if kb:
  147. return True, kb[0]
  148. return False, None
  149. @classmethod
  150. @DB.connection_context()
  151. def get_all_ids(cls):
  152. return [m["id"] for m in cls.model.select(cls.model.id).dicts()]
  153. @classmethod
  154. @DB.connection_context()
  155. def get_list(cls, joined_tenant_ids, user_id,
  156. page_number, items_per_page, orderby, desc, id, name):
  157. kbs = cls.model.select()
  158. if id:
  159. kbs = kbs.where(cls.model.id == id)
  160. if name:
  161. kbs = kbs.where(cls.model.name == name)
  162. kbs = kbs.where(
  163. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  164. TenantPermission.TEAM.value)) | (
  165. cls.model.tenant_id == user_id))
  166. & (cls.model.status == StatusEnum.VALID.value)
  167. )
  168. if desc:
  169. kbs = kbs.order_by(cls.model.getter_by(orderby).desc())
  170. else:
  171. kbs = kbs.order_by(cls.model.getter_by(orderby).asc())
  172. kbs = kbs.paginate(page_number, items_per_page)
  173. return list(kbs.dicts())
  174. @classmethod
  175. @DB.connection_context()
  176. def accessible(cls, kb_id, user_id):
  177. docs = cls.model.select(
  178. cls.model.id).join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  179. ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1)
  180. docs = docs.dicts()
  181. if not docs:
  182. return False
  183. return True
  184. @classmethod
  185. @DB.connection_context()
  186. def get_kb_by_id(cls, kb_id, user_id):
  187. kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  188. ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1)
  189. kbs = kbs.dicts()
  190. return list(kbs)
  191. @classmethod
  192. @DB.connection_context()
  193. def get_kb_by_name(cls, kb_name, user_id):
  194. kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  195. ).where(cls.model.name == kb_name, UserTenant.user_id == user_id).paginate(0, 1)
  196. kbs = kbs.dicts()
  197. return list(kbs)
  198. @classmethod
  199. @DB.connection_context()
  200. def accessible4deletion(cls, kb_id, user_id):
  201. docs = cls.model.select(
  202. cls.model.id).where(cls.model.id == kb_id, cls.model.created_by == user_id).paginate(0, 1)
  203. docs = docs.dicts()
  204. if not docs:
  205. return False
  206. return True