Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,87 +3,71 @@ 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 |
-
# ββ
|
| 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",
|
| 22 |
]
|
| 23 |
config["pipeline"]["enable_layout"] = True
|
| 24 |
-
|
| 25 |
with open(config_path, "w") as f:
|
| 26 |
yaml.dump(config, f, default_flow_style=False, sort_keys=False)
|
| 27 |
|
| 28 |
-
|
| 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)
|
| 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 |
ABANDON = set(config["pipeline"]["result_formatter"]["abandon"])
|
| 49 |
|
| 50 |
-
def
|
| 51 |
-
|
|
|
|
| 52 |
if isinstance(page_item, list):
|
| 53 |
return page_item
|
| 54 |
if isinstance(page_item, dict):
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
return []
|
| 57 |
|
| 58 |
-
def
|
| 59 |
-
|
| 60 |
-
if not isinstance(region, dict):
|
| 61 |
-
return str(region)
|
| 62 |
-
return str(region.get("content") or region.get("text") or region.get("raw") or "")
|
| 63 |
-
|
| 64 |
-
def _get_label(region):
|
| 65 |
-
"""Get label from a region."""
|
| 66 |
-
if not isinstance(region, dict):
|
| 67 |
return "text"
|
| 68 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
# ββ STEP 3: OCR via Zhipu MaaS (no local model) βββββββββββββββββββββββββββββ
|
| 71 |
def run_ocr(uploaded_file):
|
| 72 |
if uploaded_file is None:
|
| 73 |
return "Please upload a file.", "No regions detected."
|
| 74 |
-
|
| 75 |
api_key = "4570c28bdea5493c9efae9dae68edc66.sGbA9DLlcX1GlvqV"
|
| 76 |
if not api_key:
|
| 77 |
-
return
|
| 78 |
-
"Error: ZHIPU_API_KEY is not set.",
|
| 79 |
-
"Failed."
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
try:
|
| 83 |
from glmocr import parse
|
| 84 |
-
|
| 85 |
path = uploaded_file.name if hasattr(uploaded_file, "name") else str(uploaded_file)
|
| 86 |
-
|
| 87 |
if path.lower().endswith(".pdf"):
|
| 88 |
import fitz
|
| 89 |
doc = fitz.open(path)
|
|
@@ -97,28 +81,24 @@ def run_ocr(uploaded_file):
|
|
| 97 |
result = parse(page_images)
|
| 98 |
else:
|
| 99 |
result = parse(path)
|
| 100 |
-
|
| 101 |
pages_data = result if isinstance(result, list) else []
|
| 102 |
-
|
| 103 |
total_headers = 0
|
| 104 |
total_footers = 0
|
| 105 |
all_markdown = []
|
| 106 |
all_summary = []
|
| 107 |
-
|
| 108 |
for page_num, page_item in enumerate(pages_data):
|
| 109 |
-
page_regions =
|
| 110 |
if not isinstance(page_regions, list):
|
| 111 |
-
page_regions = [page_regions]
|
| 112 |
page_md = []
|
| 113 |
page_summary = [f"ββ PAGE {page_num + 1} of {len(pages_data)} ββ"]
|
| 114 |
-
|
| 115 |
for region in page_regions:
|
| 116 |
-
label =
|
| 117 |
-
content =
|
| 118 |
-
|
|
|
|
| 119 |
if label in ABANDON:
|
| 120 |
continue
|
| 121 |
-
|
| 122 |
if label == "header":
|
| 123 |
total_headers += 1
|
| 124 |
page_summary.append(f"π΅ HEADER: {content[:100]}")
|
|
@@ -130,37 +110,25 @@ def run_ocr(uploaded_file):
|
|
| 130 |
else:
|
| 131 |
page_summary.append(f"[{label}]: {content[:100]}")
|
| 132 |
page_md.append(content)
|
| 133 |
-
|
| 134 |
all_markdown.append("\n\n".join(page_md))
|
| 135 |
all_summary.extend(page_summary)
|
| 136 |
all_summary.append("")
|
| 137 |
-
|
| 138 |
summary = (
|
| 139 |
f"Total pages : {len(pages_data)}\n"
|
| 140 |
f"Headers found : {total_headers}\n"
|
| 141 |
f"Footers found : {total_footers}\n"
|
| 142 |
-
f"{'β'*40}\n"
|
| 143 |
-
+ "\n".join(all_summary)
|
| 144 |
)
|
| 145 |
markdown = "\n\n---\n\n".join(all_markdown) if all_markdown else "(No content)"
|
| 146 |
return markdown, summary
|
| 147 |
-
|
| 148 |
except Exception as e:
|
| 149 |
import traceback
|
| 150 |
return f"Error: {str(e)}\n\n{traceback.format_exc()}", "Failed."
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
gr.
|
| 155 |
-
|
| 156 |
-
Upload PDF or image. Headers π΅ and Footers π’ from the **full pipeline** (layout + OCR).
|
| 157 |
-
Uses your Zhipu API key.
|
| 158 |
-
""")
|
| 159 |
-
file_input = gr.File(
|
| 160 |
-
label="Upload PDF or Image",
|
| 161 |
-
file_types=[".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".bmp"]
|
| 162 |
-
)
|
| 163 |
-
run_btn = gr.Button("βΆ Run OCR", variant="primary", size="lg")
|
| 164 |
with gr.Row():
|
| 165 |
with gr.Column():
|
| 166 |
gr.Markdown("### π Markdown Output")
|
|
@@ -169,5 +137,4 @@ with gr.Blocks(title="GLM-OCR β MaaS (Header & Footer)") as demo:
|
|
| 169 |
gr.Markdown("### ποΈ Detected Regions")
|
| 170 |
regions_out = gr.Textbox(lines=30, label="")
|
| 171 |
run_btn.click(fn=run_ocr, inputs=file_input, outputs=[markdown_out, regions_out])
|
| 172 |
-
|
| 173 |
demo.launch()
|
|
|
|
| 3 |
import re
|
| 4 |
import os
|
| 5 |
|
|
|
|
| 6 |
import glmocr
|
| 7 |
GLMOCR_BASE = os.path.dirname(glmocr.__file__)
|
| 8 |
config_path = os.path.join(GLMOCR_BASE, "config.yaml")
|
| 9 |
formatter_path = os.path.join(GLMOCR_BASE, "postprocess", "result_formatter.py")
|
| 10 |
|
| 11 |
+
# ββ Config: MaaS on, keep header/footer ββββββββββββββββββββββββββββββββββββ
|
| 12 |
with open(config_path, "r") as f:
|
| 13 |
config = yaml.safe_load(f)
|
|
|
|
| 14 |
config["pipeline"]["maas"]["enabled"] = True
|
| 15 |
config["pipeline"]["maas"]["api_key"] = "4570c28bdea5493c9efae9dae68edc66.sGbA9DLlcX1GlvqV"
|
|
|
|
| 16 |
config["pipeline"]["result_formatter"]["abandon"] = [
|
| 17 |
+
"number", "footnote", "aside_text", "reference", "footer_image", "header_image",
|
|
|
|
| 18 |
]
|
| 19 |
config["pipeline"]["enable_layout"] = True
|
|
|
|
| 20 |
with open(config_path, "w") as f:
|
| 21 |
yaml.dump(config, f, default_flow_style=False, sort_keys=False)
|
| 22 |
|
| 23 |
+
# ββ Formatter: don't strip header/footer βββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 24 |
with open(formatter_path, "r") as f:
|
| 25 |
source = f.read()
|
| 26 |
+
for label in ['"header"', "'header'", '"footer"', "'footer'", '"doc_header"', "'doc_header'", '"doc_footer"', "'doc_footer'"]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
source = re.sub(r',\s*' + re.escape(label), '', source)
|
| 28 |
source = re.sub(re.escape(label) + r'\s*,', '', source)
|
| 29 |
source = re.sub(re.escape(label), '', source)
|
|
|
|
| 30 |
with open(formatter_path, "w") as f:
|
| 31 |
f.write(source)
|
| 32 |
|
|
|
|
|
|
|
| 33 |
ABANDON = set(config["pipeline"]["result_formatter"]["abandon"])
|
| 34 |
|
| 35 |
+
def get_regions(page_item):
|
| 36 |
+
if page_item is None:
|
| 37 |
+
return []
|
| 38 |
if isinstance(page_item, list):
|
| 39 |
return page_item
|
| 40 |
if isinstance(page_item, dict):
|
| 41 |
+
for key in ("regions", "blocks", "items", "content_list"):
|
| 42 |
+
if key in page_item and isinstance(page_item[key], list):
|
| 43 |
+
return page_item[key]
|
| 44 |
+
if "content" in page_item or "text" in page_item:
|
| 45 |
+
return [page_item]
|
| 46 |
+
if isinstance(page_item, str):
|
| 47 |
+
return [{"label": "text", "content": page_item}]
|
| 48 |
return []
|
| 49 |
|
| 50 |
+
def get_label(r):
|
| 51 |
+
if not isinstance(r, dict):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
return "text"
|
| 53 |
+
return (r.get("label") or r.get("type") or r.get("block_type") or "text")
|
| 54 |
+
|
| 55 |
+
def get_content(r):
|
| 56 |
+
if isinstance(r, str):
|
| 57 |
+
return r
|
| 58 |
+
if not isinstance(r, dict):
|
| 59 |
+
return str(r)
|
| 60 |
+
return str(r.get("content") or r.get("text") or r.get("raw") or "")
|
| 61 |
|
|
|
|
| 62 |
def run_ocr(uploaded_file):
|
| 63 |
if uploaded_file is None:
|
| 64 |
return "Please upload a file.", "No regions detected."
|
|
|
|
| 65 |
api_key = "4570c28bdea5493c9efae9dae68edc66.sGbA9DLlcX1GlvqV"
|
| 66 |
if not api_key:
|
| 67 |
+
return "Error: API key not set.", "Failed."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
try:
|
| 69 |
from glmocr import parse
|
|
|
|
| 70 |
path = uploaded_file.name if hasattr(uploaded_file, "name") else str(uploaded_file)
|
|
|
|
| 71 |
if path.lower().endswith(".pdf"):
|
| 72 |
import fitz
|
| 73 |
doc = fitz.open(path)
|
|
|
|
| 81 |
result = parse(page_images)
|
| 82 |
else:
|
| 83 |
result = parse(path)
|
|
|
|
| 84 |
pages_data = result if isinstance(result, list) else []
|
|
|
|
| 85 |
total_headers = 0
|
| 86 |
total_footers = 0
|
| 87 |
all_markdown = []
|
| 88 |
all_summary = []
|
|
|
|
| 89 |
for page_num, page_item in enumerate(pages_data):
|
| 90 |
+
page_regions = get_regions(page_item)
|
| 91 |
if not isinstance(page_regions, list):
|
| 92 |
+
page_regions = [page_regions]
|
| 93 |
page_md = []
|
| 94 |
page_summary = [f"ββ PAGE {page_num + 1} of {len(pages_data)} ββ"]
|
|
|
|
| 95 |
for region in page_regions:
|
| 96 |
+
label = get_label(region)
|
| 97 |
+
content = get_content(region)
|
| 98 |
+
if not content.strip():
|
| 99 |
+
continue
|
| 100 |
if label in ABANDON:
|
| 101 |
continue
|
|
|
|
| 102 |
if label == "header":
|
| 103 |
total_headers += 1
|
| 104 |
page_summary.append(f"π΅ HEADER: {content[:100]}")
|
|
|
|
| 110 |
else:
|
| 111 |
page_summary.append(f"[{label}]: {content[:100]}")
|
| 112 |
page_md.append(content)
|
|
|
|
| 113 |
all_markdown.append("\n\n".join(page_md))
|
| 114 |
all_summary.extend(page_summary)
|
| 115 |
all_summary.append("")
|
|
|
|
| 116 |
summary = (
|
| 117 |
f"Total pages : {len(pages_data)}\n"
|
| 118 |
f"Headers found : {total_headers}\n"
|
| 119 |
f"Footers found : {total_footers}\n"
|
| 120 |
+
f"{'β'*40}\n" + "\n".join(all_summary)
|
|
|
|
| 121 |
)
|
| 122 |
markdown = "\n\n---\n\n".join(all_markdown) if all_markdown else "(No content)"
|
| 123 |
return markdown, summary
|
|
|
|
| 124 |
except Exception as e:
|
| 125 |
import traceback
|
| 126 |
return f"Error: {str(e)}\n\n{traceback.format_exc()}", "Failed."
|
| 127 |
|
| 128 |
+
with gr.Blocks(title="GLM-OCR β MaaS") as demo:
|
| 129 |
+
gr.Markdown("# π GLM-OCR β Zhipu MaaS\nUpload PDF or image. Headers π΅ and Footers π’ when returned by the API.")
|
| 130 |
+
file_input = gr.File(label="Upload PDF or Image", file_types=[".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".bmp"])
|
| 131 |
+
run_btn = gr.Button("βΆ Run OCR", variant="primary", size="lg")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
with gr.Row():
|
| 133 |
with gr.Column():
|
| 134 |
gr.Markdown("### π Markdown Output")
|
|
|
|
| 137 |
gr.Markdown("### ποΈ Detected Regions")
|
| 138 |
regions_out = gr.Textbox(lines=30, label="")
|
| 139 |
run_btn.click(fn=run_ocr, inputs=file_input, outputs=[markdown_out, regions_out])
|
|
|
|
| 140 |
demo.launch()
|