Mageia commited on
Commit
dd08fd0
1 Parent(s): 490e90d

fix: process pdf once

Browse files
Files changed (2) hide show
  1. app-pdf.py +66 -108
  2. app.py +53 -37
app-pdf.py CHANGED
@@ -1,32 +1,20 @@
 
1
  import os
2
- import shutil
3
- import uuid
4
 
5
- import fitz # PyMuPDF
6
  import gradio as gr
 
7
  import torch
8
  from PIL import Image, ImageEnhance
9
- from transformers import AutoConfig, AutoModel, AutoTokenizer
10
 
11
- from got_ocr import got_ocr
12
-
13
- # 初始化模型和分词器
14
- # model_name = "stepfun-ai/GOT-OCR2_0"
15
  model_name = "ucaslcl/GOT-OCR2_0"
16
  device = "cuda" if torch.cuda.is_available() else "cpu"
17
 
18
  tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
19
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
20
- model = AutoModel.from_pretrained(model_name, trust_remote_code=True, low_cpu_mem_usage=True, device_map="cuda", use_safetensors=True)
21
  model = model.eval().to(device)
22
- model.config.pad_token_id = tokenizer.eos_token_id
23
-
24
- UPLOAD_FOLDER = "./uploads"
25
- RESULTS_FOLDER = "./results"
26
-
27
- # 确保必要的文件夹存在
28
- os.makedirs(UPLOAD_FOLDER, exist_ok=True)
29
- os.makedirs(RESULTS_FOLDER, exist_ok=True)
30
 
31
 
32
  def pdf_to_images(pdf_path):
@@ -34,8 +22,7 @@ def pdf_to_images(pdf_path):
34
  pdf_document = fitz.open(pdf_path)
35
  for page_num in range(len(pdf_document)):
36
  page = pdf_document.load_page(page_num)
37
- # 进一步增加分辨率和缩放比例
38
- zoom = 10 # 增加缩放比例到4
39
  mat = fitz.Matrix(zoom, zoom)
40
  pix = page.get_pixmap(matrix=mat, alpha=False)
41
  img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
@@ -49,116 +36,87 @@ def pdf_to_images(pdf_path):
49
  return images
50
 
51
 
52
- def process_pdf(pdf_file):
53
- if pdf_file is None:
54
- return None
55
-
56
- temp_pdf_path = os.path.join(UPLOAD_FOLDER, f"{uuid.uuid4()}.pdf")
57
-
58
- # 使用 shutil 复制上传的件到临时位置
59
- shutil.copy(pdf_file.name, temp_pdf_path)
60
-
61
- images = pdf_to_images(temp_pdf_path)
62
- os.remove(temp_pdf_path)
63
 
64
- # 将图像保存为临时文件并返回文件路径列表
65
- image_paths = []
66
- for i, img in enumerate(images):
67
- img_path = os.path.join(RESULTS_FOLDER, f"page_{i+1}.png")
68
- img.save(img_path, "PNG")
69
- image_paths.append(img_path)
70
 
71
- return image_paths
 
72
 
 
 
 
 
73
 
74
- def on_image_select(evt: gr.SelectData):
75
- if evt.index is not None:
76
- return evt.index
77
- return None
78
 
 
 
79
 
80
- # 更新perform_ocr函数的输入参数
81
- def perform_ocr(selected_index, image_gallery, got_mode, fine_grained_type, color, box):
82
- if selected_index is None or len(image_gallery) == 0:
83
- return "请先选择一张图片"
84
 
85
- selected_image = image_gallery[selected_index][0]
 
 
 
86
 
87
- # 根据选择的任务和参数调用GOT OCR
88
- ocr_color = color if fine_grained_type == "color" else ""
89
- ocr_box = box if fine_grained_type == "box" else ""
90
-
91
- result, html_content = got_ocr(
92
- model,
93
- tokenizer,
94
- selected_image,
95
- got_mode=got_mode,
96
- fine_grained_mode=fine_grained_type,
97
- ocr_color=ocr_color,
98
- ocr_box=ocr_box,
99
- )
100
-
101
- if html_content:
102
- iframe_src = f"data:text/html;base64,{html_content}"
103
- iframe = f'<iframe src="{iframe_src}" width="100%" height="600px"></iframe>'
104
- download_link = f'<a href="data:text/html;base64,{html_content}" download="result.html">下载完整结果</a>'
105
- return gr.Markdown(f"{download_link}\n\n{iframe}")
106
- else:
107
- return gr.Markdown(result)
108
 
 
 
109
 
110
- def task_update(task):
111
- if "fine-grained" in task:
112
- return [gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)]
113
- else:
114
- return [gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)]
 
 
 
 
 
 
115
 
 
 
 
 
 
 
 
 
116
 
117
- def fine_grained_update(fine_grained_type):
118
- if fine_grained_type == "color":
119
- return [gr.update(visible=True), gr.update(visible=False)]
120
- elif fine_grained_type == "box":
121
- return [gr.update(visible=False), gr.update(visible=True)]
122
- else:
123
- return [gr.update(visible=False), gr.update(visible=False)]
124
 
125
 
126
  with gr.Blocks() as demo:
127
- pdf_input = gr.File(label="上传PDF文件")
128
- image_gallery = gr.Gallery(
129
- label="PDF页面预览",
130
- columns=3,
131
- height=600,
132
- object_fit="contain",
133
- preview=True,
134
- )
135
- selected_index = gr.State(None)
136
- pdf_input.upload(fn=process_pdf, inputs=pdf_input, outputs=image_gallery)
137
- image_gallery.select(fn=on_image_select, inputs=[], outputs=selected_index)
138
 
139
- ####################
140
- task_dropdown = gr.Dropdown(
141
  choices=["plain texts OCR", "format texts OCR", "plain multi-crop OCR", "format multi-crop OCR", "plain fine-grained OCR", "format fine-grained OCR"],
142
- label="选择GOT模式",
143
- value="format texts OCR",
144
  )
145
- fine_grained_dropdown = gr.Dropdown(choices=["box", "color"], label="fine-grained类型", visible=False)
146
- color_dropdown = gr.Dropdown(choices=["red", "green", "blue"], label="颜色列表", visible=False)
147
- box_input = gr.Textbox(label="输入框: [x1,y1,x2,y2]", placeholder="例如: [0,0,100,100]", visible=False)
148
 
149
- ocr_button = gr.Button("开始OCR识别")
150
- ocr_result = gr.HTML(label="OCR结果") # 将Textbox更改为HTML组件
 
151
 
152
- task_dropdown.change(task_update, inputs=[task_dropdown], outputs=[fine_grained_dropdown, color_dropdown, box_input])
153
- fine_grained_dropdown.change(fine_grained_update, inputs=[fine_grained_dropdown], outputs=[color_dropdown, box_input])
154
 
155
- # 更新ocr_button的click事件,传递所有必要的参数
156
- ocr_button.click(
157
- fn=perform_ocr,
158
- inputs=[selected_index, image_gallery, task_dropdown, fine_grained_dropdown, color_dropdown, box_input],
159
- outputs=ocr_result,
160
- )
161
 
 
162
 
163
  if __name__ == "__main__":
164
  demo.launch()
 
1
+ import base64
2
  import os
3
+ import tempfile
 
4
 
5
+ import fitz
6
  import gradio as gr
7
+ import spaces
8
  import torch
9
  from PIL import Image, ImageEnhance
10
+ from transformers import AutoModel, AutoTokenizer
11
 
 
 
 
 
12
  model_name = "ucaslcl/GOT-OCR2_0"
13
  device = "cuda" if torch.cuda.is_available() else "cpu"
14
 
15
  tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
16
+ model = AutoModel.from_pretrained(model_name, trust_remote_code=True, device_map=device)
 
17
  model = model.eval().to(device)
 
 
 
 
 
 
 
 
18
 
19
 
20
  def pdf_to_images(pdf_path):
 
22
  pdf_document = fitz.open(pdf_path)
23
  for page_num in range(len(pdf_document)):
24
  page = pdf_document.load_page(page_num)
25
+ zoom = 10 # 增加缩放比例到10
 
26
  mat = fitz.Matrix(zoom, zoom)
27
  pix = page.get_pixmap(matrix=mat, alpha=False)
28
  img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
 
36
  return images
37
 
38
 
39
+ @spaces.GPU()
40
+ def ocr_process(file, got_mode, ocr_color="", ocr_box="", progress=gr.Progress()):
41
+ if file is None:
42
+ return "错误:未提供文件"
 
 
 
 
 
 
 
43
 
44
+ try:
45
+ progress(0, desc="开始处理...")
 
 
 
 
46
 
47
+ with tempfile.TemporaryDirectory() as temp_dir:
48
+ file_path = file.name # 使用文件的原始路径
49
 
50
+ if file_path.lower().endswith(".pdf"):
51
+ images = pdf_to_images(file_path)
52
+ num_pages = len(images)
53
+ results = []
54
 
55
+ for i, image in enumerate(images):
56
+ progress((i + 1) / num_pages, desc=f"处理第 {i+1}/{num_pages} 页...")
57
+ img_path = os.path.join(temp_dir, f"page_{i+1}.png")
58
+ image.save(img_path, "PNG")
59
 
60
+ result = process_single_image(img_path, got_mode, ocr_color, ocr_box)
61
+ results.append(f"第 {i+1} 页结果:\n{result}")
62
 
63
+ final_result = "\n\n".join(results)
64
+ else:
65
+ final_result = process_single_image(file_path, got_mode, ocr_color, ocr_box)
 
66
 
67
+ progress(1, desc="处理完成")
68
+ return final_result
69
+ except Exception as e:
70
+ return f"错误: {str(e)}"
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ def process_single_image(image_path, got_mode, ocr_color, ocr_box):
74
+ result_path = f"{os.path.splitext(image_path)[0]}_result.html"
75
 
76
+ if "plain" in got_mode:
77
+ if "multi-crop" in got_mode:
78
+ res = model.chat_crop(tokenizer, image_path, ocr_type="ocr")
79
+ else:
80
+ res = model.chat(tokenizer, image_path, ocr_type="ocr", ocr_box=ocr_box, ocr_color=ocr_color)
81
+ return res
82
+ elif "format" in got_mode:
83
+ if "multi-crop" in got_mode:
84
+ res = model.chat_crop(tokenizer, image_path, ocr_type="format", render=True, save_render_file=result_path)
85
+ else:
86
+ res = model.chat(tokenizer, image_path, ocr_type="format", ocr_box=ocr_box, ocr_color=ocr_color, render=True, save_render_file=result_path)
87
 
88
+ if os.path.exists(result_path):
89
+ with open(result_path, "r", encoding="utf-8") as f:
90
+ html_content = f.read()
91
+ encoded_html = base64.b64encode(html_content.encode("utf-8")).decode("utf-8")
92
+ data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
93
+ preview = f'<iframe src="{data_uri}" width="100%" height="600px"></iframe>'
94
+ download_link = f'<a href="{data_uri}" download="result.html">下载完整结果</a>'
95
+ return f"{download_link}\n\n{preview}"
96
 
97
+ return "错误: 未知的OCR模式"
 
 
 
 
 
 
98
 
99
 
100
  with gr.Blocks() as demo:
101
+ gr.Markdown("# OCR 图像识别")
102
+
103
+ file_input = gr.File(label="上传PDF或图片文件")
 
 
 
 
 
 
 
 
104
 
105
+ got_mode = gr.Dropdown(
 
106
  choices=["plain texts OCR", "format texts OCR", "plain multi-crop OCR", "format multi-crop OCR", "plain fine-grained OCR", "format fine-grained OCR"],
107
+ label="OCR模式",
108
+ value="plain texts OCR",
109
  )
 
 
 
110
 
111
+ with gr.Row():
112
+ ocr_color = gr.Textbox(label="OCR颜色 (仅用于fine-grained模式)")
113
+ ocr_box = gr.Textbox(label="OCR边界框 (仅用于fine-grained模式)")
114
 
115
+ submit_button = gr.Button("开始OCR识别")
 
116
 
117
+ output = gr.HTML(label="识别结果")
 
 
 
 
 
118
 
119
+ submit_button.click(ocr_process, inputs=[file_input, got_mode, ocr_color, ocr_box], outputs=output)
120
 
121
  if __name__ == "__main__":
122
  demo.launch()
app.py CHANGED
@@ -37,35 +37,38 @@ def pdf_to_images(pdf_path):
37
 
38
 
39
  @spaces.GPU()
40
- def ocr_process(file, got_mode, ocr_color="", ocr_box="", progress=gr.Progress()):
41
  if file is None:
42
- return "错误:未提供文件"
43
 
44
  try:
45
- progress(0, desc="开始处理...")
 
46
 
47
- with tempfile.TemporaryDirectory() as temp_dir:
48
- file_path = file.name # 使用文件的原始路径
49
 
50
- if file_path.lower().endswith(".pdf"):
51
- images = pdf_to_images(file_path)
52
- num_pages = len(images)
53
- results = []
 
54
 
55
- for i, image in enumerate(images):
56
- progress((i + 1) / num_pages, desc=f"处理第 {i+1}/{num_pages} 页...")
57
- img_path = os.path.join(temp_dir, f"page_{i+1}.png")
58
- image.save(img_path, "PNG")
59
 
60
- result = process_single_image(img_path, got_mode, ocr_color, ocr_box)
61
- results.append(f"第 {i+1} 页结果:\n{result}")
62
 
63
- final_result = "\n\n".join(results)
64
- else:
65
- final_result = process_single_image(file_path, got_mode, ocr_color, ocr_box)
 
66
 
 
 
 
67
  progress(1, desc="处理完成")
68
- return final_result
69
  except Exception as e:
70
  return f"错误: {str(e)}"
71
 
@@ -92,7 +95,7 @@ def process_single_image(image_path, got_mode, ocr_color, ocr_box):
92
  data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
93
  preview = f'<iframe src="{data_uri}" width="100%" height="600px"></iframe>'
94
  download_link = f'<a href="{data_uri}" download="result.html">下载完整结果</a>'
95
- return f"{download_link}\n\n{preview}\n\n识别结果:\n{res}"
96
 
97
  return "错误: 未知的OCR模式"
98
 
@@ -100,23 +103,36 @@ def process_single_image(image_path, got_mode, ocr_color, ocr_box):
100
  with gr.Blocks() as demo:
101
  gr.Markdown("# OCR 图像识别")
102
 
103
- file_input = gr.File(label="上传PDF或图片文件")
104
-
105
- got_mode = gr.Dropdown(
106
- choices=["plain texts OCR", "format texts OCR", "plain multi-crop OCR", "format multi-crop OCR", "plain fine-grained OCR", "format fine-grained OCR"],
107
- label="OCR模式",
108
- value="plain texts OCR",
109
- )
110
-
111
- with gr.Row():
112
- ocr_color = gr.Textbox(label="OCR颜色 (仅用于fine-grained模式)")
113
- ocr_box = gr.Textbox(label="OCR边界框 (仅用于fine-grained模式)")
114
-
115
- submit_button = gr.Button("开始OCR识别")
116
-
117
- output = gr.HTML(label="识别结果")
118
-
119
- submit_button.click(ocr_process, inputs=[file_input, got_mode, ocr_color, ocr_box], outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  if __name__ == "__main__":
122
  demo.launch()
 
37
 
38
 
39
  @spaces.GPU()
40
+ def convert_pdf_to_images(file):
41
  if file is None:
42
+ return "错误:未提供文件", None
43
 
44
  try:
45
+ if not file.name.lower().endswith(".pdf"):
46
+ return "错误:请上传PDF文件", None
47
 
48
+ images = pdf_to_images(file.name)
49
+ image_paths = []
50
 
51
+ with tempfile.TemporaryDirectory() as temp_dir:
52
+ for i, image in enumerate(images):
53
+ img_path = os.path.join(temp_dir, f"page_{i+1}.png")
54
+ image.save(img_path, "PNG")
55
+ image_paths.append(img_path)
56
 
57
+ return "PDF转换为图片成功", image_paths
58
+ except Exception as e:
59
+ return f"错误: {str(e)}", None
 
60
 
 
 
61
 
62
+ @spaces.GPU()
63
+ def ocr_process(image, got_mode, ocr_color="", ocr_box="", progress=gr.Progress()):
64
+ if image is None:
65
+ return "错误:未选择图片"
66
 
67
+ try:
68
+ progress(0, desc="开始处理...")
69
+ result = process_single_image(image, got_mode, ocr_color, ocr_box)
70
  progress(1, desc="处理完成")
71
+ return result
72
  except Exception as e:
73
  return f"错误: {str(e)}"
74
 
 
95
  data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
96
  preview = f'<iframe src="{data_uri}" width="100%" height="600px"></iframe>'
97
  download_link = f'<a href="{data_uri}" download="result.html">下载完整结果</a>'
98
+ return f"{download_link}\n\n{preview}"
99
 
100
  return "错误: 未知的OCR模式"
101
 
 
103
  with gr.Blocks() as demo:
104
  gr.Markdown("# OCR 图像识别")
105
 
106
+ with gr.Tab("PDF转图片"):
107
+ pdf_input = gr.File(label="上传PDF文件")
108
+ convert_button = gr.Button("转换PDF为图片")
109
+ pdf_output = gr.Textbox(label="转换结果")
110
+ image_gallery = gr.Gallery(label="图片预览").style(grid=3)
111
+
112
+ with gr.Tab("OCR处理"):
113
+ image_input = gr.Image(label="选择或上传图片")
114
+ got_mode = gr.Dropdown(
115
+ choices=[
116
+ "plain texts OCR",
117
+ "format texts OCR",
118
+ "plain multi-crop OCR",
119
+ "format multi-crop OCR",
120
+ "plain fine-grained OCR",
121
+ "format fine-grained OCR",
122
+ ],
123
+ label="OCR模式",
124
+ value="plain texts OCR",
125
+ )
126
+
127
+ with gr.Row():
128
+ ocr_color = gr.Textbox(label="OCR颜色 (仅用于fine-grained模式)")
129
+ ocr_box = gr.Textbox(label="OCR边界框 (仅用于fine-grained模式)")
130
+
131
+ ocr_button = gr.Button("开始OCR识别")
132
+ ocr_output = gr.HTML(label="识别结果")
133
+
134
+ convert_button.click(convert_pdf_to_images, inputs=[pdf_input], outputs=[pdf_output, image_gallery])
135
+ ocr_button.click(ocr_process, inputs=[image_input, got_mode, ocr_color, ocr_box], outputs=ocr_output)
136
 
137
  if __name__ == "__main__":
138
  demo.launch()