rehan953 commited on
Commit
cf1832c
Β·
verified Β·
1 Parent(s): 481e07c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -118
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 = 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",
@@ -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
- '"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)
@@ -45,154 +45,109 @@ with open(formatter_path, "w") as f:
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")
@@ -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
- run_btn.click(fn=run_ocr, inputs=file_input,
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()