rehan953 commited on
Commit
70c9fdf
Β·
verified Β·
1 Parent(s): 4580d6d

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +136 -0
app.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = os.path.dirname(glmocr.__file__)
11
+ config_path = os.path.join(GLMOCR_BASE, "config.yaml")
12
+ formatter_path = os.path.join(GLMOCR_BASE, "postprocess", "result_formatter.py")
13
+
14
+ # ── STEP 1: Fix config β€” keep header & footer (do NOT add them to abandon) ──
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", "reference",
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
+ # ── STEP 2: Fix result_formatter.py (remove hardcoded header/footer) ───────
27
+ with open(formatter_path, "r") as f:
28
+ source = f.read()
29
+ labels_to_remove = [
30
+ '"header"', "'header'", '"footer"', "'footer'",
31
+ '"doc_header"', "'doc_header'", '"doc_footer"', "'doc_footer'"
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: Load model ────────────────────────────────────────────────────
42
+ from transformers import AutoProcessor, GlmOcrForConditionalGeneration
43
+ print("Loading model... (~2GB first run)")
44
+ processor = AutoProcessor.from_pretrained("zai-org/GLM-OCR")
45
+ model = GlmOcrForConditionalGeneration.from_pretrained(
46
+ "zai-org/GLM-OCR",
47
+ torch_dtype=torch.bfloat16,
48
+ device_map="auto",
49
+ )
50
+ print("βœ… Model ready on", next(model.parameters()).device)
51
+ ABANDON = set(config["pipeline"]["result_formatter"]["abandon"])
52
+
53
+ # ── STEP 4: OCR (PDF β†’ image then run model) ───────────────────────────────
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
+ try:
61
+ import fitz
62
+ doc = fitz.open(path)
63
+ page = doc[0]
64
+ pix = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
65
+ img_path = path[:-4] + "_page0.png"
66
+ pix.save(img_path)
67
+ doc.close()
68
+ path = img_path
69
+ except Exception as e:
70
+ return "PDF conversion failed: " + str(e), "Failed."
71
+
72
+ messages = [
73
+ {"role": "user", "content": [
74
+ {"type": "image", "url": path},
75
+ {"type": "text", "text": "Document Parsing:"}
76
+ ]}
77
+ ]
78
+ inputs = processor.apply_chat_template(
79
+ messages, tokenize=True, add_generation_prompt=True,
80
+ return_dict=True, return_tensors="pt"
81
+ ).to(model.device)
82
+ inputs.pop("token_type_ids", None)
83
+ with torch.no_grad():
84
+ output_ids = model.generate(**inputs, max_new_tokens=2048)
85
+ raw = processor.decode(
86
+ output_ids[0][inputs["input_ids"].shape[1]:],
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
+ region_lines.append("[" + label + "]: " + content[:150])
110
+ markdown_parts.append(content)
111
+ summary = (
112
+ "Headers found : " + str(header_count) + "\n"
113
+ "Footers found : " + str(footer_count) + "\n"
114
+ "Total regions : " + str(len(regions)) + "\n" + "─"*40 + "\n"
115
+ + "\n".join(region_lines)
116
+ )
117
+ markdown = "\n\n".join(markdown_parts) if markdown_parts else raw
118
+ return markdown, summary
119
+ except Exception as e:
120
+ import traceback
121
+ return "Error: " + str(e) + "\n\n" + traceback.format_exc(), "Failed."
122
+
123
+ # ── STEP 5: Gradio UI ──────────────────────────────────────────────────────
124
+ with gr.Blocks(title="GLM-OCR β€” Header & Footer Kept") as demo:
125
+ gr.Markdown("# πŸ” GLM-OCR β€” Header & Footer Kept\nUpload PDF or image. Headers πŸ”΅ and Footers 🟒 are kept in output.")
126
+ file_input = gr.File(label="Upload PDF or Image", file_types=[".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".bmp"])
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=25, label="")
132
+ with gr.Column():
133
+ gr.Markdown("### πŸ—‚οΈ Detected Regions")
134
+ regions_out = gr.Textbox(lines=25, label="")
135
+ run_btn.click(fn=run_ocr, inputs=file_input, outputs=[markdown_out, regions_out])
136
+ demo.launch()