-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdfcsv.py
More file actions
executable file
·1538 lines (1224 loc) · 55.7 KB
/
pdfcsv.py
File metadata and controls
executable file
·1538 lines (1224 loc) · 55.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PDFcsv - Universal PDF to CSV Extractor
========================================
A powerful CLI tool for extracting tabular data from PDF documents with
intelligent column detection, bank statement support, and interactive
structure selection.
Features:
- Gap-based column detection using character X-positions
- Bank statement support with debit/credit column filling
- Interactive CLI with arrow-key navigation
- Structure grouping by column positions
- Multi-language keyword detection
Usage:
python pdfcsv.py input.pdf # Interactive mode
python pdfcsv.py input.pdf --analyze # Analyze column structure
python pdfcsv.py input.pdf --columns 6 # Extract specific column count
python pdfcsv.py input.pdf -o out.csv # Custom output path
python pdfcsv.py input.pdf --gap 10 # Adjust gap threshold
Requirements:
pip install pdfplumber
Author: @stexz01
License: MIT
Repository: https://github.com/stexz01/pdfcsv
"""
__version__ = "1.5.0"
__author__ = "@stexz01"
# Global silent mode flag
SILENT_MODE = False
# ═══════════════════════════════════════════════════════════════════════════════
# IMPORTS
# ═══════════════════════════════════════════════════════════════════════════════
import csv
import json
import os
import re
import sys
from collections import Counter
import pdfplumber
# Optional: Banking keywords for statement detection (graceful fallback if missing)
try:
from banking_keywords import is_bank_statement, DEBIT_KEYWORDS, CREDIT_KEYWORDS
BANKING_DETECTION_AVAILABLE = True
except ImportError:
BANKING_DETECTION_AVAILABLE = False
# Terminal raw input (Unix only, graceful fallback for Windows)
try:
import tty
import termios
_TERMINAL_RAW_INPUT = True
except ImportError:
_TERMINAL_RAW_INPUT = False
# ═══════════════════════════════════════════════════════════════════════════════
# COLORS & STYLING
# ═══════════════════════════════════════════════════════════════════════════════
class Colors:
# Basic colors
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
GRAY = '\033[90m'
# Styles
BOLD = '\033[1m'
DIM = '\033[2m'
UNDERLINE = '\033[4m'
# Reset
RESET = '\033[0m'
@classmethod
def disable(cls):
"""Disable colors for non-TTY output"""
for attr in dir(cls):
if attr.isupper():
setattr(cls, attr, '')
# Disable colors if not a terminal
if not sys.stdout.isatty():
Colors.disable()
def banner():
"""Print the PDFcsv banner"""
c = Colors
print(f"""
{c.CYAN}{c.BOLD}╔═══════════════════════════════════════════════════════════════╗
║ ║
║ {c.WHITE}██████╗ ██████╗ ███████╗{c.YELLOW} ██████╗███████╗██╗ ██╗{c.CYAN} ║
║ {c.WHITE}██╔══██╗██╔══██╗██╔════╝{c.YELLOW} ██╔════╝██╔════╝██║ ██║{c.CYAN} ║
║ {c.WHITE}██████╔╝██║ ██║█████╗ {c.YELLOW} ██║ ███████╗██║ ██║{c.CYAN} ║
║ {c.WHITE}██╔═══╝ ██║ ██║██╔══╝ {c.YELLOW} ██║ ╚════██║╚██╗ ██╔╝{c.CYAN} ║
║ {c.WHITE}██║ ██████╔╝██║ {c.YELLOW} ╚██████╗███████║ ╚████╔╝ {c.CYAN} ║
║ {c.WHITE}╚═╝ ╚═════╝ ╚═╝ {c.YELLOW} ╚═════╝╚══════╝ ╚═══╝ {c.CYAN} ║
║ ║
║ {c.DIM}Universal PDF to CSV Extractor {c.WHITE}v{__version__}{c.CYAN} ║
║ {c.DIM}Made with {c.RED}♥{c.DIM} by {c.WHITE}{__author__}{c.CYAN} ║
║ ║
╚═══════════════════════════════════════════════════════════════╝{c.RESET}
""")
def print_step(num, text):
"""Print a step indicator"""
if SILENT_MODE:
return
c = Colors
print(f"{c.CYAN}{c.BOLD}[{num}]{c.RESET} {text}")
def print_success(text):
"""Print success message"""
if SILENT_MODE:
return
c = Colors
print(f"{c.GREEN}{c.BOLD}✓{c.RESET} {text}")
def print_error(text):
"""Print error message (always shown, even in silent mode)"""
c = Colors
print(f"{c.RED}{c.BOLD}✗{c.RESET} {text}")
def print_info(text):
"""Print info message"""
if SILENT_MODE:
return
c = Colors
print(f"{c.BLUE}ℹ{c.RESET} {text}")
def print_warning(text):
"""Print warning message"""
if SILENT_MODE:
return
c = Colors
print(f"{c.YELLOW}⚠{c.RESET} {text}")
# ═══════════════════════════════════════════════════════════════════════════════
# CORE EXTRACTION LOGIC
# ═══════════════════════════════════════════════════════════════════════════════
def open_pdf(pdf_path: str):
"""
Open a PDF file with automatic handling of encrypted documents.
Attempts to open normally first, then tries empty password for PDFs
with owner-only restrictions. If password-protected, prompts user
for password with retry support.
Args:
pdf_path: Path to the PDF file
Returns:
pdfplumber.PDF object
Raises:
SystemExit: If user cancels password entry
"""
c = Colors
try:
return pdfplumber.open(pdf_path)
except Exception as e1:
# Try with empty password for encrypted PDFs
try:
return pdfplumber.open(pdf_path, password="")
except Exception:
# Check if it's an encryption error (check str, repr, and type)
error_info = f"{str(e1).lower()} {repr(e1).lower()} {str(type(e1))}"
if "password" in error_info or "encrypt" in error_info:
print(f"\n{c.YELLOW}{c.BOLD}PDF is password-protected{c.RESET}")
print(f"{c.DIM}File: {pdf_path}{c.RESET}")
print(f"{c.DIM}Enter password or 'q' to quit{c.RESET}\n")
# Password retry loop
attempts = 0
while True:
try:
attempts += 1
password = input(f"{c.CYAN}Password:{c.RESET} ")
# Check for quit
if password.lower() == 'q':
print(f"{c.YELLOW}Cancelled{c.RESET}\n")
sys.exit(0)
# Try opening with password
try:
pdf = pdfplumber.open(pdf_path, password=password)
print(f"{c.GREEN}{c.BOLD}✓{c.RESET} Password accepted\n")
return pdf
except Exception:
print(f"{c.RED}✗ Wrong password{c.RESET} {c.DIM}(attempt {attempts}){c.RESET}")
continue
except (KeyboardInterrupt, EOFError):
print(f"\n{c.YELLOW}Cancelled{c.RESET}\n")
sys.exit(0)
raise e1
def _extract_tables(pdf) -> list:
"""
Extract data from an open PDF using pdfplumber's built-in table detection.
Works for PDFs with structured tables (gridlines/borders).
Handles multi-line cells by joining text within each cell.
Args:
pdf: An open pdfplumber.PDF object
Returns:
List of rows (each row is a list of strings), or empty list if no tables found.
"""
all_rows = []
for page in pdf.pages:
tables = page.extract_tables()
for table in tables:
for row in table:
cleaned = []
for cell in row:
if cell:
text = re.sub(r'\s+', ' ', cell.replace('\n', ' ').strip())
cleaned.append(text)
else:
cleaned.append('')
all_rows.append(cleaned)
return all_rows
def clean_table_rows(rows: list, min_filled: int = 2) -> list:
"""
Clean extracted table rows:
- Remove fully empty rows
- Remove rows with too few meaningful values (page-break header remnants)
Args:
rows: Raw table rows
min_filled: Minimum non-empty, non-dash cells to keep a row
Returns:
Cleaned list of rows
"""
if not rows:
return []
cleaned = []
for row in rows:
meaningful = sum(
1 for cell in row
if cell and cell.strip() and cell.strip() != '-'
)
if meaningful >= min_filled:
cleaned.append(row)
return cleaned
def _table_has_concatenated_cells(rows: list) -> bool:
"""
Detect if table rows contain concatenated multi-record data.
Some PDFs (e.g. HDFC statements) pack multiple transactions into a single
table cell. This produces rows where date/amount fields contain multiple
space-separated values, which is not useful for CSV extraction.
Returns True if cells appear to contain concatenated records.
"""
if len(rows) < 2:
return False
# Check first few data rows (skip possible header)
data_rows = rows[1:min(6, len(rows))]
if not data_rows:
data_rows = rows[:min(5, len(rows))]
for row in data_rows:
for cell in row:
if not cell or len(cell) < 20:
continue
# Multiple date patterns in a single cell = concatenated records
if len(re.findall(r'\d{2}/\d{2}/\d{2,4}', cell)) > 1:
return True
if len(re.findall(r'\d{1,2}\s+\w{3}\s+\d{2,4}', cell)) > 1:
return True
return False
def _warn_broken_headers(raw_rows: list, cleaned_rows: list):
"""
Detect and warn if column headers are missing from table extraction.
Some PDFs (e.g. SBI statements) render header text as vector graphics
(tiny filled rectangles) instead of actual text characters. This makes
them invisible to any text-based PDF extraction library.
Checks raw table rows for rows that were cleaned away (mostly empty cells)
which likely represent broken/unextractable header rows.
"""
if not raw_rows or not cleaned_rows:
return
# Find the dominant column count in cleaned data
col_counts = Counter(len(r) for r in cleaned_rows)
target_cols = col_counts.most_common(1)[0][0]
# Check raw rows that were removed by cleaning — they might be broken headers
cleaned_set = {tuple(r) for r in cleaned_rows}
for row in raw_rows:
if tuple(row) in cleaned_set or len(row) != target_cols:
continue
# Row was removed and has the right column count — check if it's a broken header
empty_count = sum(1 for cell in row if not cell or not cell.strip())
if empty_count > len(row) // 2:
# More than half the cells are empty — broken header
filled = [cell.strip() for cell in row if cell and cell.strip()]
filled_str = ', '.join(filled) if filled else 'none'
print_warning(
f"Column headers not extractable (rendered as vector graphics in PDF)"
)
print_info(
f"{Colors.DIM}Only partial header recovered: [{filled_str}]{Colors.RESET}"
)
return
def table_rows_to_lines(rows: list) -> list:
"""
Convert table-extracted rows to the lines format used by gap-based extraction.
Uses dummy x_positions since table extraction doesn't provide pixel positions.
"""
return [
{
'col_count': len(row),
'columns': row,
'x_positions': list(range(len(row)))
}
for row in rows
]
def _extract_gaps(pdf, gap_threshold: int = 5) -> list:
"""
Internal: gap-based column extraction from an open pdfplumber PDF.
Groups characters by Y position, detects column breaks where gaps
between characters exceed threshold.
"""
all_lines = []
for page in pdf.pages:
chars = page.chars
if not chars:
continue
# Group characters by Y position (lines)
lines_by_y = {}
for c in chars:
y = round(c['top'])
if y not in lines_by_y:
lines_by_y[y] = []
lines_by_y[y].append(c)
# Process each line
for y in sorted(lines_by_y.keys()):
row_chars = sorted(lines_by_y[y], key=lambda c: c['x0'])
# Build columns by detecting gaps
columns = []
x_positions = []
current_col = []
col_start_x = None
for i, char in enumerate(row_chars):
if i > 0:
gap = char['x0'] - row_chars[i-1]['x1']
if gap > gap_threshold:
col_text = ''.join(c['text'] for c in current_col)
if col_text.strip():
columns.append(col_text.strip())
x_positions.append(col_start_x)
current_col = []
col_start_x = None
if col_start_x is None:
col_start_x = char['x0']
current_col.append(char)
# Don't forget last column
if current_col:
col_text = ''.join(c['text'] for c in current_col)
if col_text.strip():
columns.append(col_text.strip())
x_positions.append(col_start_x)
if columns:
all_lines.append({
'col_count': len(columns),
'columns': columns,
'x_positions': x_positions
})
return all_lines
def extract_lines_with_gaps(pdf_path: str, gap_threshold: int = 5) -> list:
"""
Extract text lines from PDF using gap-based column detection.
This is the core extraction algorithm. It works by:
1. Extracting all characters with their X,Y positions
2. Grouping characters by Y position (same line)
3. Detecting column breaks where gaps between characters exceed threshold
4. Recording X positions for structure-based grouping
Args:
pdf_path: Path to the PDF file
gap_threshold: Minimum pixel gap to consider a column break (default: 5)
Returns:
List of dicts, each containing:
- col_count: Number of columns detected
- columns: List of text values for each column
- x_positions: List of X coordinates for each column start
"""
with open_pdf(pdf_path) as pdf:
return _extract_gaps(pdf, gap_threshold)
def find_header_row(lines: list) -> dict:
"""
Find the header row in bank statement data.
Searches for rows containing both debit and credit keywords,
preferring rows with more columns (typical of headers).
Args:
lines: List of extracted line dicts
Returns:
Header line dict or None if not found
"""
if not BANKING_DETECTION_AVAILABLE:
return None
best_match = None
best_score = 0
for line in lines:
text = ' '.join(line['columns']).lower()
score = 0
# Check for debit keywords
for kw in DEBIT_KEYWORDS:
if kw in text:
score += 1
break
# Check for credit keywords
for kw in CREDIT_KEYWORDS:
if kw in text:
score += 1
break
# Prefer rows with more columns (likely headers)
if score >= 2 and line['col_count'] > best_score:
best_match = line
best_score = line['col_count']
return best_match
def keyword_matches(col: str, keywords: set) -> bool:
"""
Check if column header matches banking keywords with word boundary awareness.
Uses smart matching to prevent false positives:
- Short keywords (<=3 chars): require word boundary match
- Longer keywords: substring match is sufficient
Example: 'cr' won't match 'description' but will match 'CR' or 'Cr.'
Args:
col: Column header text
keywords: Set of keywords to match against
Returns:
True if any keyword matches
"""
col_lower = col.lower().strip()
for kw in keywords:
# For very short keywords (2-3 chars), require exact match or word boundary
if len(kw) <= 3:
# Check if column equals keyword exactly, or keyword is at word boundary
if col_lower == kw or re.search(rf'\b{re.escape(kw)}\b', col_lower):
return True
else:
# For longer keywords, substring match is fine
if kw in col_lower:
return True
return False
def find_debit_credit_column_indices(header: dict) -> tuple:
"""
Identify debit and credit column positions in a bank statement header.
Args:
header: Header line dict with 'columns' key
Returns:
Tuple of (debit_index, credit_index), or (None, None) if not found
"""
if not header or not BANKING_DETECTION_AVAILABLE:
return None, None
debit_idx = None
credit_idx = None
for i, col in enumerate(header['columns']):
if debit_idx is None and keyword_matches(col, DEBIT_KEYWORDS):
debit_idx = i
if credit_idx is None and keyword_matches(col, CREDIT_KEYWORDS):
credit_idx = i
return debit_idx, credit_idx
def fill_empty_columns(lines: list, header: dict, target_col_count: int) -> list:
"""
Fill missing debit/credit columns with '-' using gap analysis.
Bank statements often have empty debit OR credit columns per row.
This function determines which column is missing by comparing the
gap between the amount and balance columns against header patterns.
Handles:
- 1 missing column (debit OR credit empty)
- 2 missing columns (both debit AND credit need filling)
Args:
lines: List of extracted line dicts
header: Header row dict with column positions
target_col_count: Expected column count for data rows
Returns:
List of column lists with '-' inserted where needed
"""
if not header or 'x_positions' not in header:
return [line['columns'] for line in lines if line['col_count'] == target_col_count]
header_x = header['x_positions']
header_cols = header['columns']
debit_idx, credit_idx = find_debit_credit_column_indices(header)
if debit_idx is None or credit_idx is None:
return [line['columns'] for line in lines if line['col_count'] == target_col_count]
# Balance column is the last one
balance_idx = len(header_cols) - 1
# Calculate expected gaps from header positions
header_debit_to_balance = header_x[balance_idx] - header_x[debit_idx]
header_credit_to_balance = header_x[balance_idx] - header_x[credit_idx]
filled_rows = []
for line in lines:
# If line has same column count as header, use as-is
if line['col_count'] == len(header_cols):
filled_rows.append(line['columns'])
continue
# If line has one less column than header (missing debit OR credit)
if line['col_count'] == len(header_cols) - 1:
columns = list(line['columns'])
x_pos = line.get('x_positions', [])
if not x_pos or len(x_pos) < 2:
filled_rows.append(line['columns'])
continue
amount_col_idx = debit_idx
balance_col_idx = len(columns) - 1
if amount_col_idx < len(x_pos) and balance_col_idx < len(x_pos):
amount_x = x_pos[amount_col_idx]
balance_x = x_pos[balance_col_idx]
data_gap = balance_x - amount_x
diff_to_debit_pattern = abs(data_gap - header_debit_to_balance)
diff_to_credit_pattern = abs(data_gap - header_credit_to_balance)
if diff_to_debit_pattern < diff_to_credit_pattern:
columns.insert(credit_idx, '-')
else:
columns.insert(debit_idx, '-')
filled_rows.append(columns)
else:
filled_rows.append(line['columns'])
# If line has TWO less columns than header (missing Chq No AND Debit/Credit)
# Common pattern: [Date, Particulars, Amount, Balance, Init] → need [Date, Chq, Part, Debit, Credit, Bal, Init]
elif line['col_count'] == len(header_cols) - 2:
columns = list(line['columns'])
x_pos = line.get('x_positions', [])
if not x_pos or len(x_pos) < 2:
filled_rows.append(line['columns'])
continue
# Step 1: Insert '-' for missing Chq No (usually at index 1)
# This assumes the pattern: Date is col 0, then Chq No is missing, Particulars is col 1 in data
chq_idx = 1 # Chq No is typically column 1 in bank statements
if chq_idx < debit_idx: # Only insert if Chq comes before Debit/Credit
columns.insert(chq_idx, '-')
# Now columns has header-1 count, apply normal debit/credit gap-fill
# Recalculate indices after insertion
amount_col_idx = debit_idx # In the now 6-col row
balance_col_idx = len(columns) - 2 # Second to last (before Init)
if amount_col_idx < len(x_pos) and balance_col_idx < len(x_pos):
# Use original x_pos (before Chq insertion) to determine gap
orig_amount_idx = amount_col_idx - 1 # Adjust for inserted Chq
orig_balance_idx = balance_col_idx - 1
if orig_amount_idx >= 0 and orig_amount_idx < len(x_pos) and orig_balance_idx < len(x_pos):
amount_x = x_pos[orig_amount_idx]
balance_x = x_pos[orig_balance_idx]
data_gap = balance_x - amount_x
diff_to_debit = abs(data_gap - header_debit_to_balance)
diff_to_credit = abs(data_gap - header_credit_to_balance)
# Insert '-' for missing Debit or Credit
if diff_to_debit < diff_to_credit:
# Amount is in debit position, credit is missing
columns.insert(credit_idx, '-')
else:
# Amount is in credit position, debit is missing
columns.insert(debit_idx, '-')
filled_rows.append(columns)
else:
# Fallback: just insert both placeholders
if credit_idx > debit_idx:
columns.insert(credit_idx, '-')
else:
columns.insert(debit_idx, '-')
filled_rows.append(columns)
else:
# Can't determine gap, insert credit placeholder as default
columns.insert(credit_idx, '-')
filled_rows.append(columns)
elif line['col_count'] == target_col_count:
filled_rows.append(line['columns'])
return filled_rows
_DATE_RE = re.compile(
r'^\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}$'
r'|^\d{1,2}\s+\w{3}\s+\d{2,4}$'
r'|^\d{4}[/\-\.]\d{1,2}[/\-\.]\d{1,2}$'
)
def filter_non_date_rows(data_rows: list) -> tuple:
"""
Filter out rows whose first column is not a date, when the data
appears to be date-indexed (e.g. bank statements, invoices).
Only activates when >50% of rows already start with a recognisable
date pattern, so non-date PDFs are unaffected.
Returns:
Tuple of (filtered_rows, count_removed)
"""
if not data_rows or len(data_rows) < 3:
return data_rows, 0
date_count = sum(
1 for row in data_rows
if row and _DATE_RE.match(str(row[0]).strip())
)
date_ratio = date_count / len(data_rows)
if date_ratio < 0.5:
return data_rows, 0
filtered = []
for row in data_rows:
first_col = str(row[0]).strip() if row else ''
if _DATE_RE.match(first_col):
filtered.append(row)
removed = len(data_rows) - len(filtered)
return filtered, removed
def find_winning_column_count(lines: list, min_columns: int = 2) -> int:
"""Find the most common column count (ignoring lines with < min_columns)"""
counts = [line['col_count'] for line in lines if line['col_count'] >= min_columns]
if not counts:
return 0
counter = Counter(counts)
winner, _ = counter.most_common(1)[0]
return winner
def extract_data_rows(lines: list) -> tuple:
"""Extract only lines matching the winning column count"""
winner = find_winning_column_count(lines)
data_rows = [line['columns'] for line in lines if line['col_count'] == winner]
return data_rows, winner
def check_bank_statement(lines: list) -> dict:
"""
Check if the PDF appears to be a bank statement.
Returns detection info including found keywords.
"""
if not BANKING_DETECTION_AVAILABLE:
return {'is_bank': False, 'debit_found': [], 'credit_found': []}
# Combine all text from lines
all_text = ' '.join(' '.join(line['columns']) for line in lines).lower()
# Check for debit/credit keywords
debit_found = [kw for kw in DEBIT_KEYWORDS if kw in all_text]
credit_found = [kw for kw in CREDIT_KEYWORDS if kw in all_text]
is_bank = is_bank_statement(all_text)
return {
'is_bank': is_bank,
'debit_found': debit_found[:3], # Limit to 3 examples
'credit_found': credit_found[:3],
}
def analyze_lines(lines: list):
"""Print detailed analysis of column counts"""
c = Colors
counter = Counter(line['col_count'] for line in lines)
print(f"\n{c.BOLD}Column Count Analysis{c.RESET}")
print(f"{c.GRAY}{'─' * 50}{c.RESET}")
winner = counter.most_common(1)[0][0] if counter else 0
for count, freq in counter.most_common():
bar_len = int((freq / max(counter.values())) * 20)
bar = '█' * bar_len + '░' * (20 - bar_len)
if count == winner:
marker = f" {c.GREEN}← WINNER{c.RESET}"
else:
marker = ""
print(f" {c.CYAN}{count:2d} cols{c.RESET} │ {c.YELLOW}{bar}{c.RESET} │ {freq:4d} lines{marker}")
print(f"{c.GRAY}{'─' * 50}{c.RESET}")
# Show samples
print(f"\n{c.BOLD}Samples by Column Count{c.RESET}\n")
for count in sorted(counter.keys()):
samples = [l for l in lines if l['col_count'] == count][:2]
print(f" {c.CYAN}{c.BOLD}{count} columns:{c.RESET}")
for s in samples:
preview = str(s['columns'])
if len(preview) > 70:
preview = preview[:67] + "..."
print(f" {c.DIM}{preview}{c.RESET}")
print()
# ═══════════════════════════════════════════════════════════════════════════════
# INTERACTIVE CLI
# ═══════════════════════════════════════════════════════════════════════════════
def get_key():
"""
Read a single keypress from stdin, handling arrow keys.
Returns:
'UP', 'DOWN', 'ENTER', 'QUIT', 'ESC', or the character pressed
"""
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
# Handle escape sequences (arrow keys)
if ch == '\x1b':
ch2 = sys.stdin.read(1)
if ch2 == '[':
ch3 = sys.stdin.read(1)
if ch3 == 'A':
return 'UP'
elif ch3 == 'B':
return 'DOWN'
return 'ESC'
elif ch == '\r' or ch == '\n':
return 'ENTER'
elif ch == 'q' or ch == '\x03': # q or Ctrl+C
return 'QUIT'
return ch
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
def interactive_column_selector(lines: list, header_row: dict = None) -> int:
"""
Interactive CLI for selecting column structure with arrow key navigation.
Displays available column counts with row frequencies, allows user to
navigate with arrow keys, and shows a live preview of selected structure.
For bank statements, shows header row and gap-filled data preview.
Args:
lines: List of extracted line dicts
header_row: Optional header dict for bank statement preview
Returns:
Selected column count, or 0 if cancelled
"""
c = Colors
# For bank statements, filter out low-column metadata rows (2-3 cols are usually key:value pairs)
min_cols = 4 if header_row else 2
counter = Counter(line['col_count'] for line in lines if line['col_count'] >= min_cols)
if not counter:
# Fallback to 2+ columns if no results
counter = Counter(line['col_count'] for line in lines if line['col_count'] >= 2)
if not counter:
return 0
# Build options grouped by OUTPUT column count (after gap-filling)
# Maps output_col_count -> (total_rows, [source_col_counts])
output_groups = {}
for col_count, freq in counter.items():
# Determine output column count
output_cols = col_count
# Map header-1 columns to header (gap-fill adds 1 column for Debit/Credit)
if header_row and col_count == len(header_row['columns']) - 1:
output_cols = len(header_row['columns'])
# Map header-2 columns to header (gap-fill adds 2 columns: Chq + Debit/Credit)
elif header_row and col_count == len(header_row['columns']) - 2:
output_cols = len(header_row['columns']) # Both 5-col and 6-col become 7-col
if output_cols not in output_groups:
output_groups[output_cols] = {'rows': 0, 'sources': []}
output_groups[output_cols]['rows'] += freq
output_groups[output_cols]['sources'].append(col_count)
# Sort by row count (most common first)
options = sorted(output_groups.items(), key=lambda x: -x[1]['rows'])
total = len(options)
selected = 0
# Auto-select if only one option exists
if total == 1:
selected_count = options[0][0]
freq = options[0][1]['rows']
if not SILENT_MODE:
print(f"\n {c.GREEN}{c.BOLD}✓{c.RESET} Auto-selected: {c.WHITE}{c.BOLD}{selected_count} columns{c.RESET} ({freq} rows)\n")
return selected_count
# Precompute samples for each output option (with gap-filling applied)
samples_cache = {}
header_text = ' '.join(header_row['columns']).lower() if header_row else ''
# Pre-check if gap-filling will work
can_gap_fill = False
if header_row:
debit_idx, credit_idx = find_debit_credit_column_indices(header_row)
can_gap_fill = debit_idx is not None and credit_idx is not None
for output_cols, info in options:
# Get samples from source col_counts
# Prioritize gap-filled samples (they're the actual bank transactions)
filled_samples = []
other_samples = []
for src_col in info['sources']:
# Filter out header row from samples
raw_samples = []
for l in lines:
if l['col_count'] == src_col:
# Skip if this looks like the header row
if header_row and ' '.join(l['columns']).lower() == header_text:
continue
raw_samples.append(l)
if len(raw_samples) >= 7:
break
if header_row and can_gap_fill:
# Try gap-filling for header-1 or header-2 column rows
if src_col == len(header_row['columns']) - 1 or src_col == len(header_row['columns']) - 2:
filled = fill_empty_columns(raw_samples[:5], header_row, src_col)
# Verify gap-filling actually produced column count close to header
for f in filled:
if len(f) >= len(header_row['columns']) - 1:
filled_samples.append(f)
else:
other_samples.append(f)
else:
other_samples.extend([s['columns'] for s in raw_samples[:5]])
else:
other_samples.extend([s['columns'] for s in raw_samples[:5]])
# Prefer gap-filled samples, then other samples
all_samples = filled_samples + other_samples
samples_cache[output_cols] = all_samples[:5]
# Calculate fixed height
# Header(3) + separator(1) + options(1 each) + separator(1) + header(1) + samples(4) + separator(1) + controls(1) + padding(2)
fixed_height = 3 + 1 + total + 1 + 1 + 4 + 1 + 1 + 2
def clear_area():
"""Move cursor up and clear the display area"""
sys.stdout.write(f"\033[{fixed_height}A") # Move up
sys.stdout.write("\033[J") # Clear from cursor to end
sys.stdout.flush()
def render(sel_idx):
"""Render the selector UI"""
lines_out = []
# Header with map count
lines_out.append("")
lines_out.append(f" {c.BOLD}({total}) Map found{c.RESET} - {c.DIM}Select the perfect one{c.RESET}")
lines_out.append("") # New line after title
lines_out.append(f" {c.GRAY}{'─' * 58}{c.RESET}")
# Options list - format: (rows) columns
for i, (output_cols, info) in enumerate(options):
freq = info['rows']
if i == sel_idx:
lines_out.append(f" {c.CYAN}{c.BOLD}▸{c.RESET} {c.GREEN}({freq} rows){c.RESET} {c.WHITE}{c.BOLD}{output_cols} columns{c.RESET}")
else:
lines_out.append(f" {c.DIM} ({freq} rows) {output_cols} columns{c.RESET}")
lines_out.append(f" {c.GRAY}{'─' * 58}{c.RESET}")
# Preview of selected option
sel_output_cols = options[sel_idx][0]
samples = samples_cache[sel_output_cols]
# Determine header: use bank header if available and samples match its column count
# Check if samples actually have the expected column count (gap-filled)
samples_have_header_cols = (
header_row and
samples and
len(samples[0]) == len(header_row['columns'])
)
if samples_have_header_cols:
header_cols = header_row['columns']
preview_samples = samples # Show all samples as data (gap-filled)
elif samples:
header_cols = samples[0] # First row becomes header
preview_samples = samples[1:] if len(samples) > 1 else [] # Rest are data
else:
header_cols = []