rehan953 commited on
Commit
62ba456
Β·
verified Β·
1 Parent(s): 9e1fcdf

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +157 -86
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 = 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()
 
 
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()