pratyyush commited on
Commit
fd39222
·
verified ·
1 Parent(s): 63b2a7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -43
app.py CHANGED
@@ -1,61 +1,67 @@
1
  import gradio as gr
2
- from transformers import AutoModel, AutoTokenizer
3
  import torch
4
  from PIL import Image
 
5
 
6
- # Use the same model ID
7
  model_id = "zai-org/GLM-OCR"
8
 
9
- # 1. Load the tokenizer and model with remote code enabled
10
- # We use AutoModel because GLM-OCR has a custom vision-language architecture
11
- tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
12
- model = AutoModel.from_pretrained(
13
- model_id,
14
- trust_remote_code=True,
15
- device_map="auto",
16
- torch_dtype=torch.float16
17
  ).eval()
18
 
19
  def process_accountancy_image(input_image):
20
  if input_image is None:
21
  return "Please upload an image."
22
 
23
- # Define the specific prompt for accountancy extraction
24
- prompt = (
25
- "Extract all text and tables from this image. "
26
- "If there is an accountancy table (Ledger, Balance Sheet, P&L), "
27
- "format it strictly as a Markdown table. Preserve all symbols and currency signs."
28
- )
29
-
30
- # FIX: GLM-OCR uses a custom 'chat' method usually defined in its modeling script
31
- # We will use the model's own chat functionality which handles the image processing internally
32
- try:
33
- # Most GLM vision models use this specific internal method for inference
34
- with torch.no_grad():
35
- response, _ = model.chat(
36
- tokenizer,
37
- query=prompt,
38
- images=[input_image],
39
- history=[]
40
- )
41
- return response
42
- except Exception as e:
43
- return f"Extraction Error: {str(e)}\n\nTry ensuring the image is clear and not too large."
44
-
45
- # Gradio Interface
46
- with gr.Blocks() as demo:
47
- gr.Markdown("# 📊 Professional Accountancy Table Extractor")
48
- gr.Markdown("Extracts complex ledgers and financial tables into Markdown format.")
49
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  with gr.Row():
51
  with gr.Column():
52
- image_input = gr.Image(type="pil", label="Upload Accountancy Question")
53
- submit_btn = gr.Button("Extract Text & Tables", variant="primary")
54
-
55
  with gr.Column():
56
- text_output = gr.Markdown(label="Extracted Result")
57
-
58
- submit_btn.click(fn=process_accountancy_image, inputs=image_input, outputs=text_output)
59
 
60
- # Launching with the fix for Gradio 6 theme warning
61
  demo.launch()
 
1
  import gradio as gr
 
2
  import torch
3
  from PIL import Image
4
+ from transformers import AutoProcessor, GlmOcrForConditionalGeneration
5
 
6
+ # 1. Load the model and processor correctly
7
  model_id = "zai-org/GLM-OCR"
8
 
9
+ # Processor handles both the image and the text encoding
10
+ processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
11
+ model = GlmOcrForConditionalGeneration.from_pretrained(
12
+ model_id,
13
+ trust_remote_code=True,
14
+ device_map="auto",
15
+ torch_dtype=torch.bfloat16 # Use bfloat16 for better accuracy on T4/A10G GPUs
 
16
  ).eval()
17
 
18
  def process_accountancy_image(input_image):
19
  if input_image is None:
20
  return "Please upload an image."
21
 
22
+ # 2. Prepare the input using the standard conversation format
23
+ prompt = "Extract all text and tables from this accountancy question. Format tables in Markdown."
24
+
25
+ messages = [
26
+ {
27
+ "role": "user",
28
+ "content": [
29
+ {"type": "image", "image": input_image},
30
+ {"type": "text", "text": prompt},
31
+ ],
32
+ }
33
+ ]
34
+
35
+ # 3. Process inputs and generate
36
+ text = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
37
+ inputs = processor(text=[text], images=[input_image], return_tensors="pt").to(model.device)
38
+
39
+ with torch.no_grad():
40
+ output_ids = model.generate(
41
+ **inputs,
42
+ max_new_tokens=2048,
43
+ do_sample=False # Keep it deterministic for accounting numbers
44
+ )
 
 
 
45
 
46
+ # 4. Decode the result
47
+ # We slice the output to remove the input tokens and show only the answer
48
+ generated_ids = [
49
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)
50
+ ]
51
+ response = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)[0]
52
+
53
+ return response
54
+
55
+ # UI setup
56
+ with gr.Blocks() as demo:
57
+ gr.Markdown("# 📊 Precision Accountancy OCR")
58
  with gr.Row():
59
  with gr.Column():
60
+ img_in = gr.Image(type="pil", label="Upload Balance Sheet/Ledger")
61
+ btn = gr.Button("Extract Data", variant="primary")
 
62
  with gr.Column():
63
+ out = gr.Markdown()
64
+
65
+ btn.click(process_accountancy_image, inputs=img_in, outputs=out)
66
 
 
67
  demo.launch()