-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathInvoiceExtract_LocalFile.py
51 lines (42 loc) · 1.46 KB
/
InvoiceExtract_LocalFile.py
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
from openai import OpenAI
import json
import os
import base64
client = OpenAI()
def load_json_schema(schema_file: str) -> dict:
with open(schema_file, 'r') as file:
return json.load(file)
# Use the local file 'handwrittensample.png'
image_path = 'handwrittensample.png'
# Load the JSON schema
invoice_schema = load_json_schema('invoice_schema.json')
# Open the local image file in binary mode
with open(image_path, 'rb') as image_file:
image_base64 = base64.b64encode(image_file.read()).decode('utf-8')
response = client.chat.completions.create(
model='gpt-4o',
response_format={"type": "json_object"},
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "provide JSON file that represents this document. Use this JSON Schema: " +
json.dumps(invoice_schema)},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{image_base64}"
}
}
]
}
],
max_tokens=500,
)
print(response.choices[0].message.content)
json_data = json.loads(response.choices[0].message.content)
filename_without_extension = os.path.splitext(os.path.basename(image_path))[0]
json_filename = f"{filename_without_extension}.json"
with open(json_filename, 'w') as file:
json.dump(json_data, file, indent=4)
print(f"JSON data saved to {json_filename}")