1oscon commited on
Commit
c8d8d3a
·
verified ·
1 Parent(s): 11b9fab

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from paddleocr import PaddleOCR
3
+ import fitz # PyMuPDF
4
+ from PIL import Image
5
+ import numpy as np
6
+ import os
7
+
8
+ # 设置环境变量,防止一些不必要的日志输出
9
+ os.environ['KMP_DUPLICATE_LIB_OK']='True'
10
+
11
+ # 初始化PaddleOCR,强制使用CPU
12
+ # 第一次运行时会自动下载模型,会比较慢,请耐心等待
13
+ print("正在加载PaddleOCR模型...")
14
+ # 同时支持中文和英文识别
15
+ ocr = PaddleOCR(use_angle_cls=True, lang='ch', use_gpu=False, show_log=False)
16
+ print("模型加载完成。")
17
+
18
+ def pdf_ocr_process(pdf_file):
19
+ """
20
+ 接收上传的PDF文件,使用PaddleOCR进行识别,并返回纯文本结果。
21
+ """
22
+ if pdf_file is None:
23
+ return "请上传一个PDF文件进行识别。"
24
+
25
+ try:
26
+ # 从上传的文件对象中读取字节流
27
+ pdf_bytes = pdf_file.read()
28
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
29
+
30
+ full_text = []
31
+
32
+ # 遍历PDF的每一页
33
+ for page_num in range(len(doc)):
34
+ page = doc.load_page(page_num)
35
+ # 将页面转换为高分辨率的PNG图像
36
+ pix = page.get_pixmap(dpi=300)
37
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
38
+
39
+ # PaddleOCR需要一个Numpy数组格式的图像
40
+ img_np = np.array(img)
41
+
42
+ # 执行OCR识别
43
+ result = ocr.ocr(img_np, cls=True)
44
+
45
+ # 提取识别出的文本行
46
+ page_texts = []
47
+ if result and result[0]: # 确保result不是None或空
48
+ for line in result[0]:
49
+ page_texts.append(line[1][0]) # line[1][0] 是文本内容
50
+
51
+ # 将当页的文本拼接起来
52
+ full_text.append(f"--- Page {page_num + 1} ---\n" + "\n".join(page_texts))
53
+
54
+ doc.close()
55
+
56
+ return "\n\n".join(full_text)
57
+
58
+ except Exception as e:
59
+ return f"处理过程中发生错误: {str(e)}"
60
+
61
+ # 创建并启动Gradio界面
62
+ iface = gr.Interface(
63
+ fn=pdf_ocr_process,
64
+ inputs=gr.File(label="上传PDF文件", file_types=[".pdf"]),
65
+ outputs=gr.Textbox(label="识别结果 (PaddleOCR)", lines=25, show_copy_button=True),
66
+ title="免费部署的PDF文档识别 (PaddleOCR)",
67
+ description="这是一个完全免费的OCR方案,基于PaddleOCR。它在CPU上运行,处理速度取决于文档的复杂度和页数。首次运行或长时间未使用后启动较慢。",
68
+ examples=[["sample.pdf"]]
69
+ )
70
+
71
+ iface.launch()