vithacocf commited on
Commit
dcc9745
·
verified ·
1 Parent(s): 76a5fff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -13
app.py CHANGED
@@ -78,26 +78,40 @@ def convert_png_to_jpg(image):
78
  return converted
79
 
80
  # Hàm chính
81
- def predict(image, prompt=None):
82
- # Kiểm tra ảnh hợp lệ
83
- if not is_supported_image(image):
84
- return "Không hỗ trợ định dạng file này. Vui lòng tải ảnh đúng."
85
 
86
- # Prompt rỗng
87
  if prompt is None or prompt.strip() == "":
88
- return "Vui lòng nhập prompt để trích xuất dữ liệu từ ảnh."
89
 
90
  try:
91
- # Nếu ảnh là PNG có alpha, convert sang RGB
92
- if image.mode == "RGBA" or image.mode == "LA":
93
- image = convert_png_to_jpg(image)
94
 
95
- image = image.convert("RGB")
 
 
 
96
 
97
  except UnidentifiedImageError:
98
- return "Không thể đọc ảnh. Vui lòng kiểm tra lại định dạng hoặc ảnh bị lỗi."
99
  except Exception as e:
100
- return f"Lỗi khi xử lý ảnh: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  # Inference
103
  inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
@@ -118,7 +132,8 @@ def predict(image, prompt=None):
118
  demo = gr.Interface(
119
  fn=predict,
120
  inputs=[
121
- gr.Image(type="pil", label="Tải ảnh tài liệu lên"),
 
122
  gr.Textbox(label="Gợi ý (tuỳ chọn)", placeholder="VD: Trích số hóa đơn")
123
  ],
124
  outputs="text",
 
78
  return converted
79
 
80
  # Hàm chính
81
+ def predict(image_path, prompt=None):
82
+ if not isinstance(image_path, str) or not os.path.exists(image_path):
83
+ return "=Không tìm thấy ảnh. Vui lòng thử lại sau khi upload thành công."
 
84
 
 
85
  if prompt is None or prompt.strip() == "":
86
+ return "=Vui lòng nhập prompt để trích xuất dữ liệu."
87
 
88
  try:
89
+ image = Image.open(image_path).convert("RGB")
 
 
90
 
91
+ if image.mode in ["RGBA", "LA"]:
92
+ new_img = Image.new("RGB", image.size, (255, 255, 255))
93
+ new_img.paste(image)
94
+ image = new_img
95
 
96
  except UnidentifiedImageError:
97
+ return "=Không thể đọc ảnh. Ảnh thể bị hỏng hoặc sai định dạng."
98
  except Exception as e:
99
+ return f"=Lỗi khi xử lý ảnh: {str(e)}"
100
+
101
+ inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
102
+
103
+ generated_ids = model.generate(
104
+ **inputs,
105
+ max_new_tokens=512,
106
+ do_sample=False,
107
+ use_cache=False,
108
+ eos_token_id=processor.tokenizer.eos_token_id,
109
+ pad_token_id=processor.tokenizer.pad_token_id
110
+ )
111
+
112
+ result = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
113
+ return result
114
+
115
 
116
  # Inference
117
  inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
 
132
  demo = gr.Interface(
133
  fn=predict,
134
  inputs=[
135
+ # gr.Image(type="pil", label="Tải ảnh tài liệu lên"),
136
+ gr.Image(type="filepath", label="Tải ảnh tài liệu lên"),
137
  gr.Textbox(label="Gợi ý (tuỳ chọn)", placeholder="VD: Trích số hóa đơn")
138
  ],
139
  outputs="text",