Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

file_service.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 flask_login import current_user
  17. from peewee import fn
  18. from api.db import FileType, KNOWLEDGEBASE_FOLDER_NAME, FileSource
  19. from api.db.db_models import DB, File2Document, Knowledgebase
  20. from api.db.db_models import File, Document
  21. from api.db.services.common_service import CommonService
  22. from api.db.services.document_service import DocumentService
  23. from api.db.services.file2document_service import File2DocumentService
  24. from api.utils import get_uuid
  25. class FileService(CommonService):
  26. model = File
  27. @classmethod
  28. @DB.connection_context()
  29. def get_by_pf_id(cls, tenant_id, pf_id, page_number, items_per_page,
  30. orderby, desc, keywords):
  31. if keywords:
  32. files = cls.model.select().where(
  33. (cls.model.tenant_id == tenant_id)
  34. (cls.model.parent_id == pf_id),
  35. (fn.LOWER(cls.model.name).like(f"%%{keywords.lower()}%%")),
  36. ~(cls.model.id == pf_id)
  37. )
  38. else:
  39. files = cls.model.select().where((cls.model.tenant_id == tenant_id),
  40. (cls.model.parent_id == pf_id),
  41. ~(cls.model.id == pf_id)
  42. )
  43. count = files.count()
  44. if desc:
  45. files = files.order_by(cls.model.getter_by(orderby).desc())
  46. else:
  47. files = files.order_by(cls.model.getter_by(orderby).asc())
  48. files = files.paginate(page_number, items_per_page)
  49. res_files = list(files.dicts())
  50. for file in res_files:
  51. if file["type"] == FileType.FOLDER.value:
  52. file["size"] = cls.get_folder_size(file["id"])
  53. file['kbs_info'] = []
  54. continue
  55. kbs_info = cls.get_kb_id_by_file_id(file['id'])
  56. file['kbs_info'] = kbs_info
  57. return res_files, count
  58. @classmethod
  59. @DB.connection_context()
  60. def get_kb_id_by_file_id(cls, file_id):
  61. kbs = (cls.model.select(*[Knowledgebase.id, Knowledgebase.name])
  62. .join(File2Document, on=(File2Document.file_id == file_id))
  63. .join(Document, on=(File2Document.document_id == Document.id))
  64. .join(Knowledgebase, on=(Knowledgebase.id == Document.kb_id))
  65. .where(cls.model.id == file_id))
  66. if not kbs: return []
  67. kbs_info_list = []
  68. for kb in list(kbs.dicts()):
  69. kbs_info_list.append({"kb_id": kb['id'], "kb_name": kb['name']})
  70. return kbs_info_list
  71. @classmethod
  72. @DB.connection_context()
  73. def get_by_pf_id_name(cls, id, name):
  74. file = cls.model.select().where((cls.model.parent_id == id) & (cls.model.name == name))
  75. if file.count():
  76. e, file = cls.get_by_id(file[0].id)
  77. if not e:
  78. raise RuntimeError("Database error (File retrieval)!")
  79. return file
  80. return None
  81. @classmethod
  82. @DB.connection_context()
  83. def get_id_list_by_id(cls, id, name, count, res):
  84. if count < len(name):
  85. file = cls.get_by_pf_id_name(id, name[count])
  86. if file:
  87. res.append(file.id)
  88. return cls.get_id_list_by_id(file.id, name, count + 1, res)
  89. else:
  90. return res
  91. else:
  92. return res
  93. @classmethod
  94. @DB.connection_context()
  95. def get_all_innermost_file_ids(cls, folder_id, result_ids):
  96. subfolders = cls.model.select().where(cls.model.parent_id == folder_id)
  97. if subfolders.exists():
  98. for subfolder in subfolders:
  99. cls.get_all_innermost_file_ids(subfolder.id, result_ids)
  100. else:
  101. result_ids.append(folder_id)
  102. return result_ids
  103. @classmethod
  104. @DB.connection_context()
  105. def create_folder(cls, file, parent_id, name, count):
  106. if count > len(name) - 2:
  107. return file
  108. else:
  109. file = cls.insert({
  110. "id": get_uuid(),
  111. "parent_id": parent_id,
  112. "tenant_id": current_user.id,
  113. "created_by": current_user.id,
  114. "name": name[count],
  115. "location": "",
  116. "size": 0,
  117. "type": FileType.FOLDER.value
  118. })
  119. return cls.create_folder(file, file.id, name, count + 1)
  120. @classmethod
  121. @DB.connection_context()
  122. def is_parent_folder_exist(cls, parent_id):
  123. parent_files = cls.model.select().where(cls.model.id == parent_id)
  124. if parent_files.count():
  125. return True
  126. cls.delete_folder_by_pf_id(parent_id)
  127. return False
  128. @classmethod
  129. @DB.connection_context()
  130. def get_root_folder(cls, tenant_id):
  131. for file in cls.model.select().where((cls.model.tenant_id == tenant_id),
  132. (cls.model.parent_id == cls.model.id)
  133. ):
  134. return file.to_dict()
  135. file_id = get_uuid()
  136. file = {
  137. "id": file_id,
  138. "parent_id": file_id,
  139. "tenant_id": tenant_id,
  140. "created_by": tenant_id,
  141. "name": "/",
  142. "type": FileType.FOLDER.value,
  143. "size": 0,
  144. "location": "",
  145. }
  146. cls.save(**file)
  147. return file
  148. @classmethod
  149. @DB.connection_context()
  150. def get_kb_folder(cls, tenant_id):
  151. for root in cls.model.select().where(cls.model.tenant_id == tenant_id and
  152. cls.model.parent_id == cls.model.id):
  153. for folder in cls.model.select().where(cls.model.tenant_id == tenant_id and
  154. cls.model.parent_id == root.id and
  155. cls.model.name == KNOWLEDGEBASE_FOLDER_NAME
  156. ):
  157. return folder.to_dict()
  158. assert False, "Can't find the KB folder. Database init error."
  159. @classmethod
  160. @DB.connection_context()
  161. def new_a_file_from_kb(cls, tenant_id, name, parent_id, ty=FileType.FOLDER.value, size=0, location=""):
  162. for file in cls.query(tenant_id=tenant_id, parent_id=parent_id, name=name):
  163. return file.to_dict()
  164. file = {
  165. "id": get_uuid(),
  166. "parent_id": parent_id,
  167. "tenant_id": tenant_id,
  168. "created_by": tenant_id,
  169. "name": name,
  170. "type": ty,
  171. "size": size,
  172. "location": location,
  173. "source_type": FileSource.KNOWLEDGEBASE
  174. }
  175. cls.save(**file)
  176. return file
  177. @classmethod
  178. @DB.connection_context()
  179. def init_knowledgebase_docs(cls, root_id, tenant_id):
  180. for _ in cls.model.select().where((cls.model.name == KNOWLEDGEBASE_FOLDER_NAME)\
  181. & (cls.model.parent_id == root_id)):
  182. return
  183. folder = cls.new_a_file_from_kb(tenant_id, KNOWLEDGEBASE_FOLDER_NAME, root_id)
  184. for kb in Knowledgebase.select(*[Knowledgebase.id, Knowledgebase.name]).where(Knowledgebase.tenant_id==tenant_id):
  185. kb_folder = cls.new_a_file_from_kb(tenant_id, kb.name, folder["id"])
  186. for doc in DocumentService.query(kb_id=kb.id):
  187. FileService.add_file_from_kb(doc.to_dict(), kb_folder["id"], tenant_id)
  188. @classmethod
  189. @DB.connection_context()
  190. def get_parent_folder(cls, file_id):
  191. file = cls.model.select().where(cls.model.id == file_id)
  192. if file.count():
  193. e, file = cls.get_by_id(file[0].parent_id)
  194. if not e:
  195. raise RuntimeError("Database error (File retrieval)!")
  196. else:
  197. raise RuntimeError("Database error (File doesn't exist)!")
  198. return file
  199. @classmethod
  200. @DB.connection_context()
  201. def get_all_parent_folders(cls, start_id):
  202. parent_folders = []
  203. current_id = start_id
  204. while current_id:
  205. e, file = cls.get_by_id(current_id)
  206. if file.parent_id != file.id and e:
  207. parent_folders.append(file)
  208. current_id = file.parent_id
  209. else:
  210. parent_folders.append(file)
  211. break
  212. return parent_folders
  213. @classmethod
  214. @DB.connection_context()
  215. def insert(cls, file):
  216. if not cls.save(**file):
  217. raise RuntimeError("Database error (File)!")
  218. e, file = cls.get_by_id(file["id"])
  219. if not e:
  220. raise RuntimeError("Database error (File retrieval)!")
  221. return file
  222. @classmethod
  223. @DB.connection_context()
  224. def delete(cls, file):
  225. return cls.delete_by_id(file.id)
  226. @classmethod
  227. @DB.connection_context()
  228. def delete_by_pf_id(cls, folder_id):
  229. return cls.model.delete().where(cls.model.parent_id == folder_id).execute()
  230. @classmethod
  231. @DB.connection_context()
  232. def delete_folder_by_pf_id(cls, user_id, folder_id):
  233. try:
  234. files = cls.model.select().where((cls.model.tenant_id == user_id)
  235. & (cls.model.parent_id == folder_id))
  236. for file in files:
  237. cls.delete_folder_by_pf_id(user_id, file.id)
  238. return cls.model.delete().where((cls.model.tenant_id == user_id)
  239. & (cls.model.id == folder_id)).execute(),
  240. except Exception as e:
  241. print(e)
  242. raise RuntimeError("Database error (File retrieval)!")
  243. @classmethod
  244. @DB.connection_context()
  245. def get_file_count(cls, tenant_id):
  246. files = cls.model.select(cls.model.id).where(cls.model.tenant_id == tenant_id)
  247. return len(files)
  248. @classmethod
  249. @DB.connection_context()
  250. def get_folder_size(cls, folder_id):
  251. size = 0
  252. def dfs(parent_id):
  253. nonlocal size
  254. for f in cls.model.select(*[cls.model.id, cls.model.size, cls.model.type]).where(
  255. cls.model.parent_id == parent_id, cls.model.id != parent_id):
  256. size += f.size
  257. if f.type == FileType.FOLDER.value:
  258. dfs(f.id)
  259. dfs(folder_id)
  260. return size
  261. @classmethod
  262. @DB.connection_context()
  263. def add_file_from_kb(cls, doc, kb_folder_id, tenant_id):
  264. for _ in File2DocumentService.get_by_document_id(doc["id"]): return
  265. file = {
  266. "id": get_uuid(),
  267. "parent_id": kb_folder_id,
  268. "tenant_id": tenant_id,
  269. "created_by": tenant_id,
  270. "name": doc["name"],
  271. "type": doc["type"],
  272. "size": doc["size"],
  273. "location": doc["location"],
  274. "source_type": FileSource.KNOWLEDGEBASE
  275. }
  276. cls.save(**file)
  277. File2DocumentService.save(**{"id": get_uuid(), "file_id": file["id"], "document_id": doc["id"]})