File size: 7,998 Bytes
e69be74
 
4a10a29
 
eba303d
e69be74
 
eba303d
 
 
4a10a29
 
 
 
 
 
eba303d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a10a29
 
 
 
 
e69be74
4a10a29
 
 
eba303d
4a10a29
 
e69be74
4a10a29
 
e69be74
4a10a29
e69be74
4a10a29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eba303d
4a10a29
 
 
e69be74
4a10a29
eba303d
e69be74
4a10a29
eba303d
4a10a29
 
eba303d
 
 
 
 
 
 
 
 
 
4a10a29
eba303d
 
 
 
 
 
4a10a29
eba303d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a10a29
 
 
e69be74
 
4a10a29
 
 
 
 
 
e69be74
4a10a29
eba303d
4a10a29
 
e69be74
4a10a29
e69be74
4a10a29
 
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import json
import os
import time

from loguru import logger
from openai import OpenAI

from common.enum.ai_service_error import AiServiceError
from common.exceptions import AiServiceException
from common.utils import encode_image_to_webp_base64
from image_processing_interface import ImageProcessingInterface


class OpenAIService(ImageProcessingInterface):
    _instance = None

    TOOLS = [
        {
            "type": "function",
            "function": {
                "name": "parse_image",
                "description": "Parses receipt data from image into a structured JSON format.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "store_name": {"type": "string"},
                        "country": {"type": "string"},
                        "receipt_type": {"type": "string"},
                        "address": {"type": "string"},
                        "datetime": {"type": "string"},
                        "currency": {"type": "string"},
                        "sub_total_amount": {"type": "number"},
                        "total_price": {"type": "number"},
                        "total_discount": {"type": "number"},
                        "all_items_price_with_tax": {"type": "boolean"},
                        "payment_method": {
                            "type": "string",
                            "enum": ["card", "cash", "unknown"]
                        },
                        "rounding": {"type": "number"},
                        "tax": {"type": "number"},
                        "taxes_not_included_sum": {"type": "number"},
                        "tips": {"type": "number"},
                        "items": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "name": {"type": "string"},
                                    "unit_price": {"type": "number"},
                                    "quantity": {"type": "number"},
                                    "measurement_unit": {"type": "string"},
                                    "total_price_without_discount": {"type": "number"},
                                    "total_price_with_discount": {"type": "number"},
                                    "discount": {"type": "number"},
                                    "category": {"type": "string"},
                                    "item_price_with_tax": {"type": "boolean"},
                                },
                                "required": ["name", "unit_price", "quantity", "total_price_without_discount"]
                            }
                        },
                        "taxs_items": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "tax_name": {"type": "string"},
                                    "percentage": {"type": "number"},
                                    "tax_from_amount": {"type": "number"},
                                    "tax": {"type": "number"},
                                    "total": {"type": "number"},
                                    "tax_included": {"type": "boolean"},
                                },
                            }
                        }

                    },
                    "required": ["total_price", "items"]
                }
            }
        }
    ]

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(OpenAIService, cls).__new__(cls)
        return cls._instance

    def __init__(self, api_key=None):
        if not hasattr(self, "_initialized"):
            self.api_key = api_key or os.environ.get("OPENAI_API_KEY")
            if self.api_key:
                logger.info("OPENAI_API_KEY was found.")
            else:
                raise ValueError("OPENAI_API_KEY not found.")

            self.client = OpenAI(api_key=self.api_key)
            self._initialized = True

    def process_image(self, input_image64, model_name, prompt, system="You are a receipt recognizer!", temperature=0.0):
        if not input_image64:
            raise ValueError("No image provided.")

        try:
            start_time = time.time()

            response = self.client.chat.completions.create(
                model=model_name,
                messages=[
                    {"role": "system", "content": system},
                    {"role": "user", "content": [
                        {"type": "text", "text": prompt},
                        {"type": "image_url", "image_url": {
                            "url": f"data:image/webp;base64,{input_image64}"}
                         }
                    ]}
                ],
                tools=self.TOOLS,
                temperature=temperature,
                response_format={"type": "json_object"}
            )

            end_time = time.time()
            logger.info(f"Recognition spent {end_time - start_time:.2f} seconds.")

            # Extract the function call result
            if not response.choices:
                raise ValueError("The API response does not contain valid choices.")

            choice = response.choices[0]
            if not choice.message.tool_calls:
                raise ValueError(choice.message.content or "No tool calls found in the API response.")

            function_call = choice.message.tool_calls[0]

            if not (function_call.function and function_call.function.arguments):
                raise ValueError("No valid function call data found in the API response.")

            logger.debug(f"Raw API Response: {function_call.function.arguments}")

            try:
                json_content = json.loads(function_call.function.arguments)
            except json.JSONDecodeError:
                error_message = f"The receipt could not be recognized. Please retake the photo."
                logger.error(error_message)
                raise AiServiceException(AiServiceError.RETAKE_PHOTO, error_message)

            if not self._validate_receipt_data(json_content):
                error_message = f"The receipt is empty or contains no valid items. Please ensure the receipt is correctly scanned and try again"
                logger.error(error_message)
                raise AiServiceException(AiServiceError.RETAKE_PHOTO, error_message)

            json_content = self._add_total_price(json_content)
            json_content = self._add_discount_item(json_content)
            json_content = self._add_rounding_item(json_content)

            # Add token usage information
            json_content['input_tokens'] = response.usage.prompt_tokens
            json_content['output_tokens'] = response.usage.completion_tokens
            json_content['total_tokens'] = response.usage.total_tokens
            json_content['time'] = end_time - start_time

            model_input = {
                "system": system,
                "prompt": prompt
            }

            return json.dumps(json_content, indent=4), model_input

        except Exception as e:
            raise RuntimeError(f"Failed to process the image: {str(e)}")

if __name__ == "__main__":
    try:
        processor = OpenAIService()

        # Image processing
        image_path = "./examples/fatlouis.webp"
        input_image64 = encode_image_to_webp_base64(image_path)

        system = "You are a receipt recognizer."
        with open('common/prompt_v1.txt', 'r', encoding='utf-8') as file:
            prompt = file.read()
        result = processor.process_image(input_image64, "gpt-4o-mini", prompt, system, 0.0)

        print(f'Image processing result: {result}')

    except Exception as e:
        print(f"Error: {e}")