您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

file_factory.py 16KB

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