ranbac commited on
Commit
e8fb7a1
·
verified ·
1 Parent(s): f286775

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from paddleocr import PaddleOCR
3
+ from PIL import Image
4
+ import numpy as np
5
+
6
+ # 1. Khởi tạo PaddleOCR
7
+ # use_gpu=False: BẮT BUỘC cho CPU Basic
8
+ # lang='ch': Hỗ trợ tiếng Trung và tiếng Anh
9
+ # use_angle_cls=True: Tự động xoay ảnh nếu văn bản bị nghiêng
10
+ ocr = PaddleOCR(use_angle_cls=True, lang='ch', use_gpu=False)
11
+
12
+ def inference(img):
13
+ if img is None:
14
+ return None, "Vui lòng tải ảnh lên."
15
+
16
+ # Chuyển đổi ảnh sang numpy array nếu cần thiết
17
+ if isinstance(img, Image.Image):
18
+ img = np.array(img)
19
+
20
+ # 2. Thực hiện OCR
21
+ # result trả về danh sách các hộp (box), văn bản (text), và độ tin cậy (score)
22
+ result = ocr.ocr(img, cls=True)
23
+
24
+ txts = []
25
+ if result and result[0]:
26
+ # Trích xuất chỉ phần văn bản để hiển thị
27
+ txts = [line[1][0] for line in result[0]]
28
+ else:
29
+ return img, "Không tìm thấy văn bản nào."
30
+
31
+ # 3. Vẽ kết quả lên ảnh (Optional - dùng hàm có sẵn của Paddle)
32
+ from paddleocr import draw_ocr
33
+ boxes = [line[0] for line in result[0]]
34
+ scores = [line[1][1] for line in result[0]]
35
+
36
+ # Cần font tiếng Trung để vẽ lên ảnh, nếu không sẽ bị lỗi ô vuông
37
+ # PaddleOCR tự động tải font mặc định, nhưng để an toàn ta trả về text trước
38
+ im_show = draw_ocr(img, boxes, txts, scores, font_path='./fonts/simfang.ttf')
39
+ im_show = Image.fromarray(im_show)
40
+
41
+ return im_show, "\n".join(txts)
42
+
43
+ # 4. Giao diện Gradio
44
+ title = "PaddleOCR Chinese - CPU Optimized"
45
+ description = "Nhận diện tiếng Trung/Anh sử dụng PaddleOCR v4 chạy trên Hugging Face CPU Basic."
46
+
47
+ with gr.Blocks() as demo:
48
+ gr.Markdown(f"# {title}")
49
+ gr.Markdown(description)
50
+
51
+ with gr.Row():
52
+ with gr.Column():
53
+ img_input = gr.Image(label="Tải ảnh lên", type="pil")
54
+ submit_btn = gr.Button("Chạy OCR")
55
+ with gr.Column():
56
+ img_output = gr.Image(label="Kết quả Visualized", type="pil")
57
+ text_output = gr.Textbox(label="Văn bản trích xuất", lines=10)
58
+
59
+ submit_btn.click(fn=inference, inputs=img_input, outputs=[img_output, text_output])
60
+
61
+ # Launch
62
+ demo.launch()