Views
No views yet
pip install transformers torch pillow1from transformers import AutoProcessor, AutoModelForVision2Seq
2from PIL import Image
3import torch
4
5# Load model and processor
6model = AutoModelForVision2Seq.from_pretrained("sabaridsnfuji/Japanese-Receipt-VL-lfm2-450M")
7processor = AutoProcessor.from_pretrained("sabaridsnfuji/Japanese-Receipt-VL-lfm2-450M")
8
9# Load receipt image
10image = Image.open("japanese_receipt.jpg")
11
12# System prompt for structured extraction
13system_prompt = """You are an intelligent document parser. Read the following Japanese receipt and extract every piece of information exactly as it appears, and present it in a well-structured JSON format using Japanese keys and values.
14
15Please strictly follow these rules:
16
17Only extract information that is actually present on the receipt. Do not include any missing, blank, or inferred fields.
18
19Do not summarize, omit, translate, or modify any part of the receipt. Every character, number, symbol, and line must be retained exactly as printed.
20
21Extract all available content including but not limited to: store details, receipt number, date, time, cashier name, product list, prices, tax breakdowns, payment details, receipt bags, barcodes, notices, and any footer messages.
22
23Preserve original formatting such as line breaks, symbols, and full-width characters (hiragana, katakana, kanji, numbers, etc.).
24
25Do not perform any translation, correction, interpretation, or reformatting of content. Use only what is present.
26
27Output the result in JSON format, using Japanese field names as keys."""
28
29# Prepare conversation format
30messages = [
31 {
32 'role': 'system',
33 'content': [{'type': 'text', 'text': system_prompt}]
34 },
35 {
36 'role': 'user',
37 'content': [
38 {'type': 'text', 'text': 'Please parse this Japanese receipt.'},
39 {'type': 'image', 'image': image}
40 ]
41 }
42]
43
44# Process and generate
45inputs = processor.apply_chat_template(messages, return_tensors="pt")
46with torch.no_grad():
47 outputs = model.generate(**inputs, max_new_tokens=1024)
48
49# Decode response
50response = processor.decode(outputs[0], skip_special_tokens=True)
51print(response)1{
2 "ご利用明細票": {
3 "セブン銀行": "QR",
4 "取引金額": "¥10,000*",
5 "日付": "2025年03月26日",
6 "時間": "15:46",
7 "店舗番号": "0034",
8 "店番": "BranchNo0100",
9 "口座番号": "************9384",
10 "金額票": "114703045-8277103",
11 "照合コード": "0000",
12 "お取引会社からのご連絡": "PayPayのお取引です"
13 },
14 "お知らせ": [
15 "PayPayスクラッチくじ!すべての対象のお店で200円以上の支払いで1等最大全額戻ってくる(付与上限・条件あり)",
16 "詳しくはPayPayアプリで♪"
17 ],
18 "注意事項": [
19 "暗証番号は他人に知られないようにしてください。銀行員が直接あるいは電話で暗証番号をお尋ねすることはありません。",
20 "上記ご取引内容についてご不明の点は、お取引会社にお問合せください。"
21 ],
22 "セブン銀行": "セブン銀行"
23}1{
2 "店舗名": "ダイソー青葉台東急スクエア店",
3 "電話番号": "TEL:082-420-0100",
4 "公式通販サイトURL": "「DAISOオンラインショップ」『ダイソーオンライン』で検索!",
5 "令状:校訂証正日付": "2025年6月22日(日)",
6 "レジ日時": "19:24",
7 "レジ番号": "0006",
8 "責任者名": "99999992",
9 "商品列表": [
10 {
11 "商品コード": "ドウシシャ",
12 "商品名": "ナタデココ入",
13 "価格": "¥100※"
14 },
15 {
16 "商品コード": "ドウシシャ",
17 "商品名": "チアシードド",
18 "価格": "¥100※"
19 },
20 {
21 "商品名": "消臭ポリ袋(おむつ用)",
22 "価格": "¥100外"
23 },
24 {
25 "商品名": "化粧ブラシセット(5本)",
26 "価格": "¥300外"
27 },
28 {
29 "商品名": "シャワー線棒 1 1 0本入",
30 "価格": "¥100外"
31 },
32 {
33 "商品名": "抗菌線棒(バガスパルブ配",
34 "価格": "¥100外"
35 }
36 ],
37 "小計点数": "6点",
38 "小計金額": "¥800",
39 "税込ポイント": "",
40 "各税別": {
41 "10%税抜対象額": "¥600",
42 "10%税率額": "¥60",
43 "8%税抜対象額": "¥200",
44 "8%税率額": "¥16"
45 },
46 "合計金額": "¥876",
47 "ビザ/マスター金額": "¥876",
48 "お釣り金額": "¥0",
49 "注意事項": "※印は軽減税率適用商品です。",
50 "登録番号": "T7240001022681",
51 "QRコード1": "",
52 "QRコード2": "",
53 "QRコード3": "",
54 "クレジット売上票情報": "",
55 "カード会社": "カイツ",
56 "会員番号": "104",
57 "ビザ/マスター": "",
58 "有効期限": "429769XXXXXXXX5489-NFC",
59 "取扱い日": "2025年06月22日",
60 "承認番号": "0705755",
61 "伝票番号": "05755",
62 "取引内容": "売上(オンライン)",
63 "支払区分": "一括",
64 "取引金額": "¥876",
65 "端末番号": "4971162449343",
66 "ATC": "011C",
67 "カードシークス番号": "00",
68 "AID": "A00000000031010",
69 "APL名": "VISACREDIT",
70 "店舗番号": "008943",
71 "レジット番号": "1841"
72}1# Custom extraction with specific requirements
2custom_prompt = """Parse this Japanese receipt and extract only the following information in JSON format:
3- Transaction amount (取引金額)
4- Date and time (日付・時間)
5- Store information (店舗情報)
6- Payment method details (支払い方法)
7
8Use Japanese keys and preserve exact formatting."""
9
10messages = [
11 {
12 'role': 'system',
13 'content': [{'type': 'text', 'text': custom_prompt}]
14 },
15 {
16 'role': 'user',
17 'content': [
18 {'type': 'text', 'text': 'Extract the requested information from this receipt.'},
19 {'type': 'image', 'image': image}
20 ]
21 }
22]
23
24inputs = processor.apply_chat_template(messages, return_tensors="pt")
25outputs = model.generate(**inputs, max_new_tokens=512)
26response = processor.decode(outputs[0], skip_special_tokens=True)
27print(response)1import os
2from pathlib import Path
3
4def process_receipt_batch(image_folder, output_file):
5 """Process multiple receipts and save results"""
6 results = []
7
8 for image_path in Path(image_folder).glob("*.jpg"):
9 image = Image.open(image_path)
10
11 # Use the standard system prompt for full extraction
12 messages = [
13 {'role': 'system', 'content': [{'type': 'text', 'text': system_prompt}]},
14 {'role': 'user', 'content': [
15 {'type': 'text', 'text': 'Parse this receipt.'},
16 {'type': 'image', 'image': image}
17 ]}
18 ]
19
20 inputs = processor.apply_chat_template(messages, return_tensors="pt")
21 outputs = model.generate(**inputs, max_new_tokens=1024)
22 response = processor.decode(outputs[0], skip_special_tokens=True)
23
24 results.append({
25 "filename": image_path.name,
26 "extracted_data": response
27 })
28
29 # Save results
30 import json
31 with open(output_file, 'w', encoding='utf-8') as f:
32 json.dump(results, f, ensure_ascii=False, indent=2)
33
34# Process all receipts in a folder
35process_receipt_batch("./receipts/", "extracted_data.json")1@misc{japanese-receipt-vl-lfm2-450m,
2 title={Japanese Receipt VL lfm2-450M: A Specialized Vision-Language Model for Japanese Receipt Understanding},
3 author={sabaridsnfuji},
4 year={2024},
5 publisher={Hugging Face},
6 url={https://huggingface.co/sabaridsnfuji/Japanese-Receipt-VL-lfm2-450M}
7}1@article{japanese-mobile-receipt-ocr-2024,
2 title={Japanese-Mobile-Receipt-OCR-1.3K: A Comprehensive Dataset Analysis and Fine-tuned Vision-Language Model for Structured Receipt Data Extraction},
3 author={Sabari Nathan},
4 year={2024},
5 doi={10.21203/rs.3.rs-7357197/v1},
6 url={https://doi.org/10.21203/rs.3.rs-7357197/v1},
7 note={Preprint}
8}1@article{lfm2-vl-2024,
2 title={LFM2-VL: Large Foundation Model for Vision-Language Tasks},
3 author={LiquidAI},
4 year={2024},
5 publisher={LiquidAI},
6 url={https://huggingface.co/liquidai/lfm2-vl-450m}
7}