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

file_service.py 15KB

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