Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,33 +1,33 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import
|
| 3 |
-
from PIL import
|
| 4 |
import requests
|
| 5 |
|
| 6 |
-
# 加载模型和
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
model = AutoModel.from_pretrained(model_id, trust_remote_code=True)
|
| 10 |
|
| 11 |
-
|
|
|
|
| 12 |
if image is None:
|
| 13 |
-
return "请先上传图片"
|
| 14 |
-
|
| 15 |
-
# 保存临时图片
|
| 16 |
-
image_path = "temp_ocr_image.jpg"
|
| 17 |
-
image.save(image_path)
|
| 18 |
-
|
| 19 |
-
# 调用模型进行OCR识别
|
| 20 |
-
result = model.chat(tokenizer, image_path, ocr_type='ocr')
|
| 21 |
-
|
| 22 |
-
return result
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
)
|
| 32 |
|
| 33 |
-
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 3 |
+
from PIL import 图像
|
| 4 |
import requests
|
| 5 |
|
| 6 |
+
# 1. 加载模型和处理器 (从可靠的微软官方仓库)
|
| 7 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed")
|
| 8 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed")
|
|
|
|
| 9 |
|
| 10 |
+
# 2. 定义识别函数
|
| 11 |
+
def recognize_text(image):
|
| 12 |
if image is None:
|
| 13 |
+
return "请先上传一张清晰的图片。"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# 处理图片并生成文字
|
| 16 |
+
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
| 17 |
+
generated_ids = model.generate(pixel_values)
|
| 18 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 19 |
+
|
| 20 |
+
if not generated_text.strip():
|
| 21 |
+
return "未识别到文字。请确保图片清晰,且包含印刷体文字。"
|
| 22 |
+
return generated_text
|
| 23 |
+
|
| 24 |
+
# 3. 创建Gradio界面
|
| 25 |
+
iface = gr.Interface(
|
| 26 |
+
fn=recognize_text,
|
| 27 |
+
inputs=gr.Image(type="pil", label="上传图片"),
|
| 28 |
+
outputs=gr.Textbox(label="识别结果", lines=4),
|
| 29 |
+
title="图片文字识别器 (TrOCR)",
|
| 30 |
+
description="上传包含清晰印刷文字的图片,AI 将尝试提取文字。"
|
| 31 |
)
|
| 32 |
|
| 33 |
+
iface.launch()
|