pratyyush commited on
Commit
0db7bb0
Β·
verified Β·
1 Parent(s): 4673f8c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -32
app.py CHANGED
@@ -1,13 +1,19 @@
1
  import gradio as gr
2
  import torch
3
- from transformers import AutoModel, AutoTokenizer
4
  from PIL import Image
5
 
6
  model_id = "zai-org/GLM-OCR"
7
 
8
- # Load with trust_remote_code=True to get the model's specific processing logic
9
- tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
10
- model = AutoModel.from_pretrained(
 
 
 
 
 
 
11
  model_id,
12
  trust_remote_code=True,
13
  device_map="auto",
@@ -15,53 +21,62 @@ model = AutoModel.from_pretrained(
15
  ).eval()
16
 
17
  def extract_all_tables(image):
18
- if image is None: return "Please upload an image."
19
-
20
- prompt = "Extract all text and tables from this image. Format tables in Markdown. Do not skip any data."
21
 
22
- # 1. Manually build the input using the model's internal helper
23
- # This replaces the 'model.chat' method that was failing
24
- inputs = tokenizer.build_chat_input(prompt, images=[image], history=[])
25
- inputs = {k: v.to(model.device) for k, v in inputs.items() if torch.is_tensor(v)}
26
 
27
- # 2. Use the standard generate method
28
- with torch.no_grad():
29
- outputs = model.generate(
30
- **inputs,
31
- max_new_tokens=4096,
32
- do_sample=False,
33
- repetition_penalty=1.1
34
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # 3. Decode only the new parts (the answer)
37
- input_len = inputs['input_ids'].shape[1]
38
- response = tokenizer.decode(outputs[0][input_len:], skip_special_tokens=True)
39
- return response
40
 
41
- # UI with Copy Functionality
42
  with gr.Blocks() as demo:
43
- gr.Markdown("# πŸ“Š Accountancy Paper Extractor")
44
 
45
  with gr.Row():
46
  with gr.Column():
47
- img_input = gr.Image(type="pil", label="Upload Paper")
48
- btn = gr.Button("Extract All Tables", variant="primary")
49
 
50
  with gr.Column():
51
  text_output = gr.Textbox(
52
  label="Extracted Result",
53
- lines=20,
54
  interactive=True,
55
- elem_id="result-text"
56
  )
57
  copy_btn = gr.Button("πŸ“‹ Copy to Clipboard")
58
 
59
- # JavaScript for copying text
60
  copy_btn.click(None, None, None, js="""
61
  () => {
62
- const text = document.querySelector('#result-text textarea').value;
63
  navigator.clipboard.writeText(text);
64
- alert('Copied!');
65
  }
66
  """)
67
 
 
1
  import gradio as gr
2
  import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
  from PIL import Image
5
 
6
  model_id = "zai-org/GLM-OCR"
7
 
8
+ # 1. Force use_fast=False to load the custom Python methods
9
+ tokenizer = AutoTokenizer.from_pretrained(
10
+ model_id,
11
+ trust_remote_code=True,
12
+ use_fast=False
13
+ )
14
+
15
+ # 2. Load the model with appropriate precision
16
+ model = AutoModelForCausalLM.from_pretrained(
17
  model_id,
18
  trust_remote_code=True,
19
  device_map="auto",
 
21
  ).eval()
22
 
23
  def extract_all_tables(image):
24
+ if image is None:
25
+ return "Please upload an image."
 
26
 
27
+ # Precise prompt for accountancy data
28
+ prompt = "Extract all text and all tables from this image. Format tables strictly in Markdown. Preserve all currency symbols."
 
 
29
 
30
+ # 3. Use the model's internal processing logic manually
31
+ # This avoids the build_chat_input attribute error entirely
32
+ try:
33
+ # Most GLM-OCR models use this specific conversation template
34
+ query = f"<|user|>\n<|image_1|>\n{prompt}<|assistant|>\n"
35
+
36
+ inputs = tokenizer(query, return_tensors="pt").to(model.device)
37
+ # Handle the image processing separately as expected by the vision encoder
38
+ pixel_values = tokenizer.process_images([image]).to(model.device).to(torch.float16)
39
+
40
+ with torch.no_grad():
41
+ outputs = model.generate(
42
+ input_ids=inputs.input_ids,
43
+ pixel_values=pixel_values,
44
+ max_new_tokens=4096,
45
+ do_sample=False,
46
+ repetition_penalty=1.1
47
+ )
48
+
49
+ # 4. Decode the result, skipping the input tokens
50
+ response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
51
+ return response.strip()
52
 
53
+ except Exception as e:
54
+ return f"Processing Error: {str(e)}\n\nTip: If this persists, try cropping the image to just the tables."
 
 
55
 
56
+ # UI with JS-based Copy Button for compatibility
57
  with gr.Blocks() as demo:
58
+ gr.Markdown("# πŸ“Š Precision Accountancy Table Extractor")
59
 
60
  with gr.Row():
61
  with gr.Column():
62
+ img_input = gr.Image(type="pil", label="Upload Document")
63
+ btn = gr.Button("Extract Markdown", variant="primary")
64
 
65
  with gr.Column():
66
  text_output = gr.Textbox(
67
  label="Extracted Result",
68
+ lines=25,
69
  interactive=True,
70
+ elem_id="result_box"
71
  )
72
  copy_btn = gr.Button("πŸ“‹ Copy to Clipboard")
73
 
74
+ # JavaScript to handle clipboard copy
75
  copy_btn.click(None, None, None, js="""
76
  () => {
77
+ const text = document.querySelector('#result_box textarea').value;
78
  navigator.clipboard.writeText(text);
79
+ alert('Text copied to clipboard!');
80
  }
81
  """)
82