You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

file_factory.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. import mimetypes
  2. import uuid
  3. from collections.abc import Callable, Mapping, Sequence
  4. from typing import Any, cast
  5. import httpx
  6. from sqlalchemy import select
  7. from sqlalchemy.orm import Session
  8. from constants import AUDIO_EXTENSIONS, DOCUMENT_EXTENSIONS, IMAGE_EXTENSIONS, VIDEO_EXTENSIONS
  9. from core.file import File, FileBelongsTo, FileTransferMethod, FileType, FileUploadConfig, helpers
  10. from core.helper import ssrf_proxy
  11. from extensions.ext_database import db
  12. from models import MessageFile, ToolFile, UploadFile
  13. def build_from_message_files(
  14. *,
  15. message_files: Sequence["MessageFile"],
  16. tenant_id: str,
  17. config: FileUploadConfig,
  18. ) -> Sequence[File]:
  19. results = [
  20. build_from_message_file(message_file=file, tenant_id=tenant_id, config=config)
  21. for file in message_files
  22. if file.belongs_to != FileBelongsTo.ASSISTANT
  23. ]
  24. return results
  25. def build_from_message_file(
  26. *,
  27. message_file: "MessageFile",
  28. tenant_id: str,
  29. config: FileUploadConfig,
  30. ):
  31. mapping = {
  32. "transfer_method": message_file.transfer_method,
  33. "url": message_file.url,
  34. "id": message_file.id,
  35. "type": message_file.type,
  36. "upload_file_id": message_file.upload_file_id,
  37. }
  38. return build_from_mapping(
  39. mapping=mapping,
  40. tenant_id=tenant_id,
  41. config=config,
  42. )
  43. def build_from_mapping(
  44. *,
  45. mapping: Mapping[str, Any],
  46. tenant_id: str,
  47. config: FileUploadConfig | None = None,
  48. strict_type_validation: bool = False,
  49. ) -> File:
  50. transfer_method = FileTransferMethod.value_of(mapping.get("transfer_method"))
  51. build_functions: dict[FileTransferMethod, Callable] = {
  52. FileTransferMethod.LOCAL_FILE: _build_from_local_file,
  53. FileTransferMethod.REMOTE_URL: _build_from_remote_url,
  54. FileTransferMethod.TOOL_FILE: _build_from_tool_file,
  55. }
  56. build_func = build_functions.get(transfer_method)
  57. if not build_func:
  58. raise ValueError(f"Invalid file transfer method: {transfer_method}")
  59. file: File = build_func(
  60. mapping=mapping,
  61. tenant_id=tenant_id,
  62. transfer_method=transfer_method,
  63. strict_type_validation=strict_type_validation,
  64. )
  65. if config and not _is_file_valid_with_config(
  66. input_file_type=mapping.get("type", FileType.CUSTOM),
  67. file_extension=file.extension or "",
  68. file_transfer_method=file.transfer_method,
  69. config=config,
  70. ):
  71. raise ValueError(f"File validation failed for file: {file.filename}")
  72. return file
  73. def build_from_mappings(
  74. *,
  75. mappings: Sequence[Mapping[str, Any]],
  76. config: FileUploadConfig | None = None,
  77. tenant_id: str,
  78. strict_type_validation: bool = False,
  79. ) -> Sequence[File]:
  80. # TODO(QuantumGhost): Performance concern - each mapping triggers a separate database query.
  81. # Implement batch processing to reduce database load when handling multiple files.
  82. files = [
  83. build_from_mapping(
  84. mapping=mapping,
  85. tenant_id=tenant_id,
  86. config=config,
  87. strict_type_validation=strict_type_validation,
  88. )
  89. for mapping in mappings
  90. ]
  91. if (
  92. config
  93. # If image config is set.
  94. and config.image_config
  95. # And the number of image files exceeds the maximum limit
  96. and sum(1 for _ in (filter(lambda x: x.type == FileType.IMAGE, files))) > config.image_config.number_limits
  97. ):
  98. raise ValueError(f"Number of image files exceeds the maximum limit {config.image_config.number_limits}")
  99. if config and config.number_limits and len(files) > config.number_limits:
  100. raise ValueError(f"Number of files exceeds the maximum limit {config.number_limits}")
  101. return files
  102. def _build_from_local_file(
  103. *,
  104. mapping: Mapping[str, Any],
  105. tenant_id: str,
  106. transfer_method: FileTransferMethod,
  107. strict_type_validation: bool = False,
  108. ) -> File:
  109. upload_file_id = mapping.get("upload_file_id")
  110. if not upload_file_id:
  111. raise ValueError("Invalid upload file id")
  112. # check if upload_file_id is a valid uuid
  113. try:
  114. uuid.UUID(upload_file_id)
  115. except ValueError:
  116. raise ValueError("Invalid upload file id format")
  117. stmt = select(UploadFile).where(
  118. UploadFile.id == upload_file_id,
  119. UploadFile.tenant_id == tenant_id,
  120. )
  121. row = db.session.scalar(stmt)
  122. if row is None:
  123. raise ValueError("Invalid upload file")
  124. detected_file_type = _standardize_file_type(extension="." + row.extension, mime_type=row.mime_type)
  125. specified_type = mapping.get("type", "custom")
  126. if strict_type_validation and detected_file_type.value != specified_type:
  127. raise ValueError("Detected file type does not match the specified type. Please verify the file.")
  128. file_type = FileType(specified_type) if specified_type and specified_type != FileType.CUSTOM else detected_file_type
  129. return File(
  130. id=mapping.get("id"),
  131. filename=row.name,
  132. extension="." + row.extension,
  133. mime_type=row.mime_type,
  134. tenant_id=tenant_id,
  135. type=file_type,
  136. transfer_method=transfer_method,
  137. remote_url=row.source_url,
  138. related_id=mapping.get("upload_file_id"),
  139. size=row.size,
  140. storage_key=row.key,
  141. )
  142. def _build_from_remote_url(
  143. *,
  144. mapping: Mapping[str, Any],
  145. tenant_id: str,
  146. transfer_method: FileTransferMethod,
  147. strict_type_validation: bool = False,
  148. ) -> File:
  149. upload_file_id = mapping.get("upload_file_id")
  150. if upload_file_id:
  151. try:
  152. uuid.UUID(upload_file_id)
  153. except ValueError:
  154. raise ValueError("Invalid upload file id format")
  155. stmt = select(UploadFile).where(
  156. UploadFile.id == upload_file_id,
  157. UploadFile.tenant_id == tenant_id,
  158. )
  159. upload_file = db.session.scalar(stmt)
  160. if upload_file is None:
  161. raise ValueError("Invalid upload file")
  162. detected_file_type = _standardize_file_type(
  163. extension="." + upload_file.extension, mime_type=upload_file.mime_type
  164. )
  165. specified_type = mapping.get("type")
  166. if strict_type_validation and specified_type and detected_file_type.value != specified_type:
  167. raise ValueError("Detected file type does not match the specified type. Please verify the file.")
  168. file_type = (
  169. FileType(specified_type) if specified_type and specified_type != FileType.CUSTOM else detected_file_type
  170. )
  171. return File(
  172. id=mapping.get("id"),
  173. filename=upload_file.name,
  174. extension="." + upload_file.extension,
  175. mime_type=upload_file.mime_type,
  176. tenant_id=tenant_id,
  177. type=file_type,
  178. transfer_method=transfer_method,
  179. remote_url=helpers.get_signed_file_url(upload_file_id=str(upload_file_id)),
  180. related_id=mapping.get("upload_file_id"),
  181. size=upload_file.size,
  182. storage_key=upload_file.key,
  183. )
  184. url = mapping.get("url") or mapping.get("remote_url")
  185. if not url:
  186. raise ValueError("Invalid file url")
  187. mime_type, filename, file_size = _get_remote_file_info(url)
  188. extension = mimetypes.guess_extension(mime_type) or ("." + filename.split(".")[-1] if "." in filename else ".bin")
  189. file_type = _standardize_file_type(extension=extension, mime_type=mime_type)
  190. if file_type.value != mapping.get("type", "custom"):
  191. raise ValueError("Detected file type does not match the specified type. Please verify the file.")
  192. return File(
  193. id=mapping.get("id"),
  194. filename=filename,
  195. tenant_id=tenant_id,
  196. type=file_type,
  197. transfer_method=transfer_method,
  198. remote_url=url,
  199. mime_type=mime_type,
  200. extension=extension,
  201. size=file_size,
  202. storage_key="",
  203. )
  204. def _get_remote_file_info(url: str):
  205. file_size = -1
  206. filename = url.split("/")[-1].split("?")[0] or "unknown_file"
  207. mime_type = mimetypes.guess_type(filename)[0] or ""
  208. resp = ssrf_proxy.head(url, follow_redirects=True)
  209. resp = cast(httpx.Response, resp)
  210. if resp.status_code == httpx.codes.OK:
  211. if content_disposition := resp.headers.get("Content-Disposition"):
  212. filename = str(content_disposition.split("filename=")[-1].strip('"'))
  213. file_size = int(resp.headers.get("Content-Length", file_size))
  214. mime_type = mime_type or str(resp.headers.get("Content-Type", ""))
  215. return mime_type, filename, file_size
  216. def _build_from_tool_file(
  217. *,
  218. mapping: Mapping[str, Any],
  219. tenant_id: str,
  220. transfer_method: FileTransferMethod,
  221. strict_type_validation: bool = False,
  222. ) -> File:
  223. tool_file = (
  224. db.session.query(ToolFile)
  225. .filter(
  226. ToolFile.id == mapping.get("tool_file_id"),
  227. ToolFile.tenant_id == tenant_id,
  228. )
  229. .first()
  230. )
  231. if tool_file is None:
  232. raise ValueError(f"ToolFile {mapping.get('tool_file_id')} not found")
  233. extension = "." + tool_file.file_key.split(".")[-1] if "." in tool_file.file_key else ".bin"
  234. detected_file_type = _standardize_file_type(extension="." + extension, mime_type=tool_file.mimetype)
  235. specified_type = mapping.get("type")
  236. if strict_type_validation and specified_type and detected_file_type.value != specified_type:
  237. raise ValueError("Detected file type does not match the specified type. Please verify the file.")
  238. file_type = FileType(specified_type) if specified_type and specified_type != FileType.CUSTOM else detected_file_type
  239. return File(
  240. id=mapping.get("id"),
  241. tenant_id=tenant_id,
  242. filename=tool_file.name,
  243. type=file_type,
  244. transfer_method=transfer_method,
  245. remote_url=tool_file.original_url,
  246. related_id=tool_file.id,
  247. extension=extension,
  248. mime_type=tool_file.mimetype,
  249. size=tool_file.size,
  250. storage_key=tool_file.file_key,
  251. )
  252. def _is_file_valid_with_config(
  253. *,
  254. input_file_type: str,
  255. file_extension: str,
  256. file_transfer_method: FileTransferMethod,
  257. config: FileUploadConfig,
  258. ) -> bool:
  259. if (
  260. config.allowed_file_types
  261. and input_file_type not in config.allowed_file_types
  262. and input_file_type != FileType.CUSTOM
  263. ):
  264. return False
  265. if (
  266. input_file_type == FileType.CUSTOM
  267. and config.allowed_file_extensions is not None
  268. and file_extension not in config.allowed_file_extensions
  269. ):
  270. return False
  271. if input_file_type == FileType.IMAGE:
  272. if (
  273. config.image_config
  274. and config.image_config.transfer_methods
  275. and file_transfer_method not in config.image_config.transfer_methods
  276. ):
  277. return False
  278. elif config.allowed_file_upload_methods and file_transfer_method not in config.allowed_file_upload_methods:
  279. return False
  280. return True
  281. def _standardize_file_type(*, extension: str = "", mime_type: str = "") -> FileType:
  282. """
  283. Infer the possible actual type of the file based on the extension and mime_type
  284. """
  285. guessed_type = None
  286. if extension:
  287. guessed_type = _get_file_type_by_extension(extension)
  288. if guessed_type is None and mime_type:
  289. guessed_type = _get_file_type_by_mimetype(mime_type)
  290. return guessed_type or FileType.CUSTOM
  291. def _get_file_type_by_extension(extension: str) -> FileType | None:
  292. extension = extension.lstrip(".")
  293. if extension in IMAGE_EXTENSIONS:
  294. return FileType.IMAGE
  295. elif extension in VIDEO_EXTENSIONS:
  296. return FileType.VIDEO
  297. elif extension in AUDIO_EXTENSIONS:
  298. return FileType.AUDIO
  299. elif extension in DOCUMENT_EXTENSIONS:
  300. return FileType.DOCUMENT
  301. return None
  302. def _get_file_type_by_mimetype(mime_type: str) -> FileType | None:
  303. if "image" in mime_type:
  304. file_type = FileType.IMAGE
  305. elif "video" in mime_type:
  306. file_type = FileType.VIDEO
  307. elif "audio" in mime_type:
  308. file_type = FileType.AUDIO
  309. elif "text" in mime_type or "pdf" in mime_type:
  310. file_type = FileType.DOCUMENT
  311. else:
  312. file_type = FileType.CUSTOM
  313. return file_type
  314. def get_file_type_by_mime_type(mime_type: str) -> FileType:
  315. return _get_file_type_by_mimetype(mime_type) or FileType.CUSTOM
  316. class StorageKeyLoader:
  317. """FileKeyLoader load the storage key from database for a list of files.
  318. This loader is batched, the database query count is constant regardless of the input size.
  319. """
  320. def __init__(self, session: Session, tenant_id: str) -> None:
  321. self._session = session
  322. self._tenant_id = tenant_id
  323. def _load_upload_files(self, upload_file_ids: Sequence[uuid.UUID]) -> Mapping[uuid.UUID, UploadFile]:
  324. stmt = select(UploadFile).where(
  325. UploadFile.id.in_(upload_file_ids),
  326. UploadFile.tenant_id == self._tenant_id,
  327. )
  328. return {uuid.UUID(i.id): i for i in self._session.scalars(stmt)}
  329. def _load_tool_files(self, tool_file_ids: Sequence[uuid.UUID]) -> Mapping[uuid.UUID, ToolFile]:
  330. stmt = select(ToolFile).where(
  331. ToolFile.id.in_(tool_file_ids),
  332. ToolFile.tenant_id == self._tenant_id,
  333. )
  334. return {uuid.UUID(i.id): i for i in self._session.scalars(stmt)}
  335. def load_storage_keys(self, files: Sequence[File]):
  336. """Loads storage keys for a sequence of files by retrieving the corresponding
  337. `UploadFile` or `ToolFile` records from the database based on their transfer method.
  338. This method doesn't modify the input sequence structure but updates the `_storage_key`
  339. property of each file object by extracting the relevant key from its database record.
  340. Performance note: This is a batched operation where database query count remains constant
  341. regardless of input size. However, for optimal performance, input sequences should contain
  342. fewer than 1000 files. For larger collections, split into smaller batches and process each
  343. batch separately.
  344. """
  345. upload_file_ids: list[uuid.UUID] = []
  346. tool_file_ids: list[uuid.UUID] = []
  347. for file in files:
  348. related_model_id = file.related_id
  349. if file.related_id is None:
  350. raise ValueError("file id should not be None.")
  351. if file.tenant_id != self._tenant_id:
  352. err_msg = (
  353. f"invalid file, expected tenant_id={self._tenant_id}, "
  354. f"got tenant_id={file.tenant_id}, file_id={file.id}, related_model_id={related_model_id}"
  355. )
  356. raise ValueError(err_msg)
  357. model_id = uuid.UUID(related_model_id)
  358. if file.transfer_method in (FileTransferMethod.LOCAL_FILE, FileTransferMethod.REMOTE_URL):
  359. upload_file_ids.append(model_id)
  360. elif file.transfer_method == FileTransferMethod.TOOL_FILE:
  361. tool_file_ids.append(model_id)
  362. tool_files = self._load_tool_files(tool_file_ids)
  363. upload_files = self._load_upload_files(upload_file_ids)
  364. for file in files:
  365. model_id = uuid.UUID(file.related_id)
  366. if file.transfer_method in (FileTransferMethod.LOCAL_FILE, FileTransferMethod.REMOTE_URL):
  367. upload_file_row = upload_files.get(model_id)
  368. if upload_file_row is None:
  369. raise ValueError(f"Upload file not found for id: {model_id}")
  370. file._storage_key = upload_file_row.key
  371. elif file.transfer_method == FileTransferMethod.TOOL_FILE:
  372. tool_file_row = tool_files.get(model_id)
  373. if tool_file_row is None:
  374. raise ValueError(f"Tool file not found for id: {model_id}")
  375. file._storage_key = tool_file_row.file_key