Views
No views yet
1import torch
2from transformers import AutoProcessor, AutoModelForImageTextToText
3from PIL import Image
4import requests
5
6# 1) Load fine-tuned model and processor
7model_id = "berkeruveyik/smolvlm2-256m-FoodExtract-Vision-v2-without-peft" # Replace with your model ID
8
9print("Loading model and processor...")
10processor = AutoProcessor.from_pretrained(model_id)
11model = AutoModelForImageTextToText.from_pretrained(
12 model_id,
13 torch_dtype=torch.bfloat16,
14 device_map="auto",
15)
16model.eval()
17print("Model ready!")
18
19# 2) Prompts
20SYSTEM_MESSAGE = """You are an expert food and drink image extractor.
21You provide structured data to visual inputs classifying them as edible food/drink or not.
22as well as titling the image with a simple simple food/drink related caption.
23Finally you extract any and all visible food/drink items to lists."""
24
25USER_PROMPT = """Classify the given input image into food or not, and if edible food or drink items are present, extract them into lists. If no food/drink items are visible, return an empty list.
26
27Only return valid JSON in the following form:
28
29```json
30{
31 "is_food": 0,
32 "image_title": "",
33 "food_items": [],
34 "drink_items": []
35}
36```"""
37
38# 3) Load image
39image_url = "https://img.freepik.com/free-psd/roasted-chicken-dinner-platter-delicious-feast_632498-25445.jpg"
40
41print(f"\nLoading image from: {image_url}")
42resp = requests.get(image_url, stream=True, headers={"User-Agent": "Mozilla/5.0"})
43resp.raise_for_status()
44image = Image.open(resp.raw).convert("RGB")
45
46# 4) Prepare inputs
47messages = [
48 {
49 "role": "user",
50 "content": [
51 {"type": "image", "image": image},
52 {"type": "text", "text": SYSTEM_MESSAGE + "\n\n" + USER_PROMPT},
53 ],
54 }
55]
56
57text = processor.apply_chat_template(
58 messages,
59 add_generation_prompt=True,
60 tokenize=False,
61)
62
63inputs = processor(
64 text=text,
65 images=image,
66 return_tensors="pt",
67)
68
69# Move tensors to model device and dtype
70inputs = {k: v.to(model.device) for k, v in inputs.items()}
71inputs = {
72 k: (v.to(dtype=model.dtype) if torch.is_floating_point(v) and v.dtype == torch.float32 else v)
73 for k, v in inputs.items()
74}
75
76# 5) Generate
77print("\nGenerating output...")
78with torch.no_grad():
79 generated_ids = model.generate(**inputs, max_new_tokens=256, do_sample=False)
80
81# 6) Decode only the newly generated tokens
82prompt_len = inputs["input_ids"].shape[1]
83output_text = processor.batch_decode(
84 generated_ids[:, prompt_len:],
85 skip_special_tokens=True
86)[0]
87
88print("\n" + "="*60)
89print("OUTPUT:")
90print("="*60)
91print(output_text)
92print("="*60)1@misc{vonwerra2022trl,
2 title = {{TRL: Transformer Reinforcement Learning}},
3 author = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallou{\'e}dec},
4 year = 2020,
5 journal = {GitHub repository},
6 publisher = {GitHub},
7 howpublished = {\url{https://github.com/huggingface/trl}}
8}