NafishZaldinanda commited on
Commit
7ae7701
·
verified ·
1 Parent(s): 85a9e22

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +408 -0
app.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pdf2image import convert_from_path
2
+ from PIL import Image
3
+ from pathlib import Path
4
+ from torchvision.transforms.functional import InterpolationMode
5
+ from transformers import AutoModel, AutoTokenizer
6
+ from pydantic import BaseModel, Field, ValidationError, root_validator, validator
7
+ from typing import List, Optional, Literal
8
+
9
+ import gradio as gr
10
+ import tempfile
11
+ import os
12
+ import json
13
+ import numpy as np
14
+ import re
15
+ import torch
16
+ import torchvision.transforms as T
17
+
18
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
19
+ IMAGENET_STD = (0.229, 0.224, 0.225)
20
+
21
+ def build_transform(input_size):
22
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
23
+ transform = T.Compose([
24
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
25
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
26
+ T.ToTensor(),
27
+ T.Normalize(mean=MEAN, std=STD)
28
+ ])
29
+ return transform
30
+
31
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
32
+ best_ratio_diff = float('inf')
33
+ best_ratio = (1, 1)
34
+ area = width * height
35
+ for ratio in target_ratios:
36
+ target_aspect_ratio = ratio[0] / ratio[1]
37
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
38
+ if ratio_diff < best_ratio_diff:
39
+ best_ratio_diff = ratio_diff
40
+ best_ratio = ratio
41
+ elif ratio_diff == best_ratio_diff:
42
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
43
+ best_ratio = ratio
44
+ return best_ratio
45
+
46
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
47
+ orig_width, orig_height = image.size
48
+ aspect_ratio = orig_width / orig_height
49
+
50
+ # calculate the existing image aspect ratio
51
+ target_ratios = set(
52
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
53
+ i * j <= max_num and i * j >= min_num)
54
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
55
+
56
+ # find the closest aspect ratio to the target
57
+ target_aspect_ratio = find_closest_aspect_ratio(
58
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
59
+
60
+ # calculate the target width and height
61
+ target_width = image_size * target_aspect_ratio[0]
62
+ target_height = image_size * target_aspect_ratio[1]
63
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
64
+
65
+ # resize the image
66
+ resized_img = image.resize((target_width, target_height))
67
+ processed_images = []
68
+ for i in range(blocks):
69
+ box = (
70
+ (i % (target_width // image_size)) * image_size,
71
+ (i // (target_width // image_size)) * image_size,
72
+ ((i % (target_width // image_size)) + 1) * image_size,
73
+ ((i // (target_width // image_size)) + 1) * image_size
74
+ )
75
+ # split the image
76
+ split_img = resized_img.crop(box)
77
+ processed_images.append(split_img)
78
+ assert len(processed_images) == blocks
79
+ if use_thumbnail and len(processed_images) != 1:
80
+ thumbnail_img = image.resize((image_size, image_size))
81
+ processed_images.append(thumbnail_img)
82
+ return processed_images
83
+
84
+ def load_image(image_file, input_size=448, max_num=12):
85
+ image = Image.open(image_file).convert('RGB')
86
+ transform = build_transform(input_size=input_size)
87
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
88
+ pixel_values = [transform(image) for image in images]
89
+ pixel_values = torch.stack(pixel_values)
90
+ return pixel_values
91
+
92
+ device = torch.device('cpu')
93
+ base_path = Path().absolute()
94
+ path = base_path / "resources/model/InternVL2-1B"
95
+ model = AutoModel.from_pretrained(
96
+ path,
97
+ low_cpu_mem_usage=True,
98
+ trust_remote_code=True).to(device).eval()
99
+ tokenizer = AutoTokenizer.from_pretrained(str(path), trust_remote_code=True, use_fast=False)
100
+
101
+ def convert_pdf_to_images(pdf_path):
102
+ images = convert_from_path(pdf_path)
103
+ temp_file_paths = []
104
+ for i, image in enumerate(images):
105
+ with tempfile.NamedTemporaryFile(delete=False, suffix=f'_{i+1}.png', mode='wb') as temp_file:
106
+ temp_path = temp_file.name
107
+ image.save(temp_path, format='PNG')
108
+ temp_file_paths.append(temp_path)
109
+ return temp_file_paths
110
+
111
+
112
+ def images_to_pixel_values(image_paths, device):
113
+ image_paths.sort(key=lambda x: int(os.path.splitext(os.path.basename(x))[0].split('_')[-1]))
114
+ pixel_values_list = [load_image(img_path, max_num=12).to(device) for img_path in image_paths]
115
+ return torch.cat(pixel_values_list, dim=0)
116
+
117
+
118
+ def process_file(file, file_type, file_document):
119
+ if file_type == "PDF":
120
+ try:
121
+ images = convert_pdf_to_images(file.name)
122
+ pixel_values = images_to_pixel_values(images, device)
123
+
124
+ if file_document == "Receipt":
125
+ question = '''
126
+ <image> You are a document processing model. This is a purchase receipt. If multiple images are provided, treat them as a single document and combine their content for processing. Extract and label the following entities from the given image, providing the output in JSON format. The values must only include text found in the document image. Use null or [] for missing entity types.
127
+ { "type": "object", "properties": { "document_type": { "type": "string", "enum": ["purchase_receipt"] }, "data": { "type": "object", "properties": { "receipt_number": { "type": "string" }, "vendor_name": { "type": "string" }, "customer_name": { "type": "string" }, "items": { "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "quantity": { "type": "integer", "nullable": true }, "unit_price": { "type": "string" }, "total_price": { "type": "string" } }, "required": ["description", "quantity", "unit_price", "total_price"] } }, "total_amount": { "type": "string" } }, "required": ["receipt_number", "vendor_name", "customer_name", "items", "total_amount"] } }, "required": ["document_type", "data"] }
128
+ '''
129
+ generation_config = dict(num_beams=1,
130
+ max_new_tokens=4096,
131
+ do_sample=True,
132
+ temperature=0.2,
133
+ repetition_penalty=1.1,
134
+ top_p=0.7)
135
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
136
+
137
+ elif file_document == "Invoice":
138
+ question = '''
139
+ <image> You are a document processing model. This is an invoice. If multiple images are provided, treat them as a single document and combine their content for processing. Extract and label the following entities from the given image, providing the output in JSON format. The values must only include text found in the document image. Use null or [] for missing entity types.
140
+ { "type": "object", "properties": { "document_type": { "type": "string", "enum": ["invoice"] }, "data": { "type": "object", "properties": { "invoice_number": { "type": "string" }, "vendor_name": { "type": "string" }, "customer_name": { "type": "string" }, "items": { "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "quantity": { "type": "integer", "nullable": true }, "unit_price": { "type": "string" }, "total_price": { "type": "string" } }, "required": ["description", "quantity", "unit_price", "total_price"] } }, "subtotal": { "type": "string" }, "tax": { "type": "string" }, "total_amount": { "type": "string" } }, "required": ["invoice_number", "vendor_name", "customer_name", "items", "subtotal", "tax", "total_amount"] } }, "required": ["document_type", "data"] }
141
+ '''
142
+ generation_config = dict(max_new_tokens=4096)
143
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
144
+
145
+ elif file_document == "Faktur Pajak":
146
+ question = '''
147
+ <image> You are a document processing model. This is an invoice. If multiple images are provided, treat them as a single document and combine their content for processing. Extract and label the following entities from the given image, providing the output in JSON format. The values must only include text found in the document image. Use null or [] for missing entity types.
148
+ { "type": "object", "properties": { "document_type": { "type": "string", "enum": ["invoice"] }, "data": { "type": "object", "properties": { "invoice_number": { "type": "string" }, "vendor_name": { "type": "string" }, "customer_name": { "type": "string" }, "items": { "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "quantity": { "type": "integer", "nullable": true }, "unit_price": { "type": "string" }, "total_price": { "type": "string" } }, "required": ["description", "quantity", "unit_price", "total_price"] } }, "subtotal": { "type": "string" }, "tax": { "type": "string" }, "total_amount": { "type": "string" } }, "required": ["invoice_number", "vendor_name", "customer_name", "items", "subtotal", "tax", "total_amount"] } }, "required": ["document_type", "data"] }
149
+ '''
150
+ generation_config = dict(max_new_tokens=4096)
151
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
152
+
153
+ elif file_document == "E-Statement":
154
+ question = '''
155
+ <image> You are a document processing model. This is an e-statement. If multiple images are provided, treat them as a single document and combine their content for processing. Extract and label the following entities from the given image, providing the output in JSON format. The values must only include text found in the document image. Use null or [] for missing entity types.
156
+ { "type": "object", "properties": { "document_type": { "type": "string", "enum": ["e-statement"] }, "data": { "type": "object", "properties": { "account_number": { "type": "string" }, "bank_name": { "type": "string" }, "customer_name": { "type": "string" }, "statement_period": { "type": "string" }, "currency": { "type": "string" }, "country": { "type": "string" }, "transactions": { "type": "array", "items": { "type": "object", "properties": { "transaction_type": { "type": "string" }, "amount": { "type": "number", "nullable": true }, "date": { "type": "string" }, "reference": { "type": "string" } }, "required": ["transaction_type", "amount", "date", "reference"] } } }, "required": ["account_number", "bank_name", "customer_name", "statement_period", "currency", "country", "transactions"] } }, "required": ["document_type", "data"] }
157
+ '''
158
+ generation_config = dict(num_beams=1,
159
+ max_new_tokens=4096,
160
+ do_sample=True,
161
+ repetition_penalty=1.1,
162
+ temperature=0.2,
163
+ top_p=0.7)
164
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
165
+
166
+ elif file_document == "Hukum":
167
+ question = "You are a document processing model. The provided documents may include laws, regulations, legal journals, or other related legal papers. Extract and label the relevant entities from the given documents. If multiple images or files are provided, treat them as a single document and combine their content for processing. Provide the output in JSON format."
168
+ generation_config = dict(max_new_tokens=4096,
169
+ repetition_penalty=1.2,
170
+ do_sample=True,
171
+ temperature=0.1,
172
+ top_p=1.0)
173
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
174
+
175
+ except Exception as e:
176
+ return None, f"Terjadi kesalahan saat memproses file PDF: {str(e)}"
177
+
178
+ elif file_type == "Image":
179
+ try:
180
+ image = Image.open(file.name)
181
+
182
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_file:
183
+ temp_path = temp_file.name
184
+ image.save(temp_path, format='PNG')
185
+
186
+ pixel_values = load_image(temp_path, max_num=12).to(device)
187
+
188
+ if file_document == "Receipt":
189
+ question = '''
190
+ <image> You are a document processing model. This is a purchase receipt. Extract and label the following entities from the given image, providing the output in JSON format. The values must only include text found in the document image. Use null or [] for missing entity types. Extra The output JSON format must follow these specifications:
191
+ { "type": "object", "properties": { "document_type": { "type": "string", "enum": ["purchase_receipt"] }, "data": { "type": "object", "properties": { "receipt_number": { "type": "string" }, "vendor_name": { "type": "string" }, "customer_name": { "type": "string" }, "items": { "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "quantity": { "type": "integer", "nullable": true }, "unit_price": { "type": "string" }, "total_price": { "type": "string" } }, "required": ["description", "quantity", "unit_price", "total_price"] } }, "total_amount": { "type": "string" } }, "required": ["receipt_number", "vendor_name", "customer_name", "items", "total_amount"] } }, "required": ["document_type", "data"] }
192
+ '''
193
+ generation_config = dict(num_beams=1,
194
+ max_new_tokens=4096,
195
+ do_sample=True,
196
+ temperature=0.2,
197
+ repetition_penalty=1.1,
198
+ top_p=0.7)
199
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
200
+
201
+ elif file_document == "Invoice":
202
+ question = '''
203
+ <image> You are a document processing model. This is an invoice. Extract and label the following entities from the given image, providing the output in JSON format. The values must only include text found in the document image. Use null or [] for missing entity types. The output JSON format must follow these specifications:
204
+ { "type": "object", "properties": { "document_type": { "type": "string", "enum": ["invoice"] }, "data": { "type": "object", "properties": { "invoice_number": { "type": "string" }, "vendor_name": { "type": "string" }, "customer_name": { "type": "string" }, "items": { "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "quantity": { "type": "integer", "nullable": true }, "unit_price": { "type": "string" }, "total_price": { "type": "string" } }, "required": ["description", "quantity", "unit_price", "total_price"] } }, "subtotal": { "type": "string" }, "tax": { "type": "string" }, "total_amount": { "type": "string" } }, "required": ["invoice_number", "vendor_name", "customer_name", "items", "subtotal", "tax", "total_amount"] } }, "required": ["document_type", "data"] }
205
+ '''
206
+ generation_config = dict(max_new_tokens=4096)
207
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
208
+
209
+ elif file_document == "Faktur Pajak":
210
+ question = '''
211
+ <image> You are a document processing model. This is an invoice. Extract and label the following entities from the given image, providing the output in JSON format. The values must only include text found in the document image. Use null or [] for missing entity types.
212
+ { "type": "object", "properties": { "document_type": { "type": "string", "enum": ["invoice"] }, "data": { "type": "object", "properties": { "invoice_number": { "type": "string" }, "vendor_name": { "type": "string" }, "customer_name": { "type": "string" }, "items": { "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "quantity": { "type": "integer", "nullable": true }, "unit_price": { "type": "string" }, "total_price": { "type": "string" } }, "required": ["description", "quantity", "unit_price", "total_price"] } }, "subtotal": { "type": "string" }, "tax": { "type": "string" }, "total_amount": { "type": "string" } }, "required": ["invoice_number", "vendor_name", "customer_name", "items", "subtotal", "tax", "total_amount"] } }, "required": ["document_type", "data"] }
213
+ '''
214
+ generation_config = dict(max_new_tokens=4096)
215
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
216
+
217
+ elif file_document == "E-Statement":
218
+ question = '''
219
+ <image> You are a document processing model. This is an e-statement. Extract and label the following entities from the given image, providing the output in JSON format. The values must only include text found in the document image. Use null or [] for missing entity types.
220
+ { "type": "object", "properties": { "document_type": { "type": "string", "enum": ["e-statement"] }, "data": { "type": "object", "properties": { "account_number": { "type": "string" }, "bank_name": { "type": "string" }, "customer_name": { "type": "string" }, "statement_period": { "type": "string" }, "currency": { "type": "string" }, "country": { "type": "string" }, "transactions": { "type": "array", "items": { "type": "object", "properties": { "transaction_type": { "type": "string" }, "amount": { "type": "number", "nullable": true }, "date": { "type": "string" }, "reference": { "type": "string" } }, "required": ["transaction_type", "amount", "date", "reference"] } } }, "required": ["account_number", "bank_name", "customer_name", "statement_period", "currency", "country", "transactions"] } }, "required": ["document_type", "data"] }
221
+ '''
222
+ generation_config = dict(num_beams=1,
223
+ max_new_tokens=4096,
224
+ do_sample=True,
225
+ repetition_penalty=1.1,
226
+ temperature=0.2,
227
+ top_p=0.7)
228
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
229
+
230
+ elif file_document == "Hukum":
231
+ question = "You are a document processing model. The provided documents may include laws, regulations, legal journals, or other related legal papers. Extract and label the relevant entities from the given documents. If multiple images or files are provided, treat them as a single document and combine their content for processing. Provide the output in JSON format."
232
+ generation_config = dict(max_new_tokens=4096,
233
+ repetition_penalty=1.2,
234
+ do_sample=True,
235
+ temperature=0.1,
236
+ top_p=1.0)
237
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
238
+
239
+
240
+ except Exception as e:
241
+ return None, f"Terjadi kesalahan saat memproses file gambar: {str(e)}"
242
+
243
+ def preprocess_json_string_for_numbers(json_string: str) -> str:
244
+ def replace_misplaced_separators(match):
245
+ num_str = match.group(0)
246
+ num_str = re.sub(r'[^\d,.-]', '', num_str)
247
+
248
+ if ',' in num_str and '.' not in num_str:
249
+ corrected_num_str = num_str.replace(',', '')
250
+ elif ',' in num_str and '.' in num_str:
251
+ if num_str.index(',') > num_str.index('.'):
252
+ corrected_num_str = num_str.replace('.', '').replace(',', '.')
253
+ else:
254
+ corrected_num_str = num_str.replace(',', '')
255
+ else:
256
+ corrected_num_str = num_str.replace('.', '')
257
+
258
+ corrected_num_str = str(int(corrected_num_str))
259
+ return corrected_num_str
260
+
261
+ corrected_string = re.sub(r'\b\d{1,3}([.,]\d{3})*(,\d{2})?\b', replace_misplaced_separators, json_string)
262
+ return corrected_string
263
+
264
+ def extract_and_parse_json(string_with_json: str):
265
+ json_pattern = re.search(r'{.*}', string_with_json, re.DOTALL)
266
+
267
+ if json_pattern:
268
+ json_string = json_pattern.group()
269
+
270
+ try:
271
+ corrected_json_string = preprocess_json_string_for_numbers(json_string)
272
+ json_data = json.loads(corrected_json_string)
273
+ print("Parsed JSON data:", json_data)
274
+ return json_data
275
+ except json.JSONDecodeError as e:
276
+ print("Error decoding JSON:", e)
277
+ return corrected_json_string
278
+ else:
279
+ print("No JSON found in the string")
280
+ return None
281
+
282
+ string_with_json = response
283
+ string_with_json = string_with_json.replace("'", '"')
284
+ parsed_data = extract_and_parse_json(string_with_json)
285
+
286
+ if file_document == "Receipt":
287
+ class Item(BaseModel):
288
+ description: Optional[str] = None
289
+ quantity: Optional[int] = 1
290
+ unit_price: Optional[float] = None
291
+ total_price: Optional[float] = None
292
+
293
+ @validator('unit_price', 'total_price', pre=True, always=True)
294
+ def parse_price(cls, v):
295
+ if isinstance(v, str):
296
+ v = re.sub(r'[^\d,.-]', '', v).replace(',', '')
297
+ return float(v)
298
+ return v
299
+
300
+ class PurchaseReceiptData(BaseModel):
301
+ receipt_number: Optional[str] = None
302
+ vendor_name: Optional[str] = None
303
+ customer_name: Optional[str] = None
304
+ items: List[Item]
305
+ total_amount: Optional[float] = None
306
+
307
+ @validator('total_amount', pre=True, always=True)
308
+ def remove_currency_format(cls, v):
309
+ if isinstance(v, str):
310
+ v = re.sub(r'[^\d,.-]', '', v).replace(',', '')
311
+ return float(v)
312
+ return v
313
+
314
+ class PurchaseReceipt(BaseModel):
315
+ document_type: Literal["purchase_receipt"]
316
+ data: PurchaseReceiptData
317
+
318
+ @root_validator(pre=True)
319
+ def ensure_format(cls, values):
320
+ if 'document_type' not in values:
321
+ values['document_type'] = 'purchase_receipt'
322
+ return values
323
+
324
+ predicted_json = parsed_data
325
+
326
+ try:
327
+ receipt = PurchaseReceipt(document_type="purchase_receipt", data=predicted_json['data'])
328
+ corrected_json = receipt.dict()
329
+ print(corrected_json)
330
+ except ValidationError as e:
331
+ print(f"Validation error: {e}")
332
+
333
+ elif file_document == "Invoice":
334
+ class Item(BaseModel):
335
+ description: Optional[str] = None
336
+ quantity: Optional[int] = 1
337
+ unit_price: Optional[float] = None
338
+ total_price: Optional[float] = None
339
+
340
+ @validator('unit_price', 'total_price', pre=True, always=True)
341
+ def parse_price(cls, v):
342
+ if isinstance(v, str):
343
+ v = re.sub(r'[^\d,.-]', '', v).replace(',', '')
344
+ return float(v)
345
+ return v
346
+
347
+ class InvoiceData(BaseModel):
348
+ invoice_number: Optional[str] = None
349
+ vendor_name: Optional[str] = None
350
+ customer_name: Optional[str] = None
351
+ items: List[Item]
352
+ subtotal: float
353
+ tax: Optional[float] = None
354
+ total_amount: float
355
+
356
+ @validator('total_amount', 'subtotal', 'tax', pre=True, always=True)
357
+ def remove_currency_format(cls, v):
358
+ if isinstance(v, str):
359
+ v = re.sub(r'[^\d,.-]', '', v).replace(',', '')
360
+ return float(v)
361
+ return v
362
+
363
+ class Invoice(BaseModel):
364
+ document_type: Literal["invoice"]
365
+ data: InvoiceData
366
+
367
+ @root_validator(pre=True)
368
+ def ensure_format(cls, values):
369
+ if 'document_type' not in values:
370
+ values['document_type'] = 'invoice'
371
+ return values
372
+
373
+ predicted_json = parsed_data
374
+
375
+ try:
376
+ invoice = Invoice(document_type="invoice", data=predicted_json['data'])
377
+ corrected_json = invoice.dict()
378
+ print(corrected_json)
379
+ except ValidationError as e:
380
+ print(f"Validation error: {e}")
381
+
382
+ elif file_document == "Faktur Pajak":
383
+ predicted_json = parsed_data
384
+ corrected_json = predicted_json
385
+
386
+ elif file_document == "E-Statement":
387
+ predicted_json = parsed_data
388
+ corrected_json = predicted_json
389
+
390
+ elif file_document == "Hukum":
391
+ predicted_json = parsed_data
392
+ corrected_json = predicted_json
393
+
394
+ return corrected_json
395
+
396
+ file_type_radio = gr.Radio(choices=["Image", "PDF"], label="Pilih tipe file")
397
+ file_document_radio = gr.Radio(choices=["Receipt", "Invoice", "Faktur Pajak", "E-Statement", "Hukum"], label="Pilih jenis dokumen file")
398
+ file_input = gr.File(label="Unggah file", file_types=["image", "pdf"])
399
+
400
+ interface = gr.Interface(
401
+ fn=process_file,
402
+ inputs=[file_input, file_type_radio, file_document_radio],
403
+ outputs="json",
404
+ title="POC Finance Document Processing Using AI",
405
+ description="Pilih tipe file dan unggah file gambar atau PDF untuk diproses."
406
+ )
407
+
408
+ interface.launch()