Skip to content

Commit 274c194

Browse files
committed
Use document route on batched image inference
1 parent 95c23be commit 274c194

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

vlmrun/client/predictions.py

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,15 @@
22

33
from __future__ import annotations
44
import json
5+
import tempfile
6+
import contextlib
57
from pathlib import Path
6-
from typing import List, Optional, Union
8+
from typing import List, Optional, Union, Generator
79
from PIL import Image
810
from loguru import logger
911

1012
import time
13+
from vlmrun.common.utils import remote_image
1114
from vlmrun.common.image import encode_image, _open_image_with_exif
1215
from vlmrun.client.base_requestor import APIRequestor
1316
from vlmrun.types.abstract import VLMRunProtocol
@@ -25,6 +28,35 @@
2528
from cachetools.keys import hashkey
2629

2730

31+
@contextlib.contextmanager
32+
def image_path_ctx(
33+
image: Image.Image | None = None,
34+
url: str | None = None,
35+
) -> Generator[Path, None, None]:
36+
"""Context manager to handle temporary image paths.
37+
38+
Args:
39+
image: PIL Image object
40+
url: URL of the image
41+
42+
Yields:
43+
str: Path to the temporary image file
44+
"""
45+
if not url and not image:
46+
raise ValueError("Either `image` or `url` must be provided")
47+
if url and image:
48+
raise ValueError("Cannot provide both `image` and `url`")
49+
50+
# Download the image from the URL if provided
51+
if url:
52+
image: Image.Image = remote_image(url)
53+
54+
# Save the image to a temporary file, and yield the path
55+
with tempfile.NamedTemporaryFile(suffix=".jpg") as temp_file:
56+
image.save(temp_file.name, format="JPEG", quality=98)
57+
yield Path(temp_file.name)
58+
59+
2860
@cachetools.cached(
2961
cache=cachetools.TTLCache(maxsize=100, ttl=3600),
3062
key=lambda _client, domain, config: hashkey(
@@ -292,6 +324,22 @@ def generate(
292324
raise ValueError("Either `images` or `urls` must be provided")
293325
if images and urls:
294326
raise ValueError("Only one of `images` or `urls` can be provided")
327+
if batch and len(images) > 1:
328+
raise ValueError("Batch mode only supports one image")
329+
330+
if batch:
331+
assert len(images) == 1, "Batch mode only supports one image"
332+
with image_path_ctx(image=images[0]) as image_path:
333+
return self._client.document.generate(
334+
file=image_path,
335+
model=model,
336+
domain=domain,
337+
batch=batch,
338+
config=config,
339+
metadata=metadata,
340+
callback_url=callback_url,
341+
autocast=autocast,
342+
)
295343

296344
if images:
297345
# Check if all images are of the same type

vlmrun/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "0.2.19"
1+
__version__ = "0.2.20"

0 commit comments

Comments
 (0)