import os
from html import escape
from perceptron import Client, image
client = Client(api_key=os.environ["PERCEPTRON_API_KEY"])
asset_base = (
"https://raw.githubusercontent.com/perceptron-ai-inc/perceptron/"
"main/cookbook/_shared/assets/in-context-learning/multi"
)
cat_reference = {
"url": f"{asset_base}/classA.jpg",
"label": "cat",
"box": (316, 136, 703, 906),
}
dog_reference = {
"url": f"{asset_base}/classB.webp",
"label": "dog",
"box": (161, 48, 666, 980),
}
target_url = f"{asset_base}/cat_dog_input.png"
def detect_from_examples(examples, target_url):
content = [{"type": "text", "text": (
"The following images and box annotations are labeled references. "
"Use them to recognize the same classes in the final target image."
)}]
for asset_idx, example in enumerate(examples):
x1, y1, x2, y2 = example["box"]
label = escape(example["label"], quote=True)
content.extend([
image(example["url"]),
{"type": "text", "text": (
f'Reference: <point_box mention="{label}" asset_idx="{asset_idx}"> '
f"({x1},{y1}) ({x2},{y2}) </point_box>"
)},
])
target_idx = len(examples)
content.extend([
image(target_url),
{"type": "text", "text": (
f"This is the target image, asset_idx={target_idx}. "
"Find all visible instances of the reference classes here. "
"Return flat point_box annotations, without collections, using the reference labels and "
f"asset_idx={target_idx}, with normalized 0–1000 coordinates. "
"Do not annotate the reference images. Do not assume every class "
"is present; say when no matching object is visible."
)},
])
response = client.chat.completions.create(
model="perceptron-mk1.5",
messages=[{"role": "user", "content": content}],
reasoning_effort="high",
max_completion_tokens=2048,
vision_config={"annotation_format": "box"},
)
choice = response.choices[0]
if choice.finish_reason != "stop":
raise RuntimeError(f"Incomplete detection answer: {choice.finish_reason}")
return choice.message.content or ""
print("One reference:")
print(detect_from_examples([dog_reference], target_url))
print("Multiple classes:")
print(detect_from_examples([cat_reference, dog_reference], target_url))