You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

file_service.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. import re
  17. import os
  18. from flask_login import current_user
  19. from peewee import fn
  20. from api.db import FileType, KNOWLEDGEBASE_FOLDER_NAME, FileSource, ParserType
  21. from api.db.db_models import DB, File2Document, Knowledgebase
  22. from api.db.db_models import File, Document
  23. from api.db.services import duplicate_name
  24. from api.db.services.common_service import CommonService
  25. from api.db.services.document_service import DocumentService
  26. from api.db.services.file2document_service import File2DocumentService
  27. from api.utils import get_uuid
  28. from api.utils.file_utils import filename_type, thumbnail
  29. from rag.utils.storage_factory import STORAGE_IMPL
  30. class FileService(CommonService):
  31. model = File
  32. @classmethod
  33. @DB.connection_context()
  34. def get_by_pf_id(cls, tenant_id, pf_id, page_number, items_per_page,
  35. orderby, desc, keywords):
  36. if keywords:
  37. files = cls.model.select().where(
  38. (cls.model.tenant_id == tenant_id),
  39. (cls.model.parent_id == pf_id),
  40. (fn.LOWER(cls.model.name).contains(keywords.lower())),
  41. ~(cls.model.id == pf_id)
  42. )
  43. else:
  44. files = cls.model.select().where((cls.model.tenant_id == tenant_id),
  45. (cls.model.parent_id == pf_id),
  46. ~(cls.model.id == pf_id)
  47. )
  48. count = files.count()
  49. if desc:
  50. files = files.order_by(cls.model.getter_by(orderby).desc())
  51. else:
  52. files = files.order_by(cls.model.getter_by(orderby).asc())
  53. files = files.paginate(page_number, items_per_page)
  54. res_files = list(files.dicts())
  55. for file in res_files:
  56. if file["type"] == FileType.FOLDER.value:
  57. file["size"] = cls.get_folder_size(file["id"])
  58. file['kbs_info'] = []
  59. children = list(cls.model.select().where(
  60. (cls.model.tenant_id == tenant_id),
  61. (cls.model.parent_id == file["id"]),
  62. ~(cls.model.id == file["id"]),
  63. ).dicts())
  64. file["has_child_folder"] = any(value["type"] == FileType.FOLDER.value for value in children)
  65. continue
  66. kbs_info = cls.get_kb_id_by_file_id(file['id'])
  67. file['kbs_info'] = kbs_info
  68. return res_files, count
  69. @classmethod
  70. @DB.connection_context()
  71. def get_kb_id_by_file_id(cls, file_id):
  72. kbs = (cls.model.select(*[Knowledgebase.id, Knowledgebase.name])
  73. .join(File2Document, on=(File2Document.file_id == file_id))
  74. .join(Document, on=(File2Document.document_id == Document.id))
  75. .join(Knowledgebase, on=(Knowledgebase.id == Document.kb_id))
  76. .where(cls.model.id == file_id))
  77. if not kbs: return []
  78. kbs_info_list = []
  79. for kb in list(kbs.dicts()):
  80. kbs_info_list.append({"kb_id": kb['id'], "kb_name": kb['name']})
  81. return kbs_info_list
  82. @classmethod
  83. @DB.connection_context()
  84. def get_by_pf_id_name(cls, id, name):
  85. file = cls.model.select().where((cls.model.parent_id == id) & (cls.model.name == name))
  86. if file.count():
  87. e, file = cls.get_by_id(file[0].id)
  88. if not e:
  89. raise RuntimeError("Database error (File retrieval)!")
  90. return file
  91. return None
  92. @classmethod
  93. @DB.connection_context()
  94. def get_id_list_by_id(cls, id, name, count, res):
  95. if count < len(name):
  96. file = cls.get_by_pf_id_name(id, name[count])
  97. if file:
  98. res.append(file.id)
  99. return cls.get_id_list_by_id(file.id, name, count + 1, res)
  100. else:
  101. return res
  102. else:
  103. return res
  104. @classmethod
  105. @DB.connection_context()
  106. def get_all_innermost_file_ids(cls, folder_id, result_ids):
  107. subfolders = cls.model.select().where(cls.model.parent_id == folder_id)
  108. if subfolders.exists():
  109. for subfolder in subfolders:
  110. cls.get_all_innermost_file_ids(subfolder.id, result_ids)
  111. else:
  112. result_ids.append(folder_id)
  113. return result_ids
  114. @classmethod
  115. @DB.connection_context()
  116. def create_folder(cls, file, parent_id, name, count):
  117. if count > len(name) - 2:
  118. return file
  119. else:
  120. file = cls.insert({
  121. "id": get_uuid(),
  122. "parent_id": parent_id,
  123. "tenant_id": current_user.id,
  124. "created_by": current_user.id,
  125. "name": name[count],
  126. "location": "",
  127. "size": 0,
  128. "type": FileType.FOLDER.value
  129. })
  130. return cls.create_folder(file, file.id, name, count + 1)
  131. @classmethod
  132. @DB.connection_context()
  133. def is_parent_folder_exist(cls, parent_id):
  134. parent_files = cls.model.select().where(cls.model.id == parent_id)
  135. if parent_files.count():
  136. return True
  137. cls.delete_folder_by_pf_id(parent_id)
  138. return False
  139. @classmethod
  140. @DB.connection_context()
  141. def get_root_folder(cls, tenant_id):
  142. for file in cls.model.select().where((cls.model.tenant_id == tenant_id),
  143. (cls.model.parent_id == cls.model.id)
  144. ):
  145. return file.to_dict()
  146. file_id = get_uuid()
  147. file = {
  148. "id": file_id,
  149. "parent_id": file_id,
  150. "tenant_id": tenant_id,
  151. "created_by": tenant_id,
  152. "name": "/",
  153. "type": FileType.FOLDER.value,
  154. "size": 0,
  155. "location": "",
  156. }
  157. cls.save(**file)
  158. return file
  159. @classmethod
  160. @DB.connection_context()
  161. def get_kb_folder(cls, tenant_id):
  162. for root in cls.model.select().where(
  163. (cls.model.tenant_id == tenant_id), (cls.model.parent_id == cls.model.id)):
  164. for folder in cls.model.select().where(
  165. (cls.model.tenant_id == tenant_id), (cls.model.parent_id == root.id),
  166. (cls.model.name == KNOWLEDGEBASE_FOLDER_NAME)):
  167. return folder.to_dict()
  168. assert False, "Can't find the KB folder. Database init error."
  169. @classmethod
  170. @DB.connection_context()
  171. def new_a_file_from_kb(cls, tenant_id, name, parent_id, ty=FileType.FOLDER.value, size=0, location=""):
  172. for file in cls.query(tenant_id=tenant_id, parent_id=parent_id, name=name):
  173. return file.to_dict()
  174. file = {
  175. "id": get_uuid(),
  176. "parent_id": parent_id,
  177. "tenant_id": tenant_id,
  178. "created_by": tenant_id,
  179. "name": name,
  180. "type": ty,
  181. "size": size,
  182. "location": location,
  183. "source_type": FileSource.KNOWLEDGEBASE
  184. }
  185. cls.save(**file)
  186. return file
  187. @classmethod
  188. @DB.connection_context()
  189. def init_knowledgebase_docs(cls, root_id, tenant_id):
  190. for _ in cls.model.select().where((cls.model.name == KNOWLEDGEBASE_FOLDER_NAME)\
  191. & (cls.model.parent_id == root_id)):
  192. return
  193. folder = cls.new_a_file_from_kb(tenant_id, KNOWLEDGEBASE_FOLDER_NAME, root_id)
  194. for kb in Knowledgebase.select(*[Knowledgebase.id, Knowledgebase.name]).where(Knowledgebase.tenant_id==tenant_id):
  195. kb_folder = cls.new_a_file_from_kb(tenant_id, kb.name, folder["id"])
  196. for doc in DocumentService.query(kb_id=kb.id):
  197. FileService.add_file_from_kb(doc.to_dict(), kb_folder["id"], tenant_id)
  198. @classmethod
  199. @DB.connection_context()
  200. def get_parent_folder(cls, file_id):
  201. file = cls.model.select().where(cls.model.id == file_id)
  202. if file.count():
  203. e, file = cls.get_by_id(file[0].parent_id)
  204. if not e:
  205. raise RuntimeError("Database error (File retrieval)!")
  206. else:
  207. raise RuntimeError("Database error (File doesn't exist)!")
  208. return file
  209. @classmethod
  210. @DB.connection_context()
  211. def get_all_parent_folders(cls, start_id):
  212. parent_folders = []
  213. current_id = start_id
  214. while current_id:
  215. e, file = cls.get_by_id(current_id)
  216. if file.parent_id != file.id and e:
  217. parent_folders.append(file)
  218. current_id = file.parent_id
  219. else:
  220. parent_folders.append(file)
  221. break
  222. return parent_folders
  223. @classmethod
  224. @DB.connection_context()
  225. def insert(cls, file):
  226. if not cls.save(**file):
  227. raise RuntimeError("Database error (File)!")
  228. e, file = cls.get_by_id(file["id"])
  229. if not e:
  230. raise RuntimeError("Database error (File retrieval)!")
  231. return file
  232. @classmethod
  233. @DB.connection_context()
  234. def delete(cls, file):
  235. return cls.delete_by_id(file.id)
  236. @classmethod
  237. @DB.connection_context()
  238. def delete_by_pf_id(cls, folder_id):
  239. return cls.model.delete().where(cls.model.parent_id == folder_id).execute()
  240. @classmethod
  241. @DB.connection_context()
  242. def delete_folder_by_pf_id(cls, user_id, folder_id):
  243. try:
  244. files = cls.model.select().where((cls.model.tenant_id == user_id)
  245. & (cls.model.parent_id == folder_id))
  246. for file in files:
  247. cls.delete_folder_by_pf_id(user_id, file.id)
  248. return cls.model.delete().where((cls.model.tenant_id == user_id)
  249. & (cls.model.id == folder_id)).execute(),
  250. except Exception as e:
  251. print(e)
  252. raise RuntimeError("Database error (File retrieval)!")
  253. @classmethod
  254. @DB.connection_context()
  255. def get_file_count(cls, tenant_id):
  256. files = cls.model.select(cls.model.id).where(cls.model.tenant_id == tenant_id)
  257. return len(files)
  258. @classmethod
  259. @DB.connection_context()
  260. def get_folder_size(cls, folder_id):
  261. size = 0
  262. def dfs(parent_id):
  263. nonlocal size
  264. for f in cls.model.select(*[cls.model.id, cls.model.size, cls.model.type]).where(
  265. cls.model.parent_id == parent_id, cls.model.id != parent_id):
  266. size += f.size
  267. if f.type == FileType.FOLDER.value:
  268. dfs(f.id)
  269. dfs(folder_id)
  270. return size
  271. @classmethod
  272. @DB.connection_context()
  273. def add_file_from_kb(cls, doc, kb_folder_id, tenant_id):
  274. for _ in File2DocumentService.get_by_document_id(doc["id"]): return
  275. file = {
  276. "id": get_uuid(),
  277. "parent_id": kb_folder_id,
  278. "tenant_id": tenant_id,
  279. "created_by": tenant_id,
  280. "name": doc["name"],
  281. "type": doc["type"],
  282. "size": doc["size"],
  283. "location": doc["location"],
  284. "source_type": FileSource.KNOWLEDGEBASE
  285. }
  286. cls.save(**file)
  287. File2DocumentService.save(**{"id": get_uuid(), "file_id": file["id"], "document_id": doc["id"]})
  288. @classmethod
  289. @DB.connection_context()
  290. def move_file(cls, file_ids, folder_id):
  291. try:
  292. cls.filter_update((cls.model.id << file_ids, ), { 'parent_id': folder_id })
  293. except Exception as e:
  294. print(e)
  295. raise RuntimeError("Database error (File move)!")
  296. @classmethod
  297. @DB.connection_context()
  298. def upload_document(self, kb, file_objs, user_id):
  299. root_folder = self.get_root_folder(user_id)
  300. pf_id = root_folder["id"]
  301. self.init_knowledgebase_docs(pf_id, user_id)
  302. kb_root_folder = self.get_kb_folder(user_id)
  303. kb_folder = self.new_a_file_from_kb(kb.tenant_id, kb.name, kb_root_folder["id"])
  304. err, files = [], []
  305. for file in file_objs:
  306. try:
  307. MAX_FILE_NUM_PER_USER = int(os.environ.get('MAX_FILE_NUM_PER_USER', 0))
  308. if MAX_FILE_NUM_PER_USER > 0 and DocumentService.get_doc_count(kb.tenant_id) >= MAX_FILE_NUM_PER_USER:
  309. raise RuntimeError("Exceed the maximum file number of a free user!")
  310. filename = duplicate_name(
  311. DocumentService.query,
  312. name=file.filename,
  313. kb_id=kb.id)
  314. filetype = filename_type(filename)
  315. if filetype == FileType.OTHER.value:
  316. raise RuntimeError("This type of file has not been supported yet!")
  317. location = filename
  318. while STORAGE_IMPL.obj_exist(kb.id, location):
  319. location += "_"
  320. blob = file.read()
  321. STORAGE_IMPL.put(kb.id, location, blob)
  322. doc = {
  323. "id": get_uuid(),
  324. "kb_id": kb.id,
  325. "parser_id": kb.parser_id,
  326. "parser_config": kb.parser_config,
  327. "created_by": user_id,
  328. "type": filetype,
  329. "name": filename,
  330. "location": location,
  331. "size": len(blob),
  332. "thumbnail": thumbnail(filename, blob)
  333. }
  334. self.set_constant_parser(doc, filename)
  335. DocumentService.insert(doc)
  336. FileService.add_file_from_kb(doc, kb_folder["id"], kb.tenant_id)
  337. files.append((doc, blob))
  338. except Exception as e:
  339. err.append(file.filename + ": " + str(e))
  340. return err, files
  341. @staticmethod
  342. def set_constant_parser(doc, filename):
  343. if doc["type"] == FileType.VISUAL:
  344. doc["parser_id"] = ParserType.PICTURE.value
  345. if doc["type"] == FileType.AURAL:
  346. doc["parser_id"] = ParserType.AUDIO.value
  347. if re.search(r"\.(ppt|pptx|pages)$", filename):
  348. doc["parser_id"] = ParserType.PRESENTATION.value
  349. if re.search(r"\.(eml)$", filename):
  350. doc["parser_id"] = ParserType.EMAIL.value