dspy.Image
dspy.Image
dspy.Image는 이미지를 생성하는 DSPy 타입입니다. HTTP(S)/GS URL, 인코딩된 데이터 URI, raw bytes, PIL.Image.Image, 또는 단일 {"url": value} 항목의 딕셔너리(legacy)를 소스로 받을 수 있습니다.
출처: 문서
본문
dspy.Image(source: Any = None, /, *, download: Any = _UNSET, verify: Any = _UNSET, **data)
- Bases:
Type
이미지를 생성합니다.
Parameters
source: 위치 전용(positional-only) 이미지 소스. 지원되는 값은 다음과 같습니다:
str: HTTP(S)/GS URL 또는 인코딩된 데이터 URIbytes: 원시 이미지 bytesPIL.Image.Image: PIL 이미지 인스턴스dict: 단일{"url": value}항목 (legacy 형식)- 이미 인코딩된 데이터 URI
download, verify: Deprecated. 원격 이미지를 다운로드하려면 from_url(이 verify를 받음)을, 로컬 파일은 from_path를 사용하세요. 경고와 함께 한 릴리스 동안만 허용됩니다. download=True는 HTTP(S) source를 즉시 가져옵니다.
추가 키워드 인자는 pydantic.BaseModel에 전달됩니다.
일반 생성은 파일시스템이나 네트워크에 절대 접촉하지 않습니다. 로컬 파일과 원격 리소스는 반드시 from_path와 from_url로 명시적으로 불러와야 합니다. deprecated된 위치 인자 호출 Image(url, download=True)도 다운로드를 수행합니다.
def __init__(self, source: Any = None, /, *, download: Any = _UNSET, verify: Any = _UNSET, **data):
"""Create an Image.
Parameters
----------
source:
The positional-only image source. Supported values include
- ``str``: HTTP(S)/GS URL or an encoded data URI
- ``bytes``: raw image bytes
- ``PIL.Image.Image``: a PIL image instance
- ``dict`` with a single ``{"url": value}`` entry (legacy form)
- already encoded data URI
download, verify:
Deprecated. Use :meth:`from_url` (which accepts ``verify``) to download a
remote image, or :meth:`from_path` for a local file. Accepted for one release
with a warning: ``download=True`` eagerly fetches an HTTP(S) ``source``.
Any additional keyword arguments are passed to :class:`pydantic.BaseModel`.
Ordinary construction never touches the filesystem or network. Local files and remote
resources must be loaded explicitly with :meth:`from_path` and :meth:`from_url`. The
deprecated positional ``Image(url, download=True)`` compatibility call also downloads.
"""
download_requested = download is not _UNSET
verify_requested = verify is not _UNSET
if (download_requested or verify_requested) and source is None:
# `download`/`verify` are a compatibility shim for the positional constructor
# `Image(url, download=True)`. They must never be honored through the validation
# path: pydantic routes dict data into `__init__`, so an untrusted value such as
# `{"url": "http://169.254.169.254/...", "download": true}` would otherwise trigger
# a server-side fetch during output parsing. Requiring a positional source keeps the
# shim reachable only from direct developer construction.
raise TypeError(
"`download` and `verify` are only valid with a positional image source; "
"use Image.from_url(url, verify=...) to download a remote image."
)
...
소스 코드는 dspy/adapters/types/image.py에 있습니다.
Methods
from_path(file_path: str) -> Image (classmethod)
로컬 파일을 읽어 데이터 URI로 인코딩합니다. 파일이 없으면 ValueError("File not found: ...")를 발생시킵니다.
from_url(url, verify=True, timeout=30.0) -> Image (classmethod)
HTTP(S) 리소스를 다운로드해 데이터 URI로 인코딩합니다.
보안: 이 메서드는 명시적이고 호출자가 시작한 fetch를 수행하며, HTTP(S) 스킴을 요구하는 것 외에 SSRF 보호를 적용하지 않습니다.
requests.get처럼 private·loopback·cloud-metadata 호스트에 도달하고 그쪽으로 리다이렉트를 따라갑니다.url이 신뢰할 수 없는 입력에서 비롯된 경우 호출 전에 호스트를 allowlist에 대해 검증해야 합니다.
from_PIL(pil_image) (classmethod)
Image.from_PIL은 deprecated이며 3.4에서 제거될 예정입니다. Image(pil_image)를 사용하세요.
from_file(file_path: str) -> Image (classmethod)
from_path의 deprecated 별칭입니다. 3.4에서 제거될 예정이며 Image.from_path를 사용하세요.
format() -> list[dict[str, Any]] | str
이미지를 DSPy에 맞게 포맷합니다. encode_image(self.url)로 인코딩해 {"type": "image_url", "image_url": {"url": ...}} 리스트를 반환합니다.
표준 상속 메서드
adapt_to_native_lm_feature(...), extract_custom_type_from_annotation(annotation), description(), serialize_model(), parse_lm_response(...), parse_stream_chunk(...), is_streamable() 등은 모든 커스텀 타입이 공유하는 base_type.py의 표준 메서드입니다.