PaddleOCR / app.py
ranbac's picture
Update app.py
56d51db verified
raw
history blame
2.53 kB
import gradio as gr
import logging
import os
from paddleocr import PaddleOCR
from PIL import Image
import numpy as np
# 1. Cấu hình tắt log bằng code hệ thống (Thay vì truyền tham số show_log)
os.environ["CPP_MIN_LOG_LEVEL"] = "3"
logging.getLogger("ppocr").setLevel(logging.WARNING)
print("Đang khởi tạo PaddleOCR (Chinese Model)...")
# 2. KHỞI TẠO MODEL (Đã sửa lỗi)
# - Bỏ show_log=False (Gây lỗi crash)
# - Bỏ use_gpu=False (Gây lỗi crash ở bản mới, Paddle tự nhận diện CPU)
# - Đổi use_angle_cls -> use_textline_orientation (Theo chuẩn mới)
try:
# Cách khởi tạo chuẩn cho PaddleOCR v2.9+
ocr = PaddleOCR(
use_textline_orientation=True,
lang='ch'
)
except TypeError as e:
# Trường hợp dự phòng nếu thư viện thay đổi API bất ngờ
print(f"Cảnh báo khởi tạo: {e}. Chuyển sang chế độ tối giản.")
ocr = PaddleOCR(lang='ch')
except ValueError as e:
# Xử lý lỗi tham số lạ
print(f"Lỗi tham số: {e}. Đang thử lại không tham số phụ...")
ocr = PaddleOCR(lang='ch')
print("Model đã sẵn sàng hoạt động!")
def predict(image):
if image is None:
return "请上传图片 / Vui lòng tải ảnh lên."
try:
# Chuyển đổi ảnh PIL sang Numpy array
if isinstance(image, Image.Image):
image = np.array(image)
# Thực hiện nhận dạng
result = ocr.ocr(image, cls=True)
txts = []
if result and result[0]:
for line in result[0]:
text = line[1][0]
confidence = line[1][1]
# Lọc kết quả có độ tin cậy > 50%
if confidence > 0.5:
txts.append(text)
return "\n".join(txts)
else:
return "未发现文字 / Không tìm thấy văn bản."
except Exception as e:
return f"Error / Lỗi hệ thống: {str(e)}"
# Giao diện Gradio
iface = gr.Interface(
fn=predict,
inputs=gr.Image(type="pil", label="上传图片 / Upload Image"),
outputs=gr.Textbox(label="结果 / Result", lines=15, show_copy_button=True),
title="PaddleOCR Chinese - CPU Fixed",
description="Phiên bản đã sửa lỗi tham số 'show_log'. Chạy ổn định trên Hugging Face CPU.",
examples=[]
)
if __name__ == "__main__":
iface.launch(server_name="0.0.0.0", server_port=7860)