Update app.py
Browse files
app.py
CHANGED
|
@@ -2,65 +2,77 @@ import gradio as gr
|
|
| 2 |
import logging
|
| 3 |
import os
|
| 4 |
import re
|
| 5 |
-
# Đặt biến môi trường TRƯỚC KHI import paddle để tắt hoàn toàn MKLDNN ở cấp độ OS
|
| 6 |
-
os.environ["FLAGS_use_mkldnn"] = "0"
|
| 7 |
-
os.environ["FLAGS_enable_mkldnn"] = "0"
|
| 8 |
-
os.environ["CPP_MIN_LOG_LEVEL"] = "3"
|
| 9 |
-
|
| 10 |
from paddleocr import PaddleOCR
|
| 11 |
from PIL import Image
|
| 12 |
import numpy as np
|
| 13 |
|
| 14 |
-
# Tắt log
|
|
|
|
| 15 |
logging.getLogger("ppocr").setLevel(logging.WARNING)
|
| 16 |
|
| 17 |
-
print("Đang khởi tạo PaddleOCR (
|
| 18 |
|
|
|
|
|
|
|
| 19 |
try:
|
| 20 |
-
# --- CẤU HÌNH AN TOÀN TUYỆT ĐỐI ---
|
| 21 |
-
# enable_mkldnn=False: Bắt buộc tắt để tránh lỗi std::exception
|
| 22 |
-
# use_angle_cls=True: Dùng tham số cũ cho tương thích (hoặc use_textline_orientation=True)
|
| 23 |
-
# lang='ch': Tiếng Trung
|
| 24 |
ocr = PaddleOCR(
|
| 25 |
-
|
| 26 |
-
lang='ch'
|
| 27 |
-
use_gpu=False,
|
| 28 |
-
enable_mkldnn=False, # QUAN TRỌNG NHẤT: Tắt tăng tốc phần cứng gây lỗi
|
| 29 |
-
show_log=False
|
| 30 |
)
|
| 31 |
except Exception as e:
|
| 32 |
-
print(f"Lỗi khởi tạo: {e}.
|
| 33 |
-
|
| 34 |
-
ocr = PaddleOCR(lang='ch', enable_mkldnn=False)
|
| 35 |
|
| 36 |
print("Model đã sẵn sàng!")
|
| 37 |
|
| 38 |
-
# --- HÀM QUÉT ĐỆ QUY ---
|
| 39 |
def deep_extract_text(data):
|
| 40 |
found_texts = []
|
|
|
|
| 41 |
if isinstance(data, str):
|
| 42 |
-
if len(data.strip()) > 0:
|
|
|
|
| 43 |
return []
|
|
|
|
| 44 |
if isinstance(data, (list, tuple)):
|
| 45 |
for item in data:
|
| 46 |
found_texts.extend(deep_extract_text(item))
|
|
|
|
| 47 |
elif isinstance(data, dict):
|
| 48 |
for val in data.values():
|
| 49 |
found_texts.extend(deep_extract_text(val))
|
|
|
|
| 50 |
elif hasattr(data, '__dict__'):
|
| 51 |
found_texts.extend(deep_extract_text(data.__dict__))
|
| 52 |
return found_texts
|
| 53 |
|
| 54 |
-
# --- HÀM LỌC RÁC ---
|
| 55 |
def clean_text_result(text_list):
|
| 56 |
cleaned = []
|
|
|
|
| 57 |
block_list = ['min', 'max', 'general', 'header', 'footer', 'structure']
|
|
|
|
| 58 |
for t in text_list:
|
| 59 |
t = t.strip()
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
if
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
cleaned.append(t)
|
| 65 |
return cleaned
|
| 66 |
|
|
@@ -69,18 +81,16 @@ def predict(image):
|
|
| 69 |
return "请上传图片 / Vui lòng tải ảnh lên."
|
| 70 |
|
| 71 |
try:
|
| 72 |
-
# --- CHUẨN HÓA ẢNH (FIX LỖI C++ CRASH) ---
|
| 73 |
-
# Paddle C++ rất ghét ảnh RGBA (trong suốt), bắt buộc convert về RGB
|
| 74 |
if isinstance(image, Image.Image):
|
| 75 |
-
if image.mode != 'RGB':
|
| 76 |
-
image = image.convert('RGB')
|
| 77 |
image = np.array(image)
|
| 78 |
|
| 79 |
-
# Gọi OCR
|
| 80 |
raw_result = ocr.ocr(image)
|
| 81 |
|
| 82 |
-
#
|
| 83 |
all_texts = deep_extract_text(raw_result)
|
|
|
|
|
|
|
| 84 |
final_texts = clean_text_result(all_texts)
|
| 85 |
|
| 86 |
if len(final_texts) > 0:
|
|
@@ -91,15 +101,16 @@ def predict(image):
|
|
| 91 |
except Exception as e:
|
| 92 |
import traceback
|
| 93 |
traceback.print_exc()
|
| 94 |
-
return f"Lỗi
|
| 95 |
|
| 96 |
-
# Giao diện
|
| 97 |
iface = gr.Interface(
|
| 98 |
fn=predict,
|
| 99 |
inputs=gr.Image(type="pil", label="Input Image"),
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
| 103 |
examples=[]
|
| 104 |
)
|
| 105 |
|
|
|
|
| 2 |
import logging
|
| 3 |
import os
|
| 4 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from paddleocr import PaddleOCR
|
| 6 |
from PIL import Image
|
| 7 |
import numpy as np
|
| 8 |
|
| 9 |
+
# Tắt log hệ thống
|
| 10 |
+
os.environ["CPP_MIN_LOG_LEVEL"] = "3"
|
| 11 |
logging.getLogger("ppocr").setLevel(logging.WARNING)
|
| 12 |
|
| 13 |
+
print("Đang khởi tạo PaddleOCR (PaddleX 3.0)...")
|
| 14 |
|
| 15 |
+
# --- PHẦN SỬA LỖI QUAN TRỌNG ---
|
| 16 |
+
# Đã xóa hoàn toàn 'use_gpu=False' để tránh lỗi ValueError
|
| 17 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
ocr = PaddleOCR(
|
| 19 |
+
use_textline_orientation=True,
|
| 20 |
+
lang='ch'
|
|
|
|
|
|
|
|
|
|
| 21 |
)
|
| 22 |
except Exception as e:
|
| 23 |
+
print(f"Lỗi khởi tạo tham số: {e}. Chuyển sang chế độ mặc định.")
|
| 24 |
+
ocr = PaddleOCR(lang='ch')
|
|
|
|
| 25 |
|
| 26 |
print("Model đã sẵn sàng!")
|
| 27 |
|
| 28 |
+
# --- HÀM QUÉT ĐỆ QUY (Để lấy text từ cấu trúc phức tạp) ---
|
| 29 |
def deep_extract_text(data):
|
| 30 |
found_texts = []
|
| 31 |
+
# Nếu là chuỗi -> Lấy luôn
|
| 32 |
if isinstance(data, str):
|
| 33 |
+
if len(data.strip()) > 0:
|
| 34 |
+
return [data]
|
| 35 |
return []
|
| 36 |
+
# Nếu là List/Tuple -> Quét từng phần tử
|
| 37 |
if isinstance(data, (list, tuple)):
|
| 38 |
for item in data:
|
| 39 |
found_texts.extend(deep_extract_text(item))
|
| 40 |
+
# Nếu là Dict -> Quét Values
|
| 41 |
elif isinstance(data, dict):
|
| 42 |
for val in data.values():
|
| 43 |
found_texts.extend(deep_extract_text(val))
|
| 44 |
+
# Nếu là Object lạ -> Quét thuộc tính
|
| 45 |
elif hasattr(data, '__dict__'):
|
| 46 |
found_texts.extend(deep_extract_text(data.__dict__))
|
| 47 |
return found_texts
|
| 48 |
|
| 49 |
+
# --- HÀM LỌC RÁC (Loại bỏ min, general, .ttf) ---
|
| 50 |
def clean_text_result(text_list):
|
| 51 |
cleaned = []
|
| 52 |
+
# Danh sách từ khóa rác cần chặn
|
| 53 |
block_list = ['min', 'max', 'general', 'header', 'footer', 'structure']
|
| 54 |
+
|
| 55 |
for t in text_list:
|
| 56 |
t = t.strip()
|
| 57 |
+
|
| 58 |
+
# 1. Bỏ qua chuỗi quá ngắn (trừ khi là chữ Hán)
|
| 59 |
+
if len(t) < 2:
|
| 60 |
+
# Kiểm tra Unicode range chữ Hán
|
| 61 |
+
if not any(u'\u4e00' <= c <= u'\u9fff' for c in t):
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
# 2. Bỏ qua file hệ thống
|
| 65 |
+
if t.lower().endswith(('.ttf', '.json', '.pdparams', '.yml', '.yaml')):
|
| 66 |
+
continue
|
| 67 |
+
|
| 68 |
+
# 3. Bỏ qua từ khóa hệ thống
|
| 69 |
+
if t.lower() in block_list:
|
| 70 |
+
continue
|
| 71 |
+
|
| 72 |
+
# 4. Chỉ lấy dòng có nội dung thực sự
|
| 73 |
+
if not re.search(r'[\w\u4e00-\u9fff]', t):
|
| 74 |
+
continue
|
| 75 |
+
|
| 76 |
cleaned.append(t)
|
| 77 |
return cleaned
|
| 78 |
|
|
|
|
| 81 |
return "请上传图片 / Vui lòng tải ảnh lên."
|
| 82 |
|
| 83 |
try:
|
|
|
|
|
|
|
| 84 |
if isinstance(image, Image.Image):
|
|
|
|
|
|
|
| 85 |
image = np.array(image)
|
| 86 |
|
| 87 |
+
# Gọi OCR (Không truyền tham số nào khác)
|
| 88 |
raw_result = ocr.ocr(image)
|
| 89 |
|
| 90 |
+
# Trích xuất toàn bộ text
|
| 91 |
all_texts = deep_extract_text(raw_result)
|
| 92 |
+
|
| 93 |
+
# Lọc sạch kết quả
|
| 94 |
final_texts = clean_text_result(all_texts)
|
| 95 |
|
| 96 |
if len(final_texts) > 0:
|
|
|
|
| 101 |
except Exception as e:
|
| 102 |
import traceback
|
| 103 |
traceback.print_exc()
|
| 104 |
+
return f"Lỗi xử lý: {str(e)}"
|
| 105 |
|
| 106 |
+
# Giao diện Gradio
|
| 107 |
iface = gr.Interface(
|
| 108 |
fn=predict,
|
| 109 |
inputs=gr.Image(type="pil", label="Input Image"),
|
| 110 |
+
# Bỏ show_copy_button=True để tránh lỗi với Gradio cũ
|
| 111 |
+
outputs=gr.Textbox(label="Kết quả (Đã lọc nhiễu)", lines=15),
|
| 112 |
+
title="PaddleOCR Tiếng Trung (PaddleX 3.0 Clean)",
|
| 113 |
+
description="Phiên bản đã Fix lỗi use_gpu và tích hợp bộ lọc rác thông minh.",
|
| 114 |
examples=[]
|
| 115 |
)
|
| 116 |
|