instructor
65 строк · 1.8 Кб
1import instructor2from openai import OpenAI3from pydantic import BaseModel4import base645
6client = instructor.from_openai(OpenAI(), mode=instructor.Mode.MD_JSON)7
8
9class Circle(BaseModel):10x: int11y: int12color: str13
14
15def encode_image(image_path):16with open(image_path, "rb") as image_file:17return base64.b64encode(image_file.read()).decode("utf-8")18
19
20def draw_circle(image_size, num_circles, path):21from PIL import Image, ImageDraw22import random23
24image = Image.new("RGB", image_size, "white")25
26draw = ImageDraw.Draw(image)27for _ in range(num_circles):28# Randomize the circle properties29radius = 100 # random.randint(10, min(image_size)//5) # Radius between 10 and 1/5th of the smallest dimension30x = random.randint(radius, image_size[0] - radius)31y = random.randint(radius, image_size[1] - radius)32color = ["red", "black", "blue", "green"][random.randint(0, 3)]33
34circle_position = (x - radius, y - radius, x + radius, y + radius)35print(f"Generating circle at {x, y} with color {color}")36draw.ellipse(circle_position, fill=color, outline="black")37
38image.save(path)39
40
41img_path = "circle.jpg"42draw_circle((1024, 1024), 1, img_path)43base64_image = encode_image(img_path)44
45response = client.chat.completions.create(46model="gpt-4-vision-preview",47max_tokens=1800,48response_model=Circle,49messages=[50{51"role": "user",52"content": [53{"type": "text", "text": "find the circle"},54{55"type": "image_url",56"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},57},58],59}60],61)
62
63print(64f"Found circle with center at x: {response.x}, y: {response.y} and color: {response.color}"65)
66