Update app.py
Browse files
app.py
CHANGED
|
@@ -1,33 +1,45 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 3 |
from PIL import Image
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
|
|
|
| 7 |
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed")
|
| 8 |
|
| 9 |
-
|
| 10 |
def process_image(image):
|
| 11 |
-
# Chuyển
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
if image.mode in ("RGBA", "LA"):
|
| 13 |
background = Image.new("RGB", image.size, (255, 255, 255))
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 18 |
generated_ids = model.generate(pixel_values)
|
| 19 |
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 20 |
return generated_text
|
| 21 |
|
| 22 |
-
|
| 23 |
-
title = "
|
| 24 |
-
description = "
|
| 25 |
|
| 26 |
interface = gr.Interface(
|
| 27 |
fn=process_image,
|
| 28 |
inputs="image",
|
| 29 |
-
examples=[f"examples/captcha-{i}.png" for i in range(10)],
|
| 30 |
outputs="text",
|
|
|
|
| 31 |
title=title,
|
| 32 |
-
description=description
|
| 33 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 3 |
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
|
| 6 |
+
# Load model và processor
|
| 7 |
+
model_name = "chanelcolgate/trocr-base-printed_captcha_ocr"
|
| 8 |
+
model = VisionEncoderDecoderModel.from_pretrained(model_name)
|
| 9 |
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed")
|
| 10 |
|
| 11 |
+
# Hàm xử lý ảnh captcha
|
| 12 |
def process_image(image):
|
| 13 |
+
# Chuyển numpy -> PIL nếu cần
|
| 14 |
+
if isinstance(image, np.ndarray):
|
| 15 |
+
image = Image.fromarray(image)
|
| 16 |
+
|
| 17 |
+
# Thêm nền trắng nếu ảnh có alpha
|
| 18 |
if image.mode in ("RGBA", "LA"):
|
| 19 |
background = Image.new("RGB", image.size, (255, 255, 255))
|
| 20 |
+
background.paste(image, mask=image.split()[-1])
|
| 21 |
+
image = background
|
| 22 |
+
else:
|
| 23 |
+
image = image.convert("RGB")
|
| 24 |
|
| 25 |
+
# Encode và predict
|
| 26 |
pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 27 |
generated_ids = model.generate(pixel_values)
|
| 28 |
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 29 |
return generated_text
|
| 30 |
|
| 31 |
+
# Giao diện Gradio
|
| 32 |
+
title = "Captcha OCR Demo"
|
| 33 |
+
description = "Nhận diện captcha từ mã số thuế (MST) – Model TrOCR"
|
| 34 |
|
| 35 |
interface = gr.Interface(
|
| 36 |
fn=process_image,
|
| 37 |
inputs="image",
|
|
|
|
| 38 |
outputs="text",
|
| 39 |
+
examples=[f"examples/captcha-{i}.png" for i in range(10)],
|
| 40 |
title=title,
|
| 41 |
+
description=description,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
interface.launch()
|