Views
No views yet

pip install olmocr1import torch
2import base64
3import urllib.request
4
5from io import BytesIO
6from PIL import Image
7from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
8
9from olmocr.data.renderpdf import render_pdf_to_base64png
10from olmocr.prompts import build_finetuning_prompt
11from olmocr.prompts.anchor import get_anchor_text
12
13# Initialize the model
14model = Qwen2VLForConditionalGeneration.from_pretrained("allenai/olmOCR-7B-0225-preview", torch_dtype=torch.bfloat16).eval()
15processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
16device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17model.to(device)
18
19# Grab a sample PDF
20urllib.request.urlretrieve("https://molmo.allenai.org/paper.pdf", "./paper.pdf")
21
22# Render page 1 to an image
23image_base64 = render_pdf_to_base64png("./paper.pdf", 1, target_longest_image_dim=1024)
24
25# Build the prompt, using document metadata
26anchor_text = get_anchor_text("./paper.pdf", 1, pdf_engine="pdfreport", target_length=4000)
27prompt = build_finetuning_prompt(anchor_text)
28
29# Build the full prompt
30messages = [
31 {
32 "role": "user",
33 "content": [
34 {"type": "text", "text": prompt},
35 {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}},
36 ],
37 }
38 ]
39
40# Apply the chat template and processor
41text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
42main_image = Image.open(BytesIO(base64.b64decode(image_base64)))
43
44inputs = processor(
45 text=[text],
46 images=[main_image],
47 padding=True,
48 return_tensors="pt",
49)
50inputs = {key: value.to(device) for (key, value) in inputs.items()}
51
52
53# Generate the output
54output = model.generate(
55 **inputs,
56 temperature=0.8,
57 max_new_tokens=50,
58 num_return_sequences=1,
59 do_sample=True,
60 )
61
62# Decode the output
63prompt_length = inputs["input_ids"].shape[1]
64new_tokens = output[:, prompt_length:]
65text_output = processor.tokenizer.batch_decode(
66 new_tokens, skip_special_tokens=True
67)
68
69print(text_output)
70# ['{"primary_language":"en","is_rotation_valid":true,"rotation_correction":0,"is_table":false,"is_diagram":false,"natural_text":"Molmo and PixMo:\\nOpen Weights and Open Data\\nfor State-of-the']