rehan953 commited on
Commit
c855e0a
·
verified ·
1 Parent(s): a48260e

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +21 -8
app.py CHANGED
@@ -11,7 +11,7 @@ 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.yaml on startup ───────────────────────
15
  with open(config_path, "r") as f:
16
  config = yaml.safe_load(f)
17
  config["pipeline"]["result_formatter"]["abandon"] = [
@@ -21,9 +21,9 @@ config["pipeline"]["result_formatter"]["abandon"] = [
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")
25
 
26
- # ── STEP 2: Fix result_formatter.py on startup ───────────────
27
  with open(formatter_path, "r") as f:
28
  source = f.read()
29
  labels_to_remove = [
@@ -38,7 +38,7 @@ 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")
@@ -50,12 +50,25 @@ model = GlmOcrForConditionalGeneration.from_pretrained(
50
  print("✅ Model ready on", next(model.parameters()).device)
51
  ABANDON = set(config["pipeline"]["result_formatter"]["abandon"])
52
 
53
- # ── STEP 4: OCR function ──────────────────────────────────────
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
  messages = [
60
  {"role": "user", "content": [
61
  {"type": "image", "url": path},
@@ -107,9 +120,9 @@ def run_ocr(uploaded_file):
107
  import traceback
108
  return "Error: " + str(e) + "\n\n" + traceback.format_exc(), "Failed."
109
 
110
- # ── STEP 5: Gradio UI ─────────────────────────────────────────
111
- with gr.Blocks(title="GLM-OCR — Header & Footer Fix") as demo:
112
- gr.Markdown("# 🔍 GLM-OCR — Header & Footer Fix\nUpload any PDF or image. Headers 🔵 and Footers 🟢 now appear in output.")
113
  file_input = gr.File(label="Upload PDF or Image", file_types=[".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".bmp"])
114
  run_btn = gr.Button("▶ Run OCR", variant="primary", size="lg")
115
  with gr.Row():
 
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"] = [
 
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 = [
 
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")
 
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},
 
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():