Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

file_service.py 19KB

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