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