BNP_PDF_statement_parser/bnp_pdf_statement_parser.py

82 lines
2.7 KiB
Python
Raw Normal View History

2023-06-21 00:36:27 +02:00
#!/usr/bin/python3
# Depends on `pdftotext`.
2023-11-05 21:10:45 +01:00
import os
import subprocess
import re
2023-06-21 00:36:27 +02:00
2023-11-05 21:10:45 +01:00
path = f'/home/benjamin/Desktop/bens_folder/bazaar/documents/bnp/bank_statements/'
2023-06-21 00:36:27 +02:00
os.chdir(path)
'''
Assuming file hierarchy like:
2022
20221121.pdf
20221221.pdf
2023
20230123.pdf
20230221.pdf
'''
def execute(command):
2023-07-28 18:15:03 +02:00
return subprocess.check_output(command).decode('utf-8')
2023-06-21 00:36:27 +02:00
def getTextFromPdf(pdfPath):
2023-11-05 21:10:45 +01:00
return execute(['pdftotext', '-raw', pdfPath, '-'])
2023-06-21 00:36:27 +02:00
firstLineOfPaymentRegex = re.compile('\d{2}\.\d{2} \d{2}\.\d{2} \d+,\d{2}')
endPageAfterTheFirstOneRegex = re.compile('P\. \d+/\d+')
2023-06-21 00:57:16 +02:00
soldeCrediteurAuRegex = re.compile('SOLDE CREDITEUR AU \d{2}\.\d{2}\.\d{4}')
2023-06-21 00:36:27 +02:00
for folder in os.listdir():
for file in os.listdir(folder):
2023-06-21 00:57:16 +02:00
#folder = '2022'
#file = '20220321.pdf'
2023-06-21 00:36:27 +02:00
filePath = f'{folder}/{file}'
print(filePath)
2023-06-21 00:36:27 +02:00
content = getTextFromPdf(filePath)
lines = content.splitlines()
started = False
firstPage = True
2023-06-21 00:57:16 +02:00
initialAmount = None
currentAmount = None
date = None
comment = []
2023-06-21 00:36:27 +02:00
for line in lines:
if not started:
# We are interested in the content after this line:
2023-09-14 20:18:51 +02:00
if soldeCrediteurAuRegex.match(line) is not None or (line.startswith('Date Nature des opérations Valeur Débit Crédit') and not firstPage):
2023-06-21 00:57:16 +02:00
if soldeCrediteurAuRegex.match(line):
initialAmount = float(soldeCrediteurAuRegex.sub('', line).replace(',', '.').replace(' ', ''))
currentAmount = initialAmount
print('Initial amount', initialAmount)
print()
2023-06-21 00:36:27 +02:00
started = True
continue
else:
# We aren't interested in the content after this line:
2023-09-14 20:18:51 +02:00
if line.startswith('BNP PARIBAS SA au capital de') or endPageAfterTheFirstOneRegex.match(line) is not None:
2023-06-21 00:36:27 +02:00
firstPage = False
started = False
continue
# We aren't interested in the content after this line
elif line.startswith('TOTAL DES OPERATIONS'):
break
2023-09-14 20:18:51 +02:00
if firstLineOfPaymentRegex.match(line) is not None:
if date is not None:
print(date, valeur, amount, currentAmount)
print('\n'.join(comment))
print()
date, valeur, amount = line.split()
amount = float(amount.replace(',', '.'))
currentAmount -= amount
comment = []
else:
comment += [line]
2023-06-21 00:36:27 +02:00
break
break