Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

file_service.py 16KB

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