-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathidentifyreceipt.py
More file actions
174 lines (140 loc) · 5.24 KB
/
Copy pathidentifyreceipt.py
File metadata and controls
174 lines (140 loc) · 5.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 22:27:41 2026
@author: sheng
"""
#!/usr/bin/env python3
"""
Receipt Total Extractor
Uses Claude's vision API to analyze a receipt image and extract the total amount.
Usage:
python receipt_reader.py <path_to_receipt_image>
Requirements:
pip install anthropic
export ANTHROPIC_API_KEY="your-api-key"
"""
import anthropic
import base64
import sys
import os
import re
from pathlib import Path
def load_image_as_base64(image_path: str) -> tuple[str, str]:
"""Load an image file and return base64-encoded data and media type."""
path = Path(image_path)
if not path.exists():
raise FileNotFoundError(f"Image file not found: {image_path}")
# Determine media type from extension
ext = path.suffix.lower()
media_type_map = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
}
media_type = media_type_map.get(ext)
if not media_type:
raise ValueError(f"Unsupported image format: {ext}. Use JPG, PNG, GIF, or WebP.")
with open(image_path, "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
return image_data, media_type
def extract_receipt_total(image_path: str) -> dict:
"""
Analyze a receipt image and extract the total amount.
Args:
image_path: Path to the receipt image file.
Returns:
A dict with 'total', 'currency', 'raw_response', and 'confidence'.
"""
# Load and encode the image
image_data, media_type = load_image_as_base64(image_path)
# Initialize the Anthropic client
# Automatically uses ANTHROPIC_API_KEY environment variable
client = anthropic.Anthropic()
# Send the image to Claude for analysis
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": media_type,
"data": image_data,
},
},
{
"type": "text",
"text": (
"Please analyze this receipt image and extract the total amount due. "
"Look for labels like 'Total', 'Grand Total', 'Amount Due', 'Balance Due', or similar. "
"Respond in this exact format:\n\n"
"TOTAL: <amount>\n"
"CURRENCY: <currency symbol or code>\n"
"CONFIDENCE: <high/medium/low>\n"
"NOTES: <any relevant notes, e.g. if multiple totals found, tax info, etc.>\n\n"
"If you cannot find a total amount, respond with TOTAL: NOT_FOUND and explain in NOTES."
),
},
],
}
],
)
raw_response = message.content[0].text
# Parse the structured response
result = {
"total": None,
"currency": None,
"confidence": None,
"notes": None,
"raw_response": raw_response,
}
for line in raw_response.splitlines():
if line.startswith("TOTAL:"):
total_str = line.split(":", 1)[1].strip()
if total_str != "NOT_FOUND":
# Remove currency symbols and commas for clean numeric value
result["total"] = re.sub(r"[^\d.,]", "", total_str) or total_str
result["total_display"] = total_str # Keep original for display
elif line.startswith("CURRENCY:"):
result["currency"] = line.split(":", 1)[1].strip()
elif line.startswith("CONFIDENCE:"):
result["confidence"] = line.split(":", 1)[1].strip()
elif line.startswith("NOTES:"):
result["notes"] = line.split(":", 1)[1].strip()
return result
def main():
if len(sys.argv) < 2:
print("Usage: python receipt_reader.py <path_to_receipt_image>")
print("Example: python receipt_reader.py receipt.jpg")
sys.exit(1)
image_path = sys.argv[1]
# Check for API key
if not os.environ.get("ANTHROPIC_API_KEY"):
print("Error: ANTHROPIC_API_KEY environment variable is not set.")
print("Set it with: export ANTHROPIC_API_KEY='your-api-key'")
sys.exit(1)
print(f"Analyzing receipt: {image_path}")
print("-" * 40)
result = extract_receipt_total(image_path)
# Display results
if result["total"]:
display = result.get("total_display", result["total"])
currency = result["currency"] or ""
print(f"✅ Total Amount Found: {currency} {display}".strip())
print(f" Confidence: {result['confidence'] or 'N/A'}")
else:
print("❌ Could not extract total amount from receipt.")
if result["notes"]:
print(f" Notes: {result['notes']}")
print("-" * 40)
print("Full response from Claude:")
print(result["raw_response"])
return result
if __name__ == "__main__":
main()