1oscon commited on
Commit
3d8e7a8
·
verified ·
1 Parent(s): d337cf9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -45
app.py CHANGED
@@ -4,65 +4,107 @@ 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,明确指定使用中文模型 (lang='ch')
12
- print("正在加载PaddleOCR中文模型...")
13
- ocr = PaddleOCR(use_textline_orientation=True, lang='ch')
14
- print("模型加载完成。")
 
 
 
 
15
 
16
- def pdf_ocr_process(pdf_file):
 
 
 
17
  """
18
- 接收上传的PDF文件,使用PaddleOCR进行识别,并返回纯文本结果。
19
  """
20
  if pdf_file is None:
21
- return "请上传一个PDF文件进行识别。"
22
 
23
  try:
24
- # Gradio传递的是一个临时文件对象,我们使用它的.name属性获取文件路径
25
- doc = fitz.open(pdf_file.name)
26
-
27
- full_text = []
28
 
29
- # 遍历PDF的每一页
30
- for page_num in range(len(doc)):
31
- page = doc.load_page(page_num)
32
- # 将页面转换为高分辨率的PNG图像,以提高识别准确率
33
- pix = page.get_pixmap(dpi=300)
34
- img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
35
-
36
- # 转换为PaddleOCR需要的Numpy数组格式
37
- img_np = np.array(img)
38
-
39
- # --- 核心修正 ---
40
- # 执行OCR识别,移除新版本中已不接受的 'cls' 参数
41
- result = ocr.ocr(img_np)
42
-
43
- # 提取识别出的文本行
44
- page_texts = []
45
- if result and result[0]: # 确保result不是None或空
46
- for line in result[0]:
47
- page_texts.append(line[1][0]) # line[1][0] 是文本内容
48
 
49
- # 将当页的文本拼接起来
50
- full_text.append(f"--- Page {page_num + 1} ---\n" + "\n".join(page_texts))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  doc.close()
53
 
54
- return "\n\n".join(full_text)
 
 
 
 
 
 
 
 
55
 
56
  except Exception as e:
57
- return f"处理过程中发生错误: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- # 创建并启动Gradio界面
60
- iface = gr.Interface(
61
- fn=pdf_ocr_process,
62
- inputs=gr.File(label="上传PDF文件", file_types=[".pdf"]),
63
- outputs=gr.Textbox(label="中文识别结果 (PaddleOCR)", lines=25, show_copy_button=True),
64
- title="免费部署的中文PDF文档识别",
65
- description="此应用基于PaddleOCR,为中文识别特别优化。它在CPU上运行,处理速度取决于文档的复杂度和页数。"
66
- )
67
 
68
- iface.launch()
 
4
  from PIL import Image
5
  import numpy as np
6
  import os
7
+ import time
8
 
9
+ # --- 配置 ---
10
+ OUTPUT_DIR = "output_results" # 保存结果的文件夹
11
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
12
 
13
+ # --- 模型加载器 ---
14
+ # 将模型加载封装成函数,确保只在GPU会话中加载
15
+ def load_gpu_model():
16
+ print("正在加载PaddleOCR GPU模型...")
17
+ # 核心改动:use_gpu=True, 强制使用GPU
18
+ ocr_model = PaddleOCR(use_textline_orientation=True, lang='ch', use_gpu=True, show_log=False)
19
+ print("GPU模型加载完成。")
20
+ return ocr_model
21
 
22
+ # --- Gradio调用的核心处理函数 ---
23
+ # 核心改动:使用@spaces.GPU申请GPU资源
24
+ @spaces.GPU
25
+ def process_pdf_max_speed(pdf_file, progress=gr.Progress(track_tqdm=True)):
26
  """
27
+ 使用GPU和批处理来极速处理PDF,并实时更新进度条。
28
  """
29
  if pdf_file is None:
30
+ return "请先上传一个PDF文件。", None
31
 
32
  try:
33
+ # 在GPU会话中加载模型
34
+ ocr = load_gpu_model()
 
 
35
 
36
+ # --- 准备工作 ---
37
+ doc = fitz.open(pdf_file.name)
38
+ total_pages = len(doc)
39
+ batch_size = 4 # 批处理大小,一次性处理4页,可以充分利用GPU
40
+ full_text_result = []
41
+
42
+ # --- 核心处理循环 ---
43
+ # gr.Progress(track_tqdm=True) 会自动创建一个漂亮的进度条
44
+ for i in progress.tqdm(range(0, total_pages, batch_size), desc="🚀 批处理中..."):
 
 
 
 
 
 
 
 
 
 
45
 
46
+ batch_images = []
47
+ # 准备一个批次的图片
48
+ for page_num in range(i, min(i + batch_size, total_pages)):
49
+ page = doc.load_page(page_num)
50
+ pix = page.get_pixmap(dpi=200)
51
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
52
+ # PaddleOCR可以直接处理Numpy数组
53
+ batch_images.append(np.array(img))
54
+
55
+ # --- 速度核心:一次性识别一个批次的图片 ---
56
+ if batch_images:
57
+ results = ocr.ocr(batch_images)
58
+
59
+ # 整理这个批次的结果
60
+ for page_index, page_result in enumerate(results):
61
+ page_texts = []
62
+ current_page_num = i + page_index + 1
63
+ if page_result:
64
+ for line in page_result:
65
+ page_texts.append(line[1][0])
66
+
67
+ full_text_result.append(f"--- Page {current_page_num} ---\n" + "\n".join(page_texts))
68
 
69
  doc.close()
70
 
71
+ # --- 保存最终结果 ---
72
+ final_text = "\n\n".join(full_text_result)
73
+ output_filename = os.path.join(OUTPUT_DIR, f"{os.path.splitext(os.path.basename(pdf_file.name))[0]}_result.txt")
74
+ with open(output_filename, 'w', encoding='utf-8') as f:
75
+ f.write(final_text)
76
+
77
+ print(f"处理完成!结果已保存到 {output_filename}")
78
+ # 返回文本内容和可供下载的文件路径
79
+ return final_text, output_filename
80
 
81
  except Exception as e:
82
+ error_message = f"处理过程中发生错误: {str(e)}"
83
+ print(error_message)
84
+ return error_message, None
85
+
86
+ # --- 构建Gradio界面 ---
87
+ with gr.Blocks(title="��速PDF识别器", theme=gr.themes.Soft()) as demo:
88
+ gr.Markdown(
89
+ """
90
+ # 🔥 极速PDF识别器 (GPU加速版) 🔥
91
+ **速度拉满!实时进度显示,但处理期间请勿关闭页面。**
92
+ """
93
+ )
94
+
95
+ with gr.Row():
96
+ pdf_input = gr.File(label="📄 上传PDF文件", file_types=[".pdf"])
97
+
98
+ submit_btn = gr.Button("⚡️ 开始极速处理", variant="primary")
99
+
100
+ result_display = gr.Textbox(label="识别结果", lines=20, show_copy_button=True)
101
+ download_link = gr.File(label="📥 点击此处下载结果文件", interactive=False)
102
 
103
+ # 按钮和函数的连接
104
+ submit_btn.click(
105
+ fn=process_pdf_max_speed,
106
+ inputs=[pdf_input],
107
+ outputs=[result_display, download_link]
108
+ )
 
 
109
 
110
+ demo.queue().launch()