Spaces:
Running
Running
add: pdf2images
Browse files- app-ocr.py +149 -0
- app.py +29 -130
- requirements.txt +1 -0
app-ocr.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
import io
|
3 |
+
import os
|
4 |
+
import shutil
|
5 |
+
import time
|
6 |
+
import uuid
|
7 |
+
from pathlib import Path
|
8 |
+
|
9 |
+
# import numpy as np
|
10 |
+
# import tempfile
|
11 |
+
# from PIL import Image
|
12 |
+
import gradio as gr
|
13 |
+
from modelscope import AutoModel, AutoTokenizer
|
14 |
+
|
15 |
+
UPLOAD_FOLDER = "./uploads"
|
16 |
+
RESULTS_FOLDER = "./results"
|
17 |
+
|
18 |
+
|
19 |
+
tokenizer = AutoTokenizer.from_pretrained("stepfun-ai/GOT-OCR2_0", trust_remote_code=True)
|
20 |
+
model = AutoModel.from_pretrained("stepfun-ai/GOT-OCR2_0", trust_remote_code=True, low_cpu_mem_usage=True, device_map="cuda", use_safetensors=True)
|
21 |
+
model = model.eval().cuda()
|
22 |
+
|
23 |
+
for folder in [UPLOAD_FOLDER, RESULTS_FOLDER]:
|
24 |
+
if not os.path.exists(folder):
|
25 |
+
os.makedirs(folder)
|
26 |
+
|
27 |
+
|
28 |
+
def image_to_base64(image):
|
29 |
+
buffered = io.BytesIO()
|
30 |
+
image.save(buffered, format="PNG")
|
31 |
+
return base64.b64encode(buffered.getvalue()).decode()
|
32 |
+
|
33 |
+
|
34 |
+
def run_GOT(image, got_mode, fine_grained_mode="", ocr_color="", ocr_box=""):
|
35 |
+
unique_id = str(uuid.uuid4())
|
36 |
+
image_path = os.path.join(UPLOAD_FOLDER, f"{unique_id}.png")
|
37 |
+
result_path = os.path.join(RESULTS_FOLDER, f"{unique_id}.html")
|
38 |
+
|
39 |
+
shutil.copy(image, image_path)
|
40 |
+
|
41 |
+
try:
|
42 |
+
if got_mode == "plain texts OCR":
|
43 |
+
res = model.chat(tokenizer, image_path, ocr_type="ocr")
|
44 |
+
return res, None
|
45 |
+
elif got_mode == "format texts OCR":
|
46 |
+
res = model.chat(tokenizer, image_path, ocr_type="format", render=True, save_render_file=result_path)
|
47 |
+
elif got_mode == "plain multi-crop OCR":
|
48 |
+
res = model.chat_crop(tokenizer, image_path, ocr_type="ocr")
|
49 |
+
return res, None
|
50 |
+
elif got_mode == "format multi-crop OCR":
|
51 |
+
res = model.chat_crop(tokenizer, image_path, ocr_type="format", render=True, save_render_file=result_path)
|
52 |
+
elif got_mode == "plain fine-grained OCR":
|
53 |
+
res = model.chat(tokenizer, image_path, ocr_type="ocr", ocr_box=ocr_box, ocr_color=ocr_color)
|
54 |
+
return res, None
|
55 |
+
elif got_mode == "format fine-grained OCR":
|
56 |
+
res = model.chat(tokenizer, image_path, ocr_type="format", ocr_box=ocr_box, ocr_color=ocr_color, render=True, save_render_file=result_path)
|
57 |
+
|
58 |
+
# res_markdown = f"$$ {res} $$"
|
59 |
+
res_markdown = res
|
60 |
+
|
61 |
+
if "format" in got_mode and os.path.exists(result_path):
|
62 |
+
with open(result_path, "r") as f:
|
63 |
+
html_content = f.read()
|
64 |
+
encoded_html = base64.b64encode(html_content.encode("utf-8")).decode("utf-8")
|
65 |
+
iframe_src = f"data:text/html;base64,{encoded_html}"
|
66 |
+
iframe = f'<iframe src="{iframe_src}" width="100%" height="600px"></iframe>'
|
67 |
+
download_link = f'<a href="data:text/html;base64,{encoded_html}" download="result_{unique_id}.html">Download Full Result</a>'
|
68 |
+
return res_markdown, f"{download_link}<br>{iframe}"
|
69 |
+
else:
|
70 |
+
return res_markdown, None
|
71 |
+
except Exception as e:
|
72 |
+
return f"Error: {str(e)}", None
|
73 |
+
finally:
|
74 |
+
if os.path.exists(image_path):
|
75 |
+
os.remove(image_path)
|
76 |
+
|
77 |
+
|
78 |
+
def task_update(task):
|
79 |
+
if "fine-grained" in task:
|
80 |
+
return [
|
81 |
+
gr.update(visible=True),
|
82 |
+
gr.update(visible=False),
|
83 |
+
gr.update(visible=False),
|
84 |
+
]
|
85 |
+
else:
|
86 |
+
return [
|
87 |
+
gr.update(visible=False),
|
88 |
+
gr.update(visible=False),
|
89 |
+
gr.update(visible=False),
|
90 |
+
]
|
91 |
+
|
92 |
+
|
93 |
+
def fine_grained_update(task):
|
94 |
+
if task == "box":
|
95 |
+
return [
|
96 |
+
gr.update(visible=False, value=""),
|
97 |
+
gr.update(visible=True),
|
98 |
+
]
|
99 |
+
elif task == "color":
|
100 |
+
return [
|
101 |
+
gr.update(visible=True),
|
102 |
+
gr.update(visible=False, value=""),
|
103 |
+
]
|
104 |
+
|
105 |
+
|
106 |
+
def cleanup_old_files():
|
107 |
+
current_time = time.time()
|
108 |
+
for folder in [UPLOAD_FOLDER, RESULTS_FOLDER]:
|
109 |
+
for file_path in Path(folder).glob("*"):
|
110 |
+
if current_time - file_path.stat().st_mtime > 3600: # 1 hour
|
111 |
+
file_path.unlink()
|
112 |
+
|
113 |
+
|
114 |
+
with gr.Blocks() as demo:
|
115 |
+
with gr.Row():
|
116 |
+
with gr.Column():
|
117 |
+
image_input = gr.Image(type="filepath", label="上传图片")
|
118 |
+
task_dropdown = gr.Dropdown(
|
119 |
+
choices=[
|
120 |
+
"plain texts OCR",
|
121 |
+
"format texts OCR",
|
122 |
+
"plain multi-crop OCR",
|
123 |
+
"format multi-crop OCR",
|
124 |
+
"plain fine-grained OCR",
|
125 |
+
"format fine-grained OCR",
|
126 |
+
],
|
127 |
+
label="选择GOT模式",
|
128 |
+
value="plain texts OCR",
|
129 |
+
)
|
130 |
+
fine_grained_dropdown = gr.Dropdown(choices=["box", "color"], label="fine-grained type", visible=False)
|
131 |
+
color_dropdown = gr.Dropdown(choices=["red", "green", "blue"], label="color list", visible=False)
|
132 |
+
box_input = gr.Textbox(label="input box: [x1,y1,x2,y2]", placeholder="e.g., [0,0,100,100]", visible=False)
|
133 |
+
submit_button = gr.Button("Submit")
|
134 |
+
|
135 |
+
with gr.Column():
|
136 |
+
ocr_result = gr.Textbox(label="GOT output")
|
137 |
+
|
138 |
+
with gr.Column():
|
139 |
+
gr.Markdown("**如果选择带格式的模式,mathpix结果将自动呈现如下:**")
|
140 |
+
html_result = gr.HTML(label="rendered html", show_label=True)
|
141 |
+
|
142 |
+
task_dropdown.change(task_update, inputs=[task_dropdown], outputs=[fine_grained_dropdown, color_dropdown, box_input])
|
143 |
+
fine_grained_dropdown.change(fine_grained_update, inputs=[fine_grained_dropdown], outputs=[color_dropdown, box_input])
|
144 |
+
|
145 |
+
submit_button.click(run_GOT, inputs=[image_input, task_dropdown, fine_grained_dropdown, color_dropdown, box_input], outputs=[ocr_result, html_result])
|
146 |
+
|
147 |
+
if __name__ == "__main__":
|
148 |
+
cleanup_old_files()
|
149 |
+
demo.launch()
|
app.py
CHANGED
@@ -1,150 +1,49 @@
|
|
1 |
-
import base64
|
2 |
-
import io
|
3 |
import os
|
4 |
-
import shutil
|
5 |
-
import time
|
6 |
import uuid
|
7 |
-
from pathlib import Path
|
8 |
|
|
|
9 |
import gradio as gr
|
10 |
-
from
|
11 |
-
|
12 |
-
# import numpy as np
|
13 |
-
# import tempfile
|
14 |
-
# from PIL import Image
|
15 |
-
|
16 |
-
|
17 |
-
tokenizer = AutoTokenizer.from_pretrained("stepfun-ai/GOT-OCR2_0", trust_remote_code=True)
|
18 |
-
model = AutoModel.from_pretrained("stepfun-ai/GOT-OCR2_0", trust_remote_code=True, low_cpu_mem_usage=True, device_map="cuda", use_safetensors=True)
|
19 |
-
model = model.eval().cuda()
|
20 |
|
21 |
UPLOAD_FOLDER = "./uploads"
|
22 |
RESULTS_FOLDER = "./results"
|
23 |
|
24 |
-
for folder in [UPLOAD_FOLDER, RESULTS_FOLDER]:
|
25 |
-
if not os.path.exists(folder):
|
26 |
-
os.makedirs(folder)
|
27 |
-
|
28 |
-
|
29 |
-
def image_to_base64(image):
|
30 |
-
buffered = io.BytesIO()
|
31 |
-
image.save(buffered, format="PNG")
|
32 |
-
return base64.b64encode(buffered.getvalue()).decode()
|
33 |
-
|
34 |
-
|
35 |
-
def run_GOT(image, got_mode, fine_grained_mode="", ocr_color="", ocr_box=""):
|
36 |
-
unique_id = str(uuid.uuid4())
|
37 |
-
image_path = os.path.join(UPLOAD_FOLDER, f"{unique_id}.png")
|
38 |
-
result_path = os.path.join(RESULTS_FOLDER, f"{unique_id}.html")
|
39 |
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
-
try:
|
43 |
-
if got_mode == "plain texts OCR":
|
44 |
-
res = model.chat(tokenizer, image_path, ocr_type="ocr")
|
45 |
-
return res, None
|
46 |
-
elif got_mode == "format texts OCR":
|
47 |
-
res = model.chat(tokenizer, image_path, ocr_type="format", render=True, save_render_file=result_path)
|
48 |
-
elif got_mode == "plain multi-crop OCR":
|
49 |
-
res = model.chat_crop(tokenizer, image_path, ocr_type="ocr")
|
50 |
-
return res, None
|
51 |
-
elif got_mode == "format multi-crop OCR":
|
52 |
-
res = model.chat_crop(tokenizer, image_path, ocr_type="format", render=True, save_render_file=result_path)
|
53 |
-
elif got_mode == "plain fine-grained OCR":
|
54 |
-
res = model.chat(tokenizer, image_path, ocr_type="ocr", ocr_box=ocr_box, ocr_color=ocr_color)
|
55 |
-
return res, None
|
56 |
-
elif got_mode == "format fine-grained OCR":
|
57 |
-
res = model.chat(tokenizer, image_path, ocr_type="format", ocr_box=ocr_box, ocr_color=ocr_color, render=True, save_render_file=result_path)
|
58 |
|
59 |
-
|
60 |
-
|
|
|
|
|
|
|
|
|
61 |
|
62 |
-
if "format" in got_mode and os.path.exists(result_path):
|
63 |
-
with open(result_path, "r") as f:
|
64 |
-
html_content = f.read()
|
65 |
-
encoded_html = base64.b64encode(html_content.encode("utf-8")).decode("utf-8")
|
66 |
-
iframe_src = f"data:text/html;base64,{encoded_html}"
|
67 |
-
iframe = f'<iframe src="{iframe_src}" width="100%" height="600px"></iframe>'
|
68 |
-
download_link = f'<a href="data:text/html;base64,{encoded_html}" download="result_{unique_id}.html">Download Full Result</a>'
|
69 |
-
return res_markdown, f"{download_link}<br>{iframe}"
|
70 |
-
else:
|
71 |
-
return res_markdown, None
|
72 |
-
except Exception as e:
|
73 |
-
return f"Error: {str(e)}", None
|
74 |
-
finally:
|
75 |
-
if os.path.exists(image_path):
|
76 |
-
os.remove(image_path)
|
77 |
|
|
|
|
|
|
|
78 |
|
79 |
-
def task_update(task):
|
80 |
-
if "fine-grained" in task:
|
81 |
-
return [
|
82 |
-
gr.update(visible=True),
|
83 |
-
gr.update(visible=False),
|
84 |
-
gr.update(visible=False),
|
85 |
-
]
|
86 |
-
else:
|
87 |
-
return [
|
88 |
-
gr.update(visible=False),
|
89 |
-
gr.update(visible=False),
|
90 |
-
gr.update(visible=False),
|
91 |
-
]
|
92 |
|
93 |
-
|
94 |
-
|
95 |
-
if task == "box":
|
96 |
-
return [
|
97 |
-
gr.update(visible=False, value=""),
|
98 |
-
gr.update(visible=True),
|
99 |
-
]
|
100 |
-
elif task == "color":
|
101 |
-
return [
|
102 |
-
gr.update(visible=True),
|
103 |
-
gr.update(visible=False, value=""),
|
104 |
-
]
|
105 |
-
|
106 |
-
|
107 |
-
def cleanup_old_files():
|
108 |
-
current_time = time.time()
|
109 |
-
for folder in [UPLOAD_FOLDER, RESULTS_FOLDER]:
|
110 |
-
for file_path in Path(folder).glob("*"):
|
111 |
-
if current_time - file_path.stat().st_mtime > 3600: # 1 hour
|
112 |
-
file_path.unlink()
|
113 |
|
114 |
|
115 |
with gr.Blocks() as demo:
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
task_dropdown = gr.Dropdown(
|
120 |
-
choices=[
|
121 |
-
"plain texts OCR",
|
122 |
-
"format texts OCR",
|
123 |
-
"plain multi-crop OCR",
|
124 |
-
"format multi-crop OCR",
|
125 |
-
"plain fine-grained OCR",
|
126 |
-
"format fine-grained OCR",
|
127 |
-
],
|
128 |
-
label="选择GOT模式",
|
129 |
-
value="plain texts OCR",
|
130 |
-
)
|
131 |
-
fine_grained_dropdown = gr.Dropdown(choices=["box", "color"], label="fine-grained type", visible=False)
|
132 |
-
color_dropdown = gr.Dropdown(choices=["red", "green", "blue"], label="color list", visible=False)
|
133 |
-
box_input = gr.Textbox(label="input box: [x1,y1,x2,y2]", placeholder="e.g., [0,0,100,100]", visible=False)
|
134 |
-
submit_button = gr.Button("Submit")
|
135 |
-
|
136 |
-
with gr.Column():
|
137 |
-
ocr_result = gr.Textbox(label="GOT output")
|
138 |
-
|
139 |
-
with gr.Column():
|
140 |
-
gr.Markdown("**如果选择带格式的模式,mathpix结果将自动呈现如下:**")
|
141 |
-
html_result = gr.HTML(label="rendered html", show_label=True)
|
142 |
-
|
143 |
-
task_dropdown.change(task_update, inputs=[task_dropdown], outputs=[fine_grained_dropdown, color_dropdown, box_input])
|
144 |
-
fine_grained_dropdown.change(fine_grained_update, inputs=[fine_grained_dropdown], outputs=[color_dropdown, box_input])
|
145 |
|
146 |
-
|
|
|
147 |
|
148 |
-
|
149 |
-
cleanup_old_files()
|
150 |
-
demo.launch()
|
|
|
|
|
|
|
1 |
import os
|
|
|
|
|
2 |
import uuid
|
|
|
3 |
|
4 |
+
import fitz # PyMuPDF
|
5 |
import gradio as gr
|
6 |
+
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
UPLOAD_FOLDER = "./uploads"
|
9 |
RESULTS_FOLDER = "./results"
|
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
def pdf_to_images(pdf_path):
|
13 |
+
images = []
|
14 |
+
pdf_document = fitz.open(pdf_path)
|
15 |
+
for page_num in range(len(pdf_document)):
|
16 |
+
page = pdf_document.load_page(page_num)
|
17 |
+
pix = page.get_pixmap()
|
18 |
+
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
19 |
+
images.append(img)
|
20 |
+
pdf_document.close()
|
21 |
+
return images
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
def process_pdf(pdf_file):
|
25 |
+
temp_pdf_path = os.path.join(UPLOAD_FOLDER, f"{uuid.uuid4()}.pdf")
|
26 |
+
pdf_file.save(temp_pdf_path)
|
27 |
+
images = pdf_to_images(temp_pdf_path)
|
28 |
+
os.remove(temp_pdf_path)
|
29 |
+
return images
|
30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
+
def display_images(images):
|
33 |
+
image_elements = [gr.Image(value=img, type="pil") for img in images]
|
34 |
+
return gr.Gallery(value=image_elements)
|
35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
+
def on_image_select(image):
|
38 |
+
return image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
|
41 |
with gr.Blocks() as demo:
|
42 |
+
pdf_input = gr.File(label="上传PDF文件")
|
43 |
+
image_gallery = gr.Gallery(label="PDF页面预览", columns=3, height="auto")
|
44 |
+
selected_image = gr.Image(label="选中的图片", type="pil")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
pdf_input.upload(fn=process_pdf, inputs=pdf_input, outputs=image_gallery)
|
47 |
+
image_gallery.select(fn=on_image_select, inputs=image_gallery, outputs=selected_image)
|
48 |
|
49 |
+
# 这里可以添加OCR转换功能的相关组件和逻辑
|
|
|
|
requirements.txt
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
verovio
|
2 |
gradio
|
3 |
numpy
|
|
|
1 |
+
PyMuPDF
|
2 |
verovio
|
3 |
gradio
|
4 |
numpy
|