Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,136 +1,207 @@
|
|
| 1 |
-
|
| 2 |
import gradio as gr
|
| 3 |
import yaml
|
| 4 |
import re
|
|
|
|
| 5 |
import os
|
| 6 |
import torch
|
| 7 |
|
| 8 |
-
# Paths from installed glmocr package (required on HF Space)
|
| 9 |
import glmocr
|
| 10 |
-
GLMOCR_BASE
|
| 11 |
-
config_path
|
| 12 |
formatter_path = os.path.join(GLMOCR_BASE, "postprocess", "result_formatter.py")
|
| 13 |
|
| 14 |
-
# ββ STEP 1: Fix config
|
| 15 |
with open(config_path, "r") as f:
|
| 16 |
config = yaml.safe_load(f)
|
|
|
|
| 17 |
config["pipeline"]["result_formatter"]["abandon"] = [
|
| 18 |
-
"number", "footnote", "aside_text",
|
| 19 |
-
"footer_image", "header_image",
|
| 20 |
]
|
| 21 |
config["pipeline"]["enable_layout"] = True
|
|
|
|
| 22 |
with open(config_path, "w") as f:
|
| 23 |
yaml.dump(config, f, default_flow_style=False, sort_keys=False)
|
| 24 |
-
print("β
config.yaml fixed (header & footer kept in output)")
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
| 27 |
with open(formatter_path, "r") as f:
|
| 28 |
source = f.read()
|
|
|
|
| 29 |
labels_to_remove = [
|
| 30 |
-
'"header"', "'header'",
|
| 31 |
-
'"
|
|
|
|
|
|
|
| 32 |
]
|
| 33 |
for label in labels_to_remove:
|
| 34 |
source = re.sub(r',\s*' + re.escape(label), '', source)
|
| 35 |
source = re.sub(re.escape(label) + r'\s*,', '', source)
|
| 36 |
source = re.sub(re.escape(label), '', source)
|
|
|
|
| 37 |
with open(formatter_path, "w") as f:
|
| 38 |
f.write(source)
|
|
|
|
| 39 |
print("β
result_formatter.py fixed")
|
| 40 |
|
| 41 |
-
# ββ STEP 3:
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
def run_ocr(uploaded_file):
|
| 55 |
if uploaded_file is None:
|
| 56 |
return "Please upload a file.", "No regions detected."
|
|
|
|
| 57 |
try:
|
|
|
|
|
|
|
| 58 |
path = uploaded_file.name if hasattr(uploaded_file, "name") else str(uploaded_file)
|
|
|
|
| 59 |
if path.lower().endswith(".pdf"):
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
pix
|
| 65 |
-
img_path =
|
| 66 |
pix.save(img_path)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
skip_special_tokens=False
|
| 88 |
-
)
|
| 89 |
-
raw = raw.replace("<|user|>", "").strip()
|
| 90 |
-
json_match = re.search(r'\[.*\]', raw, re.DOTALL)
|
| 91 |
-
regions = json.loads(json_match.group()) if json_match else []
|
| 92 |
-
header_count = footer_count = 0
|
| 93 |
-
region_lines = []
|
| 94 |
-
markdown_parts = []
|
| 95 |
-
for region in regions:
|
| 96 |
-
label = region.get("label", "text")
|
| 97 |
-
content = str(region.get("content", ""))
|
| 98 |
-
if label in ABANDON:
|
| 99 |
-
continue
|
| 100 |
-
if label == "header":
|
| 101 |
-
header_count += 1
|
| 102 |
-
region_lines.append("π΅ HEADER:\n" + content + "\n")
|
| 103 |
-
markdown_parts.append("<!-- HEADER -->\n" + content)
|
| 104 |
-
elif label == "footer":
|
| 105 |
-
footer_count += 1
|
| 106 |
-
region_lines.append("π’ FOOTER:\n" + content + "\n")
|
| 107 |
-
markdown_parts.append("<!-- FOOTER -->\n" + content)
|
| 108 |
else:
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
summary = (
|
| 112 |
-
"
|
| 113 |
-
"
|
| 114 |
-
"
|
| 115 |
-
|
|
|
|
| 116 |
)
|
| 117 |
-
|
|
|
|
| 118 |
return markdown, summary
|
|
|
|
| 119 |
except Exception as e:
|
| 120 |
import traceback
|
| 121 |
-
return "Error:
|
| 122 |
|
| 123 |
-
# ββ STEP
|
| 124 |
-
with gr.Blocks(title="GLM-OCR β Header & Footer
|
| 125 |
-
gr.Markdown("
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
run_btn = gr.Button("βΆ Run OCR", variant="primary", size="lg")
|
|
|
|
| 128 |
with gr.Row():
|
| 129 |
with gr.Column():
|
| 130 |
gr.Markdown("### π Markdown Output")
|
| 131 |
-
markdown_out = gr.Textbox(lines=
|
| 132 |
with gr.Column():
|
| 133 |
gr.Markdown("### ποΈ Detected Regions")
|
| 134 |
-
regions_out = gr.Textbox(lines=
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
| 136 |
demo.launch()
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import yaml
|
| 3 |
import re
|
| 4 |
+
import json
|
| 5 |
import os
|
| 6 |
import torch
|
| 7 |
|
|
|
|
| 8 |
import glmocr
|
| 9 |
+
GLMOCR_BASE = os.path.dirname(glmocr.__file__)
|
| 10 |
+
config_path = os.path.join(GLMOCR_BASE, "config.yaml")
|
| 11 |
formatter_path = os.path.join(GLMOCR_BASE, "postprocess", "result_formatter.py")
|
| 12 |
|
| 13 |
+
# ββ STEP 1: Fix config.yaml βββββββββββββββββββββββββββββββββββ
|
| 14 |
with open(config_path, "r") as f:
|
| 15 |
config = yaml.safe_load(f)
|
| 16 |
+
|
| 17 |
config["pipeline"]["result_formatter"]["abandon"] = [
|
| 18 |
+
"number", "footnote", "aside_text",
|
| 19 |
+
"reference", "footer_image", "header_image",
|
| 20 |
]
|
| 21 |
config["pipeline"]["enable_layout"] = True
|
| 22 |
+
|
| 23 |
with open(config_path, "w") as f:
|
| 24 |
yaml.dump(config, f, default_flow_style=False, sort_keys=False)
|
|
|
|
| 25 |
|
| 26 |
+
print("β
config.yaml fixed")
|
| 27 |
+
|
| 28 |
+
# ββ STEP 2: Fix result_formatter.py ββββββββββββββββββββββββββ
|
| 29 |
with open(formatter_path, "r") as f:
|
| 30 |
source = f.read()
|
| 31 |
+
|
| 32 |
labels_to_remove = [
|
| 33 |
+
'"header"', "'header'",
|
| 34 |
+
'"footer"', "'footer'",
|
| 35 |
+
'"doc_header"', "'doc_header'",
|
| 36 |
+
'"doc_footer"', "'doc_footer'"
|
| 37 |
]
|
| 38 |
for label in labels_to_remove:
|
| 39 |
source = re.sub(r',\s*' + re.escape(label), '', source)
|
| 40 |
source = re.sub(re.escape(label) + r'\s*,', '', source)
|
| 41 |
source = re.sub(re.escape(label), '', source)
|
| 42 |
+
|
| 43 |
with open(formatter_path, "w") as f:
|
| 44 |
f.write(source)
|
| 45 |
+
|
| 46 |
print("β
result_formatter.py fixed")
|
| 47 |
|
| 48 |
+
# ββ STEP 3: Lazy model load βββββββββββββββββββββββββββββββββββ
|
| 49 |
+
processor = None
|
| 50 |
+
model = None
|
| 51 |
+
ABANDON = set(config["pipeline"]["result_formatter"]["abandon"])
|
| 52 |
+
|
| 53 |
+
def load_model():
|
| 54 |
+
global processor, model
|
| 55 |
+
if model is not None:
|
| 56 |
+
return
|
| 57 |
+
from transformers import AutoProcessor, GlmOcrForConditionalGeneration
|
| 58 |
+
print("Loading model...")
|
| 59 |
+
processor = AutoProcessor.from_pretrained("zai-org/GLM-OCR")
|
| 60 |
+
model = GlmOcrForConditionalGeneration.from_pretrained(
|
| 61 |
+
"zai-org/GLM-OCR",
|
| 62 |
+
torch_dtype=torch.bfloat16,
|
| 63 |
+
device_map="auto",
|
| 64 |
+
)
|
| 65 |
+
print(f"β
Model ready on {next(model.parameters()).device}")
|
| 66 |
+
|
| 67 |
+
# ββ STEP 4: OCR one image βββββββββββββββββββββββββββββββββββββ
|
| 68 |
+
def ocr_image(img_path):
|
| 69 |
+
messages = [
|
| 70 |
+
{"role": "user", "content": [
|
| 71 |
+
{"type": "image", "url": img_path},
|
| 72 |
+
{"type": "text", "text": "Document Parsing:"}
|
| 73 |
+
]}
|
| 74 |
+
]
|
| 75 |
+
inputs = processor.apply_chat_template(
|
| 76 |
+
messages, tokenize=True, add_generation_prompt=True,
|
| 77 |
+
return_dict=True, return_tensors="pt"
|
| 78 |
+
).to(model.device)
|
| 79 |
+
inputs.pop("token_type_ids", None)
|
| 80 |
+
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
output_ids = model.generate(**inputs, max_new_tokens=2048)
|
| 83 |
+
|
| 84 |
+
raw = processor.decode(
|
| 85 |
+
output_ids[0][inputs["input_ids"].shape[1]:],
|
| 86 |
+
skip_special_tokens=False
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
for token in ["<|assistant|>", "<|user|>", "<|system|>",
|
| 90 |
+
"<|endoftext|>", "</s>", "<s>"]:
|
| 91 |
+
raw = raw.replace(token, "")
|
| 92 |
+
raw = raw.strip()
|
| 93 |
+
|
| 94 |
+
json_match = re.search(r'\[.*\]', raw, re.DOTALL)
|
| 95 |
+
if json_match:
|
| 96 |
+
try:
|
| 97 |
+
regions = json.loads(json_match.group())
|
| 98 |
+
return regions, raw, "json"
|
| 99 |
+
except:
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
+
return [], raw, "raw"
|
| 103 |
+
|
| 104 |
+
# ββ STEP 5: Main OCR function βββββββββββββββββββββββββββββββββ
|
| 105 |
def run_ocr(uploaded_file):
|
| 106 |
if uploaded_file is None:
|
| 107 |
return "Please upload a file.", "No regions detected."
|
| 108 |
+
|
| 109 |
try:
|
| 110 |
+
load_model()
|
| 111 |
+
|
| 112 |
path = uploaded_file.name if hasattr(uploaded_file, "name") else str(uploaded_file)
|
| 113 |
+
|
| 114 |
if path.lower().endswith(".pdf"):
|
| 115 |
+
import fitz
|
| 116 |
+
doc = fitz.open(path)
|
| 117 |
+
page_images = []
|
| 118 |
+
for i in range(len(doc)):
|
| 119 |
+
pix = doc[i].get_pixmap(matrix=fitz.Matrix(1.5, 1.5), alpha=False)
|
| 120 |
+
img_path = f"/tmp/page_{i}.png"
|
| 121 |
pix.save(img_path)
|
| 122 |
+
page_images.append(img_path)
|
| 123 |
+
doc.close()
|
| 124 |
+
else:
|
| 125 |
+
page_images = [path]
|
| 126 |
+
|
| 127 |
+
total_headers = 0
|
| 128 |
+
total_footers = 0
|
| 129 |
+
all_markdown = []
|
| 130 |
+
all_summary = []
|
| 131 |
+
|
| 132 |
+
for page_num, img_path in enumerate(page_images):
|
| 133 |
+
regions, raw, output_type = ocr_image(img_path)
|
| 134 |
+
|
| 135 |
+
page_md = []
|
| 136 |
+
page_summary = [f"ββ PAGE {page_num + 1} of {len(page_images)} ββ"]
|
| 137 |
+
|
| 138 |
+
if output_type == "raw":
|
| 139 |
+
page_md.append(raw)
|
| 140 |
+
page_summary.append("[raw HTML/text output]")
|
| 141 |
+
page_summary.append(f"Content length: {len(raw)} chars")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
else:
|
| 143 |
+
for region in regions:
|
| 144 |
+
label = region.get("label", "text")
|
| 145 |
+
content = str(region.get("content", ""))
|
| 146 |
+
|
| 147 |
+
if label in ABANDON:
|
| 148 |
+
continue
|
| 149 |
+
|
| 150 |
+
if label == "header":
|
| 151 |
+
total_headers += 1
|
| 152 |
+
page_summary.append(f"π΅ HEADER: {content[:100]}")
|
| 153 |
+
page_md.append(f"<!-- HEADER -->\n{content}")
|
| 154 |
+
elif label == "footer":
|
| 155 |
+
total_footers += 1
|
| 156 |
+
page_summary.append(f"π’ FOOTER: {content[:100]}")
|
| 157 |
+
page_md.append(f"<!-- FOOTER -->\n{content}")
|
| 158 |
+
else:
|
| 159 |
+
page_summary.append(f"[{label}]: {content[:100]}")
|
| 160 |
+
page_md.append(content)
|
| 161 |
+
|
| 162 |
+
all_markdown.append("\n\n".join(page_md))
|
| 163 |
+
all_summary.extend(page_summary)
|
| 164 |
+
all_summary.append("")
|
| 165 |
+
|
| 166 |
summary = (
|
| 167 |
+
f"Total pages : {len(page_images)}\n"
|
| 168 |
+
f"Headers found : {total_headers}\n"
|
| 169 |
+
f"Footers found : {total_footers}\n"
|
| 170 |
+
f"{'β'*40}\n"
|
| 171 |
+
+ "\n".join(all_summary)
|
| 172 |
)
|
| 173 |
+
|
| 174 |
+
markdown = "\n\n---\n\n".join(all_markdown)
|
| 175 |
return markdown, summary
|
| 176 |
+
|
| 177 |
except Exception as e:
|
| 178 |
import traceback
|
| 179 |
+
return f"Error: {str(e)}\n\n{traceback.format_exc()}", "Failed."
|
| 180 |
|
| 181 |
+
# ββ STEP 6: Gradio UI βββββββββββββββββββββββββββββββββββββββββ
|
| 182 |
+
with gr.Blocks(title="GLM-OCR β Header & Footer Fix") as demo:
|
| 183 |
+
gr.Markdown("""
|
| 184 |
+
# π GLM-OCR β Header & Footer Fix
|
| 185 |
+
Upload PDF or image. Headers π΅ and Footers π’ now appear in output.
|
| 186 |
+
Multi-page PDFs fully supported.
|
| 187 |
+
> First request takes ~2 min to load model. After that it is fast.
|
| 188 |
+
""")
|
| 189 |
+
|
| 190 |
+
file_input = gr.File(
|
| 191 |
+
label="Upload PDF or Image",
|
| 192 |
+
file_types=[".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".bmp"]
|
| 193 |
+
)
|
| 194 |
run_btn = gr.Button("βΆ Run OCR", variant="primary", size="lg")
|
| 195 |
+
|
| 196 |
with gr.Row():
|
| 197 |
with gr.Column():
|
| 198 |
gr.Markdown("### π Markdown Output")
|
| 199 |
+
markdown_out = gr.Textbox(lines=30, label="")
|
| 200 |
with gr.Column():
|
| 201 |
gr.Markdown("### ποΈ Detected Regions")
|
| 202 |
+
regions_out = gr.Textbox(lines=30, label="")
|
| 203 |
+
|
| 204 |
+
run_btn.click(fn=run_ocr, inputs=file_input,
|
| 205 |
+
outputs=[markdown_out, regions_out])
|
| 206 |
+
|
| 207 |
demo.launch()
|