Views
No views yet
1from transformers import AutoModelForImageTextToText, AutoProcessor, BitsAndBytesConfig
2from PIL import Image
3import requests
4import torch
5from io import BytesIO
6
7
8model_id = "Ak137/granite-docling-258M-finetuned"
9
10model = AutoModelForImageTextToText.from_pretrained(
11 model_id,
12 device_map='cuda',
13 attn_implementation="flash_attention_2",
14 dtype=torch.bfloat16
15)
16processor = AutoProcessor.from_pretrained(model_id)
17
18
19def generate_text_from_sample(model, processor, sample, max_new_tokens=40):
20 prompt = processor.apply_chat_template(sample["prompt"], add_generation_prompt=True)
21 inputs = processor(text=prompt, images=sample["images"], return_tensors="pt")
22 inputs = inputs.to(model.device)
23
24 outputs = model.generate(**inputs, max_new_tokens=max_new_tokens)
25 return (processor.decode(outputs[0][inputs["input_ids"].shape[-1]:]))
26
27
28user_prompt = "Convert this document to docling format"
29
30url = "https://blogs.loc.gov/law/files/2020/01/sld-misc-image-1.jpg"
31response = requests.get(url)
32img = Image.open(BytesIO(response.content))
33if img.mode != 'RGB':
34 img = img.convert('RGB')
35
36example = {
37 "images": [img],
38 "prompt":
39 [
40 { 'role': 'user',
41 'content':
42 [
43 {'type': 'image'},
44 {'text': user_prompt, 'type': 'text'}
45 ],
46 }
47 ],
48 }
49
50
51res = generate_text_from_sample(model, processor, sample=example, max_new_tokens=120)
52print(res)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}