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

upload_file_parser.py 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import base64
  2. import logging
  3. import time
  4. from typing import Optional
  5. from configs import dify_config
  6. from constants import IMAGE_EXTENSIONS
  7. from core.helper.url_signer import UrlSigner
  8. from extensions.ext_storage import storage
  9. class UploadFileParser:
  10. @classmethod
  11. def get_image_data(cls, upload_file, force_url: bool = False) -> Optional[str]:
  12. if not upload_file:
  13. return None
  14. if upload_file.extension not in IMAGE_EXTENSIONS:
  15. return None
  16. if dify_config.MULTIMODAL_SEND_FORMAT == "url" or force_url:
  17. return cls.get_signed_temp_image_url(upload_file.id)
  18. else:
  19. # get image file base64
  20. try:
  21. data = storage.load(upload_file.key)
  22. except FileNotFoundError:
  23. logging.exception(f"File not found: {upload_file.key}")
  24. return None
  25. encoded_string = base64.b64encode(data).decode("utf-8")
  26. return f"data:{upload_file.mime_type};base64,{encoded_string}"
  27. @classmethod
  28. def get_signed_temp_image_url(cls, upload_file_id) -> str:
  29. """
  30. get signed url from upload file
  31. :param upload_file: UploadFile object
  32. :return:
  33. """
  34. base_url = dify_config.FILES_URL
  35. image_preview_url = f"{base_url}/files/{upload_file_id}/image-preview"
  36. return UrlSigner.get_signed_url(url=image_preview_url, sign_key=upload_file_id, prefix="image-preview")
  37. @classmethod
  38. def verify_image_file_signature(cls, upload_file_id: str, timestamp: str, nonce: str, sign: str) -> bool:
  39. """
  40. verify signature
  41. :param upload_file_id: file id
  42. :param timestamp: timestamp
  43. :param nonce: nonce
  44. :param sign: signature
  45. :return:
  46. """
  47. result = UrlSigner.verify(
  48. sign_key=upload_file_id, timestamp=timestamp, nonce=nonce, sign=sign, prefix="image-preview"
  49. )
  50. # verify signature
  51. if not result:
  52. return False
  53. current_time = int(time.time())
  54. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT