Views
No views yet
1from transformers import pipeline
2
3question = "If you had a time machine, but could only go to the past or the future once and never return, which would you choose and why?"
4generator = pipeline("text-generation", model="aliRafik/invoices-donut-finetuned", device="cuda")
5output = generator([{"role": "user", "content": question}], max_new_tokens=128, return_full_text=False)[0]
6print(output["generated_text"])invoices-donut-finetuned-lora is a parameter-efficient fine-tuned version of numind/NuExtract-2.0-4B using LoRA adapters.
It was trained on the same dataset (katanaml-org/invoices-donut-data-v1) but only ~0.05% of parameters were updated via LoRA,
making it lighter and faster to train compared to the fully fine-tuned model.pip install transformers torch datasets pillow1from peft import PeftModel
2from transformers import AutoModelForVision2Seq, AutoProcessor
3
4base_model = "numind/NuExtract-2.0-4B"
5lora_model = "aliRafik/invoices-donut-finetuned-lora"
6
7model = AutoModelForVision2Seq.from_pretrained(
8 base_model,
9 trust_remote_code=True,
10 torch_dtype=torch.bfloat16,
11 attn_implementation="flash_attention_2",
12 device_map="auto"
13)
14
15# Load LoRA adapters
16model = PeftModel.from_pretrained(model, lora_model)
17
18processor = AutoProcessor.from_pretrained(
19 base_model,
20 trust_remote_code=True,
21 padding_side="left",
22 use_fast=True
23)1template = """
2{
3 "header": {
4 "invoice_no": "string",
5 "invoice_date": "date-time",
6 "seller": "string",
7 "client": "string",
8 "seller_tax_id": "string",
9 "client_tax_id": "string",
10 "iban": "string"
11 },
12 "items": [
13 {
14 "item_desc": "string",
15 "item_qty": "number",
16 "item_net_price": "number",
17 "item_net_worth": "number",
18 "item_vat": "number",
19 "item_gross_worth": "number"
20 }
21 ],
22 "summary": {
23 "total_net_worth": "number",
24 "total_vat": "number",
25 "total_gross_worth": "number"
26 }
27}
28"""1from datasets import load_dataset
2import json
3from qwen_vl_utils import process_vision_info
4
5# Load the dataset
6dataset = load_dataset("katanaml-org/invoices-donut-data-v1")
7
8# Select a sample (e.g., index 0)
9sample = dataset['train'][0]
10image = sample['image']
11ground_truth = sample['ground_truth']
12
13print(json.loads(ground_truth))
14
15# Prepare message
16messages = [
17 {"role": "user", "content": [{"type": "image", "image": image}]}
18]
19
20# Process vision info
21image_inputs, _ = process_vision_info(messages)
22
23# Apply chat template
24text = processor.tokenizer.apply_chat_template(
25 messages,
26 template=template,
27 tokenize=False,
28 add_generation_prompt=True
29)
30
31# Prepare inputs
32inputs = processor(
33 text=[text],
34 images=image_inputs,
35 padding=True,
36 return_tensors="pt"
37).to(model.device)
38
39# Generation config
40generation_config = {
41 "do_sample": False,
42 "num_beams": 1,
43 "max_new_tokens": 2048
44}
45
46# Generate
47generated_ids = model.generate(**inputs, **generation_config)
48generated_ids_trimmed = [
49 out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
50]
51
52output_text = processor.batch_decode(
53 generated_ids_trimmed,
54 skip_special_tokens=True,
55 clean_up_tokenization_spaces=False
56)
57
58# Parse and print
59try:
60 extracted_data = json.loads(output_text[0])
61 print("Extracted Data:", extracted_data)
62except json.JSONDecodeError:
63 print("Raw Output:", output_text[0])
64
65# Compare with ground truth
66gt_parsed = json.loads(ground_truth)['gt_parse']
67print("Ground Truth:", gt_parsed)
68
691from PIL import Image
2from io import BytesIO
3import requests
4
5# Load from local path
6image_path = "/content/image.jpg" # Replace with your path
7image = Image.open(image_path)
8
9# Or load from URL
10# image_url = "https://example.com/your_invoice.jpg"
11# response = requests.get(image_url)
12# image = Image.open(BytesIO(response.content))
13
14# Use same inference code as above
15
161
2{
3 "header": {
4 "invoice_no": "49565075",
5 "invoice_date": "2019-10-28",
6 "seller": "Kane-Morgan 968 Carr Mission Apt. 320 Bernardville, VA 28211",
7 "client": "Garcia Inc 445 Haas Viaduct Suite 454 Michaelhaven, LA 32852",
8 "seller_tax_id": "964-95-3813",
9 "client_tax_id": "909-75-5482",
10 "iban": "GB73WCJ55232646970614"
11 },
12 "items": [
13 {
14 "item_desc": "Anthropologie Gold Elegant Swan Decorative Metal Bottle Stopper Wine Saver",
15 "item_qty": 3.0,
16 "item_net_price": 19.98,
17 "item_net_worth": 59.94,
18 "item_vat": 10.0,
19 "item_gross_worth": 65.93
20 },
21 {
22 "item_desc": "Lolita Happy Retirement Wine Glass 15 Ounce GLS11-5534H",
23 "item_qty": 1.0,
24 "item_net_price": 8.0,
25 "item_net_worth": 8.0,
26 "item_vat": 10.0,
27 "item_gross_worth": 8.8
28 },
29 {
30 "item_desc": "Lolita \"Congratulations\" Hand Painted and Decorated Wine Glass NIB",
31 "item_qty": 1.0,
32 "item_net_price": 20.0,
33 "item_net_worth": 20.0,
34 "item_vat": 10.0,
35 "item_gross_worth": 22.0
36 }
37 ],
38 "summary": {
39 "total_net_worth": 87.94,
40 "total_vat": 8.79,
41 "total_gross_worth": 96.73
42 }
43}
441@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}