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

file_factory.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 constants import AUDIO_EXTENSIONS, DOCUMENT_EXTENSIONS, IMAGE_EXTENSIONS, VIDEO_EXTENSIONS
  8. from core.file import File, FileBelongsTo, FileTransferMethod, FileType, FileUploadConfig, helpers
  9. from core.helper import ssrf_proxy
  10. from extensions.ext_database import db
  11. from models import MessageFile, ToolFile, UploadFile
  12. def build_from_message_files(
  13. *,
  14. message_files: Sequence["MessageFile"],
  15. tenant_id: str,
  16. config: FileUploadConfig,
  17. ) -> Sequence[File]:
  18. results = [
  19. build_from_message_file(message_file=file, tenant_id=tenant_id, config=config)
  20. for file in message_files
  21. if file.belongs_to != FileBelongsTo.ASSISTANT
  22. ]
  23. return results
  24. def build_from_message_file(
  25. *,
  26. message_file: "MessageFile",
  27. tenant_id: str,
  28. config: FileUploadConfig,
  29. ):
  30. mapping = {
  31. "transfer_method": message_file.transfer_method,
  32. "url": message_file.url,
  33. "id": message_file.id,
  34. "type": message_file.type,
  35. "upload_file_id": message_file.upload_file_id,
  36. }
  37. return build_from_mapping(
  38. mapping=mapping,
  39. tenant_id=tenant_id,
  40. config=config,
  41. )
  42. def build_from_mapping(
  43. *,
  44. mapping: Mapping[str, Any],
  45. tenant_id: str,
  46. config: FileUploadConfig | None = None,
  47. ) -> File:
  48. transfer_method = FileTransferMethod.value_of(mapping.get("transfer_method"))
  49. build_functions: dict[FileTransferMethod, Callable] = {
  50. FileTransferMethod.LOCAL_FILE: _build_from_local_file,
  51. FileTransferMethod.REMOTE_URL: _build_from_remote_url,
  52. FileTransferMethod.TOOL_FILE: _build_from_tool_file,
  53. }
  54. build_func = build_functions.get(transfer_method)
  55. if not build_func:
  56. raise ValueError(f"Invalid file transfer method: {transfer_method}")
  57. file: File = build_func(
  58. mapping=mapping,
  59. tenant_id=tenant_id,
  60. transfer_method=transfer_method,
  61. )
  62. if config and not _is_file_valid_with_config(
  63. input_file_type=mapping.get("type", FileType.CUSTOM),
  64. file_extension=file.extension or "",
  65. file_transfer_method=file.transfer_method,
  66. config=config,
  67. ):
  68. raise ValueError(f"File validation failed for file: {file.filename}")
  69. return file
  70. def build_from_mappings(
  71. *,
  72. mappings: Sequence[Mapping[str, Any]],
  73. config: FileUploadConfig | None = None,
  74. tenant_id: str,
  75. ) -> Sequence[File]:
  76. files = [
  77. build_from_mapping(
  78. mapping=mapping,
  79. tenant_id=tenant_id,
  80. config=config,
  81. )
  82. for mapping in mappings
  83. ]
  84. if (
  85. config
  86. # If image config is set.
  87. and config.image_config
  88. # And the number of image files exceeds the maximum limit
  89. and sum(1 for _ in (filter(lambda x: x.type == FileType.IMAGE, files))) > config.image_config.number_limits
  90. ):
  91. raise ValueError(f"Number of image files exceeds the maximum limit {config.image_config.number_limits}")
  92. if config and config.number_limits and len(files) > config.number_limits:
  93. raise ValueError(f"Number of files exceeds the maximum limit {config.number_limits}")
  94. return files
  95. def _build_from_local_file(
  96. *,
  97. mapping: Mapping[str, Any],
  98. tenant_id: str,
  99. transfer_method: FileTransferMethod,
  100. ) -> File:
  101. upload_file_id = mapping.get("upload_file_id")
  102. if not upload_file_id:
  103. raise ValueError("Invalid upload file id")
  104. # check if upload_file_id is a valid uuid
  105. try:
  106. uuid.UUID(upload_file_id)
  107. except ValueError:
  108. raise ValueError("Invalid upload file id format")
  109. stmt = select(UploadFile).where(
  110. UploadFile.id == upload_file_id,
  111. UploadFile.tenant_id == tenant_id,
  112. )
  113. row = db.session.scalar(stmt)
  114. if row is None:
  115. raise ValueError("Invalid upload file")
  116. file_type = _standardize_file_type(extension="." + row.extension, mime_type=row.mime_type)
  117. if file_type.value != mapping.get("type", "custom"):
  118. raise ValueError("Detected file type does not match the specified type. Please verify the file.")
  119. return File(
  120. id=mapping.get("id"),
  121. filename=row.name,
  122. extension="." + row.extension,
  123. mime_type=row.mime_type,
  124. tenant_id=tenant_id,
  125. type=file_type,
  126. transfer_method=transfer_method,
  127. remote_url=row.source_url,
  128. related_id=mapping.get("upload_file_id"),
  129. size=row.size,
  130. storage_key=row.key,
  131. )
  132. def _build_from_remote_url(
  133. *,
  134. mapping: Mapping[str, Any],
  135. tenant_id: str,
  136. transfer_method: FileTransferMethod,
  137. ) -> File:
  138. upload_file_id = mapping.get("upload_file_id")
  139. if upload_file_id:
  140. try:
  141. uuid.UUID(upload_file_id)
  142. except ValueError:
  143. raise ValueError("Invalid upload file id format")
  144. stmt = select(UploadFile).where(
  145. UploadFile.id == upload_file_id,
  146. UploadFile.tenant_id == tenant_id,
  147. )
  148. upload_file = db.session.scalar(stmt)
  149. if upload_file is None:
  150. raise ValueError("Invalid upload file")
  151. file_type = _standardize_file_type(extension="." + upload_file.extension, mime_type=upload_file.mime_type)
  152. if file_type.value != mapping.get("type", "custom"):
  153. raise ValueError("Detected file type does not match the specified type. Please verify the file.")
  154. return File(
  155. id=mapping.get("id"),
  156. filename=upload_file.name,
  157. extension="." + upload_file.extension,
  158. mime_type=upload_file.mime_type,
  159. tenant_id=tenant_id,
  160. type=file_type,
  161. transfer_method=transfer_method,
  162. remote_url=helpers.get_signed_file_url(upload_file_id=str(upload_file_id)),
  163. related_id=mapping.get("upload_file_id"),
  164. size=upload_file.size,
  165. storage_key=upload_file.key,
  166. )
  167. url = mapping.get("url") or mapping.get("remote_url")
  168. if not url:
  169. raise ValueError("Invalid file url")
  170. mime_type, filename, file_size = _get_remote_file_info(url)
  171. extension = mimetypes.guess_extension(mime_type) or ("." + filename.split(".")[-1] if "." in filename else ".bin")
  172. file_type = _standardize_file_type(extension=extension, mime_type=mime_type)
  173. if file_type.value != mapping.get("type", "custom"):
  174. raise ValueError("Detected file type does not match the specified type. Please verify the file.")
  175. return File(
  176. id=mapping.get("id"),
  177. filename=filename,
  178. tenant_id=tenant_id,
  179. type=file_type,
  180. transfer_method=transfer_method,
  181. remote_url=url,
  182. mime_type=mime_type,
  183. extension=extension,
  184. size=file_size,
  185. storage_key="",
  186. )
  187. def _get_remote_file_info(url: str):
  188. file_size = -1
  189. filename = url.split("/")[-1].split("?")[0] or "unknown_file"
  190. mime_type = mimetypes.guess_type(filename)[0] or ""
  191. resp = ssrf_proxy.head(url, follow_redirects=True)
  192. resp = cast(httpx.Response, resp)
  193. if resp.status_code == httpx.codes.OK:
  194. if content_disposition := resp.headers.get("Content-Disposition"):
  195. filename = str(content_disposition.split("filename=")[-1].strip('"'))
  196. file_size = int(resp.headers.get("Content-Length", file_size))
  197. mime_type = mime_type or str(resp.headers.get("Content-Type", ""))
  198. return mime_type, filename, file_size
  199. def _build_from_tool_file(
  200. *,
  201. mapping: Mapping[str, Any],
  202. tenant_id: str,
  203. transfer_method: FileTransferMethod,
  204. ) -> File:
  205. tool_file = (
  206. db.session.query(ToolFile)
  207. .filter(
  208. ToolFile.id == mapping.get("tool_file_id"),
  209. ToolFile.tenant_id == tenant_id,
  210. )
  211. .first()
  212. )
  213. if tool_file is None:
  214. raise ValueError(f"ToolFile {mapping.get('tool_file_id')} not found")
  215. extension = "." + tool_file.file_key.split(".")[-1] if "." in tool_file.file_key else ".bin"
  216. file_type = _standardize_file_type(extension=extension, mime_type=tool_file.mimetype)
  217. if file_type.value != mapping.get("type", "custom"):
  218. raise ValueError("Detected file type does not match the specified type. Please verify the file.")
  219. return File(
  220. id=mapping.get("id"),
  221. tenant_id=tenant_id,
  222. filename=tool_file.name,
  223. type=file_type,
  224. transfer_method=transfer_method,
  225. remote_url=tool_file.original_url,
  226. related_id=tool_file.id,
  227. extension=extension,
  228. mime_type=tool_file.mimetype,
  229. size=tool_file.size,
  230. storage_key=tool_file.file_key,
  231. )
  232. def _is_file_valid_with_config(
  233. *,
  234. input_file_type: str,
  235. file_extension: str,
  236. file_transfer_method: FileTransferMethod,
  237. config: FileUploadConfig,
  238. ) -> bool:
  239. if (
  240. config.allowed_file_types
  241. and input_file_type not in config.allowed_file_types
  242. and input_file_type != FileType.CUSTOM
  243. ):
  244. return False
  245. if (
  246. input_file_type == FileType.CUSTOM
  247. and config.allowed_file_extensions is not None
  248. and file_extension not in config.allowed_file_extensions
  249. ):
  250. return False
  251. if input_file_type == FileType.IMAGE:
  252. if (
  253. config.image_config
  254. and config.image_config.transfer_methods
  255. and file_transfer_method not in config.image_config.transfer_methods
  256. ):
  257. return False
  258. elif config.allowed_file_upload_methods and file_transfer_method not in config.allowed_file_upload_methods:
  259. return False
  260. return True
  261. def _standardize_file_type(*, extension: str = "", mime_type: str = "") -> FileType:
  262. """
  263. Infer the possible actual type of the file based on the extension and mime_type
  264. """
  265. guessed_type = None
  266. if extension:
  267. guessed_type = _get_file_type_by_extension(extension)
  268. if guessed_type is None and mime_type:
  269. guessed_type = _get_file_type_by_mimetype(mime_type)
  270. return guessed_type or FileType.CUSTOM
  271. def _get_file_type_by_extension(extension: str) -> FileType | None:
  272. extension = extension.lstrip(".")
  273. if extension in IMAGE_EXTENSIONS:
  274. return FileType.IMAGE
  275. elif extension in VIDEO_EXTENSIONS:
  276. return FileType.VIDEO
  277. elif extension in AUDIO_EXTENSIONS:
  278. return FileType.AUDIO
  279. elif extension in DOCUMENT_EXTENSIONS:
  280. return FileType.DOCUMENT
  281. return None
  282. def _get_file_type_by_mimetype(mime_type: str) -> FileType | None:
  283. if "image" in mime_type:
  284. file_type = FileType.IMAGE
  285. elif "video" in mime_type:
  286. file_type = FileType.VIDEO
  287. elif "audio" in mime_type:
  288. file_type = FileType.AUDIO
  289. elif "text" in mime_type or "pdf" in mime_type:
  290. file_type = FileType.DOCUMENT
  291. else:
  292. file_type = FileType.CUSTOM
  293. return file_type
  294. def get_file_type_by_mime_type(mime_type: str) -> FileType:
  295. return _get_file_type_by_mimetype(mime_type) or FileType.CUSTOM