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

file_service.py 19KB

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