Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,21 @@
|
|
| 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
|
| 10 |
-
config_path
|
| 11 |
formatter_path = os.path.join(GLMOCR_BASE, "postprocess", "result_formatter.py")
|
| 12 |
|
| 13 |
-
# ββ STEP 1:
|
| 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",
|
|
@@ -23,17 +25,15 @@ config["pipeline"]["enable_layout"] = True
|
|
| 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 |
-
'"
|
| 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)
|
|
@@ -45,154 +45,109 @@ with open(formatter_path, "w") as f:
|
|
| 45 |
|
| 46 |
print("β
result_formatter.py fixed")
|
| 47 |
|
| 48 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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
|
| 120 |
-
img_path = f"/tmp/
|
| 121 |
pix.save(img_path)
|
| 122 |
page_images.append(img_path)
|
| 123 |
doc.close()
|
|
|
|
|
|
|
| 124 |
else:
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
total_headers = 0
|
| 128 |
total_footers = 0
|
| 129 |
-
all_markdown
|
| 130 |
-
all_summary
|
| 131 |
-
|
| 132 |
-
for page_num,
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
page_md
|
| 136 |
-
page_summary = [f"ββ PAGE {page_num + 1} of {len(
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 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(
|
| 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
|
| 182 |
-
with gr.Blocks(title="GLM-OCR β Header & Footer
|
| 183 |
gr.Markdown("""
|
| 184 |
-
# π GLM-OCR β
|
| 185 |
-
Upload PDF or image. Headers π΅ and Footers π’
|
| 186 |
-
|
| 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")
|
|
@@ -200,8 +155,6 @@ with gr.Blocks(title="GLM-OCR β Header & Footer Fix") as demo:
|
|
| 200 |
with gr.Column():
|
| 201 |
gr.Markdown("### ποΈ Detected Regions")
|
| 202 |
regions_out = gr.Textbox(lines=30, label="")
|
|
|
|
| 203 |
|
| 204 |
-
|
| 205 |
-
outputs=[markdown_out, regions_out])
|
| 206 |
-
|
| 207 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import yaml
|
| 3 |
import re
|
|
|
|
| 4 |
import os
|
|
|
|
| 5 |
|
| 6 |
+
# Paths from installed glmocr package
|
| 7 |
import glmocr
|
| 8 |
+
GLMOCR_BASE = os.path.dirname(glmocr.__file__)
|
| 9 |
+
config_path = os.path.join(GLMOCR_BASE, "config.yaml")
|
| 10 |
formatter_path = os.path.join(GLMOCR_BASE, "postprocess", "result_formatter.py")
|
| 11 |
|
| 12 |
+
# ββ STEP 1: Load and fix config (MaaS + keep header/footer) βββββββββββββββββ
|
| 13 |
with open(config_path, "r") as f:
|
| 14 |
config = yaml.safe_load(f)
|
| 15 |
|
| 16 |
+
config["pipeline"]["maas"]["enabled"] = True
|
| 17 |
+
config["pipeline"]["maas"]["api_key"] = "4570c28bdea5493c9efae9dae68edc66.sGbA9DLlcX1GlvqV"
|
| 18 |
+
|
| 19 |
config["pipeline"]["result_formatter"]["abandon"] = [
|
| 20 |
"number", "footnote", "aside_text",
|
| 21 |
"reference", "footer_image", "header_image",
|
|
|
|
| 25 |
with open(config_path, "w") as f:
|
| 26 |
yaml.dump(config, f, default_flow_style=False, sort_keys=False)
|
| 27 |
|
| 28 |
+
print("β
config.yaml fixed (MaaS enabled, header/footer kept)")
|
| 29 |
|
| 30 |
+
# ββ STEP 2: Fix result_formatter.py ββββββββββββββββββββββββββββββββββββββββ
|
| 31 |
with open(formatter_path, "r") as f:
|
| 32 |
source = f.read()
|
| 33 |
|
| 34 |
labels_to_remove = [
|
| 35 |
+
'"header"', "'header'", '"footer"', "'footer'",
|
| 36 |
+
'"doc_header"', "'doc_header'", '"doc_footer"', "'doc_footer'"
|
|
|
|
|
|
|
| 37 |
]
|
| 38 |
for label in labels_to_remove:
|
| 39 |
source = re.sub(r',\s*' + re.escape(label), '', source)
|
|
|
|
| 45 |
|
| 46 |
print("β
result_formatter.py fixed")
|
| 47 |
|
| 48 |
+
ABANDON = set(config["pipeline"]["result_formatter"]["abandon"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
# ββ STEP 3: OCR via Zhipu MaaS (no local model) βββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def run_ocr(uploaded_file):
|
| 52 |
if uploaded_file is None:
|
| 53 |
return "Please upload a file.", "No regions detected."
|
| 54 |
|
| 55 |
+
api_key = "4570c28bdea5493c9efae9dae68edc66.sGbA9DLlcX1GlvqV"
|
| 56 |
+
if not api_key:
|
| 57 |
+
return (
|
| 58 |
+
"Error: ZHIPU_API_KEY is not set. Add it in Space Settings β Variables and secrets.",
|
| 59 |
+
"Failed."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
try:
|
| 63 |
+
from glmocr import parse
|
| 64 |
|
| 65 |
path = uploaded_file.name if hasattr(uploaded_file, "name") else str(uploaded_file)
|
| 66 |
|
| 67 |
+
# PDF β list of image paths (SDK expects images per page)
|
| 68 |
if path.lower().endswith(".pdf"):
|
| 69 |
import fitz
|
| 70 |
doc = fitz.open(path)
|
| 71 |
page_images = []
|
| 72 |
for i in range(len(doc)):
|
| 73 |
+
pix = doc[i].get_pixmap(matrix=fitz.Matrix(1.5, 1.5), alpha=False)
|
| 74 |
+
img_path = f"/tmp/maas_page_{i}.png"
|
| 75 |
pix.save(img_path)
|
| 76 |
page_images.append(img_path)
|
| 77 |
doc.close()
|
| 78 |
+
# parse() with list = one document, multiple pages
|
| 79 |
+
result = parse(page_images)
|
| 80 |
else:
|
| 81 |
+
result = parse(path)
|
| 82 |
+
|
| 83 |
+
# result.json_result: list of pages, each page = list of regions
|
| 84 |
+
# Region: {"label": "header"|"footer"|"text"|..., "content": "...", ...}
|
| 85 |
+
pages_data = result.json_result if hasattr(result, "json_result") else []
|
| 86 |
+
if not isinstance(pages_data, list):
|
| 87 |
+
pages_data = [pages_data] if pages_data else []
|
| 88 |
|
| 89 |
total_headers = 0
|
| 90 |
total_footers = 0
|
| 91 |
+
all_markdown = []
|
| 92 |
+
all_summary = []
|
| 93 |
+
|
| 94 |
+
for page_num, page_regions in enumerate(pages_data):
|
| 95 |
+
if not isinstance(page_regions, list):
|
| 96 |
+
page_regions = [page_regions] if page_regions else []
|
| 97 |
+
page_md = []
|
| 98 |
+
page_summary = [f"ββ PAGE {page_num + 1} of {len(pages_data)} ββ"]
|
| 99 |
+
|
| 100 |
+
for region in page_regions:
|
| 101 |
+
if not isinstance(region, dict):
|
| 102 |
+
continue
|
| 103 |
+
label = region.get("label", "text")
|
| 104 |
+
content = str(region.get("content", ""))
|
| 105 |
+
|
| 106 |
+
if label in ABANDON:
|
| 107 |
+
continue
|
| 108 |
+
|
| 109 |
+
if label == "header":
|
| 110 |
+
total_headers += 1
|
| 111 |
+
page_summary.append(f"π΅ HEADER: {content[:100]}")
|
| 112 |
+
page_md.append(f"<!-- HEADER -->\n{content}")
|
| 113 |
+
elif label == "footer":
|
| 114 |
+
total_footers += 1
|
| 115 |
+
page_summary.append(f"π’ FOOTER: {content[:100]}")
|
| 116 |
+
page_md.append(f"<!-- FOOTER -->\n{content}")
|
| 117 |
+
else:
|
| 118 |
+
page_summary.append(f"[{label}]: {content[:100]}")
|
| 119 |
+
page_md.append(content)
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
all_markdown.append("\n\n".join(page_md))
|
| 122 |
all_summary.extend(page_summary)
|
| 123 |
all_summary.append("")
|
| 124 |
|
| 125 |
summary = (
|
| 126 |
+
f"Total pages : {len(pages_data)}\n"
|
| 127 |
f"Headers found : {total_headers}\n"
|
| 128 |
f"Footers found : {total_footers}\n"
|
| 129 |
f"{'β'*40}\n"
|
| 130 |
+ "\n".join(all_summary)
|
| 131 |
)
|
| 132 |
+
markdown = "\n\n---\n\n".join(all_markdown) if all_markdown else "(No content)"
|
|
|
|
| 133 |
return markdown, summary
|
| 134 |
|
| 135 |
except Exception as e:
|
| 136 |
import traceback
|
| 137 |
return f"Error: {str(e)}\n\n{traceback.format_exc()}", "Failed."
|
| 138 |
|
| 139 |
+
# ββ STEP 4: Gradio UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 140 |
+
with gr.Blocks(title="GLM-OCR β MaaS (Header & Footer)") as demo:
|
| 141 |
gr.Markdown("""
|
| 142 |
+
# π GLM-OCR β Zhipu MaaS
|
| 143 |
+
Upload PDF or image. Headers π΅ and Footers π’ from the **full pipeline** (layout + OCR).
|
| 144 |
+
Uses your Zhipu API key (set in Space secrets).
|
|
|
|
| 145 |
""")
|
|
|
|
| 146 |
file_input = gr.File(
|
| 147 |
label="Upload PDF or Image",
|
| 148 |
file_types=[".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".bmp"]
|
| 149 |
)
|
| 150 |
run_btn = gr.Button("βΆ Run OCR", variant="primary", size="lg")
|
|
|
|
| 151 |
with gr.Row():
|
| 152 |
with gr.Column():
|
| 153 |
gr.Markdown("### π Markdown Output")
|
|
|
|
| 155 |
with gr.Column():
|
| 156 |
gr.Markdown("### ποΈ Detected Regions")
|
| 157 |
regions_out = gr.Textbox(lines=30, label="")
|
| 158 |
+
run_btn.click(fn=run_ocr, inputs=file_input, outputs=[markdown_out, regions_out])
|
| 159 |
|
| 160 |
+
demo.launch()
|
|
|
|
|
|
|
|
|