YI-X commited on
Commit
57e2852
·
verified ·
1 Parent(s): bbcaa1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -25
app.py CHANGED
@@ -1,33 +1,33 @@
1
  import gradio as gr
2
- from transformers import AutoModel, AutoTokenizer
3
- from PIL import Image
4
  import requests
5
 
6
- # 加载模型和分词器
7
- model_id = "PaddlePaddle/PaddleOCR-VL-0.9B"
8
- tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
9
- model = AutoModel.from_pretrained(model_id, trust_remote_code=True)
10
 
11
- def extract_text_from_image(image):
 
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
- # 创建Gradio界面
25
- demo = gr.Interface(
26
- fn=extract_text_from_image,
27
- inputs=gr.Image(type="pil", label="上传包含文字的图片"),
28
- outputs=gr.Textbox(label="识别出的文字", lines=10),
29
- title="OCR文字识别器",
30
- description="上传一张包含文字的图片,AI会自动识别并提取其中的文字内容。支持中英文混合识别。"
 
 
 
 
 
 
 
 
 
31
  )
32
 
33
- demo.launch()
 
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()