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 16KB

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