Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

file_service.py 19KB

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