minhvh commited on
Commit
6a009c3
·
verified ·
1 Parent(s): 9fb3717

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -52
app.py CHANGED
@@ -1,69 +1,77 @@
1
  import gradio as gr
2
- import cv2
 
3
  import numpy as np
4
- import easyocr
5
- from paddleocr import PaddleOCR
6
 
7
- # Khởi tạo EasyOCR cho English, Japanese
8
- readers = {
9
- "English": easyocr.Reader(['en'], gpu=False),
10
- "Japanese": easyocr.Reader(['ja', 'en'], gpu=False),
 
 
 
 
11
  }
12
 
13
- # Khởi tạo PaddleOCR cho Chinese (Simplified)
14
- paddle_reader = PaddleOCR(
15
- use_doc_orientation_classify=False,
16
- use_doc_unwarping=False,
17
- use_textline_orientation=False
18
- )
19
 
20
- def preprocess_image(image, max_width=1024):
21
  """
22
- Resize ảnh nếu quá lớn, convert sang RGB.
23
  """
24
- if image.shape[2] == 4:
25
- image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
26
- h, w = image.shape[:2]
27
- if w > max_width:
28
- ratio = max_width / w
29
- image = cv2.resize(image, (max_width, int(h * ratio)))
30
- return image
31
 
32
- def ocr_image(image, lang_choice):
33
- """
34
- OCR với EasyOCR (English/Japanese) hoặc PaddleOCR (Chinese).
35
- """
36
- # image = preprocess_image(image)
 
 
37
 
38
- if lang_choice == "Chinese (Simplified)":
39
- # PaddleOCR: input thể numpy array
40
- results = paddle_reader.ocr(image, cls=False)
41
- texts = []
42
- for res in results:
43
- for line in res:
44
- texts.append(line[1][0]) # line[1] = (text, confidence)
45
- return "\n".join(texts) if texts else "Không nhận diện được văn bản"
46
- else:
47
- # EasyOCR
48
- reader = readers[lang_choice]
49
- results = reader.readtext(image)
50
- texts = [res[1] for res in results]
51
- return "\n".join(texts) if texts else "Không nhận diện được văn bản"
 
 
 
 
 
 
 
 
52
 
53
- # Giao diện Gradio
54
  demo = gr.Interface(
55
- fn=ocr_image,
56
  inputs=[
57
- gr.Image(type="numpy", label="Upload ảnh"),
58
- gr.Dropdown(
59
- choices=["English", "Chinese (Simplified)", "Japanese"],
60
- value="English",
61
- label="Chọn ngôn ngữ OCR"
62
- )
63
  ],
64
- outputs="text",
65
- title="OCR Đa Ngôn Ngữ (EasyOCR + PaddleOCR)",
66
- description="English & Japanese dùng EasyOCR, Chinese Simplified dùng PaddleOCR"
 
67
  )
68
 
69
  if __name__ == "__main__":
 
1
  import gradio as gr
2
+ from paddleocr import PaddleOCR, draw_ocr
3
+ from PIL import Image
4
  import numpy as np
 
 
5
 
6
+ # ===== Khởi tạo model OCR cho từng ngôn ngữ =====
7
+ LANG_CONFIG = {
8
+ "ch": "Chinese (Simplified)",
9
+ "en": "English",
10
+ "japan": "Japanese",
11
+ "korean": "Korean",
12
+ "fr": "French",
13
+ "german": "German",
14
  }
15
 
16
+ # Load toàn bộ model sẵn (startup lâu nhưng inference nhanh)
17
+ ocr_models = {
18
+ lang: PaddleOCR(lang=lang, use_angle_cls=True, use_gpu=False)
19
+ for lang in LANG_CONFIG.keys()
20
+ }
 
21
 
22
+ def inference(img, lang):
23
  """
24
+ Nhận diện text bằng PaddleOCR vẽ kết quả ra ảnh.
25
  """
26
+ # OCR
27
+ ocr = ocr_models[lang]
28
+ result = ocr.ocr(img, cls=True)[0]
 
 
 
 
29
 
30
+ # Load ảnh gốc bằng PIL
31
+ image = Image.open(img).convert("RGB")
32
+
33
+ # Lấy bbox, text, confidence
34
+ boxes = [line[0] for line in result]
35
+ txts = [line[1][0] for line in result]
36
+ scores = [line[1][1] for line in result]
37
 
38
+ # Vẽ kết quả OCR
39
+ im_show = draw_ocr(image, boxes, txts, scores, font_path="./simfang.ttf")
40
+ im_show = Image.fromarray(im_show.astype(np.uint8)) # từ numpy -> PIL
41
+
42
+ # Trả về text + ảnh
43
+ text_out = "\n".join([f"{t} (conf={s:.2f})" for t, s in zip(txts, scores)])
44
+ return im_show, text_out
45
+
46
+
47
+ # ===== Giao diện Gradio =====
48
+ title = "PaddleOCR Multi-language"
49
+ description = """
50
+ PaddleOCR hỗ trợ Chinese, English, Japanese, Korean, French, German.
51
+ - Upload ảnh + chọn ngôn ngữ để nhận diện.
52
+ - Model load sẵn toàn bộ, inference nhanh.
53
+ """
54
+
55
+ examples = [
56
+ ["en_example.jpg", "en"],
57
+ ["cn_example.jpg", "ch"],
58
+ ["jp_example.jpg", "japan"],
59
+ ]
60
 
 
61
  demo = gr.Interface(
62
+ fn=inference,
63
  inputs=[
64
+ gr.Image(type="filepath", label="Upload ảnh"),
65
+ gr.Dropdown(choices=list(LANG_CONFIG.keys()), value="ch", label="Ngôn ngữ OCR")
66
+ ],
67
+ outputs=[
68
+ gr.Image(type="pil", label="Ảnh kết quả"),
69
+ gr.Textbox(label="Kết quả nhận diện")
70
  ],
71
+ title=title,
72
+ description=description,
73
+ examples=examples,
74
+ cache_examples=False,
75
  )
76
 
77
  if __name__ == "__main__":