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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -40
app.py CHANGED
@@ -5,7 +5,7 @@ import numpy as np
5
  # Load lightweight CPU model
6
  model = ocr_predictor(det_arch='db_resnet50', reco_arch='crnn_vgg16_bn', pretrained=True)
7
 
8
- def extract_intelligent_table(image):
9
  if image is None:
10
  return "Please upload an image."
11
 
@@ -15,28 +15,23 @@ def extract_intelligent_table(image):
15
 
16
  markdown_rows = []
17
 
 
 
 
 
18
  for page in json_export['pages']:
19
  words_list = []
20
  for block in page['blocks']:
21
  for line in block['lines']:
22
  for word in line['words']:
23
- # Calculate center Y and start/end X
24
  y_center = (word['geometry'][0][1] + word['geometry'][1][1]) / 2
25
  x_start = word['geometry'][0][0]
26
- x_end = word['geometry'][1][0]
27
- words_list.append({
28
- 'text': word['value'],
29
- 'y': y_center,
30
- 'x_start': x_start,
31
- 'x_end': x_end
32
- })
33
 
34
  if not words_list: continue
35
 
36
- # 1. Sort vertically by Y
37
  words_list.sort(key=lambda w: w['y'])
38
-
39
- # 2. Group into rows
40
  rows = []
41
  current_row = [words_list[0]]
42
  for i in range(1, len(words_list)):
@@ -47,43 +42,37 @@ def extract_intelligent_table(image):
47
  current_row = [words_list[i]]
48
  rows.append(current_row)
49
 
50
- # 3. Process each row with smart horizontal grouping
51
  for row in rows:
52
- row.sort(key=lambda w: w['x_start'])
53
-
54
- row_cells = []
55
- if not row: continue
56
 
57
- current_cell_text = row[0]['text']
58
-
59
- for j in range(1, len(row)):
60
- # Calculate the gap between the end of the last word and start of this one
61
- gap = row[j]['x_start'] - row[j-1]['x_end']
62
-
63
- # If the gap is small (e.g., < 3% of page width), keep in same cell
64
- if gap < 0.03:
65
- current_cell_text += " " + row[j]['text']
66
  else:
67
- # Large gap indicates a new column
68
- row_cells.append(current_cell_text)
69
- current_cell_text = row[j]['text']
70
-
71
- row_cells.append(current_cell_text)
72
 
73
- # Join cells with pipe for Markdown
74
- markdown_rows.append("| " + " | ".join(row_cells) + " |")
 
75
 
76
  return "\n".join(markdown_rows)
77
 
78
- # UI Setup
79
  with gr.Blocks() as demo:
80
- gr.Markdown("## πŸ“‘ Accountancy Table Extractor (Smart Cell Grouping)")
81
- gr.Markdown("This version detects gaps between words to keep phrases in a single cell.")
82
 
83
  with gr.Row():
84
  with gr.Column():
85
- img_in = gr.Image(type="pil", label="Upload Paper")
86
- btn = gr.Button("Extract Structured Table", variant="primary")
87
  with gr.Column():
88
  out = gr.Textbox(label="Result", lines=20, elem_id="out_box")
89
  copy_btn = gr.Button("πŸ“‹ Copy Table")
@@ -92,10 +81,10 @@ with gr.Blocks() as demo:
92
  () => {
93
  const text = document.querySelector('#out_box textarea').value;
94
  navigator.clipboard.writeText(text);
95
- alert('Copied! Cells are now correctly grouped.');
96
  }
97
  """)
98
 
99
- btn.click(extract_intelligent_table, inputs=img_in, outputs=out)
100
 
101
  demo.launch()
 
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
 
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 = []
24
  for block in page['blocks']:
25
  for line in block['lines']:
26
  for word in line['words']:
 
27
  y_center = (word['geometry'][0][1] + word['geometry'][1][1]) / 2
28
  x_start = word['geometry'][0][0]
29
+ words_list.append({'text': word['value'], 'y': y_center, 'x': x_start})
 
 
 
 
 
 
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]]
37
  for i in range(1, len(words_list)):
 
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")
 
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()