pratyyush commited on
Commit
321e4a9
Β·
verified Β·
1 Parent(s): 637d19f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -23
app.py CHANGED
@@ -2,10 +2,9 @@ import gradio as gr
2
  from doctr.models import ocr_predictor
3
  import numpy as np
4
 
5
- # Load lightweight CPU model
6
  model = ocr_predictor(det_arch='db_resnet50', reco_arch='crnn_vgg16_bn', pretrained=True)
7
 
8
- def extract_aligned_table(image):
9
  if image is None:
10
  return "Please upload an image."
11
 
@@ -15,9 +14,9 @@ def extract_aligned_table(image):
15
 
16
  markdown_rows = []
17
 
18
- # Define Column Boundaries (Adjusted for typical Accountancy Layouts)
19
- # These are percentages of the page width (0.0 to 1.0)
20
- col_bounds = [0.25, 0.65, 0.85] # Boundaries between Col 1|2, 2|3, 3|4
21
 
22
  for page in json_export['pages']:
23
  words_list = []
@@ -30,7 +29,6 @@ def extract_aligned_table(image):
30
 
31
  if not words_list: continue
32
 
33
- # 1. Sort and Group into Rows
34
  words_list.sort(key=lambda w: w['y'])
35
  rows = []
36
  current_row = [words_list[0]]
@@ -42,49 +40,53 @@ def extract_aligned_table(image):
42
  current_row = [words_list[i]]
43
  rows.append(current_row)
44
 
45
- # 2. Assign words to specific Column "Buckets"
46
  for row in rows:
47
- # Create 4 empty slots for [Acc Num, Acc Name, Debit, Credit]
48
  slots = ["", "", "", ""]
 
49
 
50
  for w in row:
51
  x = w['x']
52
- if x < col_bounds[0]:
53
- slots[0] += w['text'] + " "
 
 
 
 
 
 
 
 
54
  elif x < col_bounds[1]:
55
- slots[1] += w['text'] + " "
56
  elif x < col_bounds[2]:
57
- slots[2] += w['text'] + " "
58
  else:
59
- slots[3] += w['text'] + " "
60
 
61
- # Clean up extra spaces and add to markdown
62
  clean_slots = [s.strip() for s in slots]
63
  markdown_rows.append("| " + " | ".join(clean_slots) + " |")
64
 
65
  return "\n".join(markdown_rows)
66
 
67
- # UI with JS-based Copy
68
  with gr.Blocks() as demo:
69
- gr.Markdown("## πŸ“‘ Accountancy Aligned Table Extractor")
70
- gr.Markdown("This version uses fixed columns to prevent Debit and Credit from merging.")
71
 
72
  with gr.Row():
73
  with gr.Column():
74
- img_in = gr.Image(type="pil", label="Upload Trial Balance")
75
- btn = gr.Button("Extract with Columns", variant="primary")
76
  with gr.Column():
77
- out = gr.Textbox(label="Result", lines=20, elem_id="out_box")
78
  copy_btn = gr.Button("πŸ“‹ Copy Table")
79
-
80
  copy_btn.click(None, None, None, js="""
81
  () => {
82
  const text = document.querySelector('#out_box textarea').value;
83
  navigator.clipboard.writeText(text);
84
- alert('Table copied! Empty cells are now preserved.');
85
  }
86
  """)
87
 
88
- btn.click(extract_aligned_table, inputs=img_in, outputs=out)
89
 
90
  demo.launch()
 
2
  from doctr.models import ocr_predictor
3
  import numpy as np
4
 
 
5
  model = ocr_predictor(det_arch='db_resnet50', reco_arch='crnn_vgg16_bn', pretrained=True)
6
 
7
+ def extract_perfect_table(image):
8
  if image is None:
9
  return "Please upload an image."
10
 
 
14
 
15
  markdown_rows = []
16
 
17
+ # Precise Column Boundaries (Adjusted for 4-column accountancy papers)
18
+ # Bucket 1: < 22% | Bucket 2: 22%-62% | Bucket 3: 62%-82% | Bucket 4: > 82%
19
+ col_bounds = [0.22, 0.62, 0.82]
20
 
21
  for page in json_export['pages']:
22
  words_list = []
 
29
 
30
  if not words_list: continue
31
 
 
32
  words_list.sort(key=lambda w: w['y'])
33
  rows = []
34
  current_row = [words_list[0]]
 
40
  current_row = [words_list[i]]
41
  rows.append(current_row)
42
 
 
43
  for row in rows:
 
44
  slots = ["", "", "", ""]
45
+ row.sort(key=lambda w: w['x']) # Ensure words in row are left-to-right
46
 
47
  for w in row:
48
  x = w['x']
49
+ text = w['text']
50
+
51
+ # Logic to handle the "Debit Credit" header merging
52
+ if "Debit" in text and x > 0.55 and x < 0.75:
53
+ slots[2] += text + " "
54
+ elif "Credit" in text and x > 0.75:
55
+ slots[3] += text + " "
56
+ # General bucket logic for the rest of the rows
57
+ elif x < col_bounds[0]:
58
+ slots[0] += text + " "
59
  elif x < col_bounds[1]:
60
+ slots[1] += text + " "
61
  elif x < col_bounds[2]:
62
+ slots[2] += text + " "
63
  else:
64
+ slots[3] += text + " "
65
 
 
66
  clean_slots = [s.strip() for s in slots]
67
  markdown_rows.append("| " + " | ".join(clean_slots) + " |")
68
 
69
  return "\n".join(markdown_rows)
70
 
 
71
  with gr.Blocks() as demo:
72
+ gr.Markdown("## πŸ“‘ Final Accountancy Table Extractor")
73
+ gr.Markdown("Fixed header alignment for Debit/Credit columns.")
74
 
75
  with gr.Row():
76
  with gr.Column():
77
+ img_in = gr.Image(type="pil")
78
+ btn = gr.Button("Extract Table", variant="primary")
79
  with gr.Column():
80
+ out = gr.Textbox(label="Copy-Paste Ready", lines=20, elem_id="out_box")
81
  copy_btn = gr.Button("πŸ“‹ Copy Table")
 
82
  copy_btn.click(None, None, None, js="""
83
  () => {
84
  const text = document.querySelector('#out_box textarea').value;
85
  navigator.clipboard.writeText(text);
86
+ alert('Table copied! Header columns are now separated.');
87
  }
88
  """)
89
 
90
+ btn.click(extract_perfect_table, inputs=img_in, outputs=out)
91
 
92
  demo.launch()