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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
#DSPY
|
| 4 |
+
import dspy
|
| 5 |
+
from dspy import Prediction
|
| 6 |
+
from dspy.evaluate import Evaluate
|
| 7 |
+
from dspy import Prediction
|
| 8 |
+
from dspy.teleprompt import BootstrapFewShot
|
| 9 |
+
from dspy.teleprompt import BootstrapFewShotWithRandomSearch
|
| 10 |
+
|
| 11 |
+
# Data handling
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from google.colab import drive
|
| 14 |
+
from google.colab import userdata
|
| 15 |
+
|
| 16 |
+
# Calculations and formatting
|
| 17 |
+
import re
|
| 18 |
+
from decimal import Decimal
|
| 19 |
+
|
| 20 |
+
# UI
|
| 21 |
+
import gradio as gr
|
| 22 |
+
from gradio_pdf import PDF
|
| 23 |
+
|
| 24 |
+
# PDF handling
|
| 25 |
+
import pdfplumber
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
pdf_examples_dir = './pdfexamples/'
|
| 29 |
+
|
| 30 |
+
model = dspy.OpenAI(
|
| 31 |
+
model='gpt-3.5-turbo-0125',
|
| 32 |
+
api_key=userdata.get('OPENAI_PROJECT_KEY'),
|
| 33 |
+
max_tokens=2000,
|
| 34 |
+
temperature=0.01)
|
| 35 |
+
|
| 36 |
+
dspy.settings.configure(lm=model)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Utils
|
| 40 |
+
def parse_CSV_string(csv_string):
|
| 41 |
+
# Parses a CSV string into a unique list
|
| 42 |
+
return list(set(map(str.lower, map(str.strip, csv_string.split(',')))))
|
| 43 |
+
|
| 44 |
+
def parse_list_of_CSV_strings(list_of_csv_strings):
|
| 45 |
+
# Parses a list of CSV strings with invoice numbers into a list of lists
|
| 46 |
+
parsed_csv_list = []
|
| 47 |
+
for csv_string in list_of_csv_strings:
|
| 48 |
+
parsed_csv_list.append(parse_CSV_string(csv_string))
|
| 49 |
+
return parsed_csv_list
|
| 50 |
+
|
| 51 |
+
def parse_invoice_number(s):
|
| 52 |
+
# Return the invoice number in Siemens' format if found, otherwise just return the string
|
| 53 |
+
rp = r'^\s*?([\S\d]+\d{6})'
|
| 54 |
+
m = re.search(rp, s)
|
| 55 |
+
return m.group(1) if m else s
|
| 56 |
+
|
| 57 |
+
def standardize_number(s):
|
| 58 |
+
# Find the last occurrence of a comma or period
|
| 59 |
+
last_separator_index = max(s.rfind(','), s.rfind('.'))
|
| 60 |
+
if last_separator_index != -1:
|
| 61 |
+
# Split the string into two parts
|
| 62 |
+
before_separator = s[:last_separator_index]
|
| 63 |
+
after_separator = s[last_separator_index+1:]
|
| 64 |
+
|
| 65 |
+
# Clean the first part of any commas, periods, or whitespace
|
| 66 |
+
before_separator_cleaned = re.sub(r'[.,\s]', '', before_separator)
|
| 67 |
+
|
| 68 |
+
# Ensure the decimal part starts with a period, even if it was a comma
|
| 69 |
+
standardized_s = before_separator_cleaned + '.' + after_separator
|
| 70 |
+
else:
|
| 71 |
+
# If there's no separator, just remove commas, periods, or whitespace
|
| 72 |
+
standardized_s = re.sub(r'[.,\s]', '', s)
|
| 73 |
+
|
| 74 |
+
return standardized_s
|
| 75 |
+
|
| 76 |
+
def remove_chars_after_last_digit(s):
|
| 77 |
+
# Remove any non-digit characters following the last digit in the string
|
| 78 |
+
return re.sub(r'(?<=\d)[^\d]*$', '', s)
|
| 79 |
+
|
| 80 |
+
def clean_text(s):
|
| 81 |
+
# This pattern looks for:
|
| 82 |
+
# - Optional non-digit or non-negative sign characters followed by whitespace (if any)
|
| 83 |
+
# - Followed by any characters until a digit is found in the word
|
| 84 |
+
# It then replaces this matched portion with the remaining part of the word from the first digit
|
| 85 |
+
# cleaned_s = re.sub(r'\S*?\s*?(\S*\d\S*)', r'\1', s)
|
| 86 |
+
cleaned_s = re.sub(r'[^\d-]*\s?(\S*\d\S*)', r'\1', s)
|
| 87 |
+
return cleaned_s
|
| 88 |
+
|
| 89 |
+
def format_text_decimal(text_decimal):
|
| 90 |
+
# Run functions to format a text decimal
|
| 91 |
+
return clean_text(remove_chars_after_last_digit(standardize_number(text_decimal.strip().lower())))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# PDF handling
|
| 95 |
+
def extract_text_using_pdfplumber(file_path):
|
| 96 |
+
# TODO: add check for text vs images padf
|
| 97 |
+
with pdfplumber.open(file_path) as pdf:
|
| 98 |
+
extracted_text = ''
|
| 99 |
+
for i, page in enumerate(pdf.pages):
|
| 100 |
+
# Remove duplicate characters from the page.
|
| 101 |
+
deduped_page = page.dedupe_chars(tolerance=1)
|
| 102 |
+
extracted_text += deduped_page.extract_text()
|
| 103 |
+
return extracted_text
|
| 104 |
+
|
| 105 |
+
def get_PDF_examples(directory):
|
| 106 |
+
example_pdf_files = []
|
| 107 |
+
for filename in os.listdir(directory):
|
| 108 |
+
if filename.endswith('.pdf'):
|
| 109 |
+
example_pdf_files.append(os.path.join(directory, filename))
|
| 110 |
+
return example_pdf_files
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Signatures and Models
|
| 114 |
+
class FindInvoiceNumberColumns(dspy.Signature):
|
| 115 |
+
"""Given an input remittance letter, return a list of column header names that may contain invoice numbers."""
|
| 116 |
+
content = dspy.InputField(desc="remittance letter", format=lambda s:s) # s:s so it doesn't skip the new lines
|
| 117 |
+
column_header_names = dspy.OutputField(desc="comma-separated list of column header names that may contain "\
|
| 118 |
+
"invoice numbers")
|
| 119 |
+
|
| 120 |
+
class InvoiceColumnHeaders(dspy.Module):
|
| 121 |
+
def __init__(self):
|
| 122 |
+
super().__init__()
|
| 123 |
+
|
| 124 |
+
# self.potential_invoice_column_headers = dspy.ChainOfThought(FindInvoiceNumberColumns)
|
| 125 |
+
self.potential_invoice_column_headers = dspy.Predict(FindInvoiceNumberColumns) # Ervin suggests Predict
|
| 126 |
+
|
| 127 |
+
def forward(self, file_content):
|
| 128 |
+
prediction = self.potential_invoice_column_headers(content=file_content)
|
| 129 |
+
# NOTE: Instead of a prediction we could return a simple list (for consistency with my other Modules)
|
| 130 |
+
# or even a parsed list (not CSV)
|
| 131 |
+
return prediction
|
| 132 |
+
|
| 133 |
+
# This creates a new Prediction object adding the File Content
|
| 134 |
+
# return Prediction(content=file_content, column_header_names=prediction.column_header_names, rationale=prediction.rationale)
|
| 135 |
+
# Creating a new Prediction object with extra data can be useful if we need more data for the verification
|
| 136 |
+
|
| 137 |
+
class FindInvoiceList(dspy.Signature):
|
| 138 |
+
"""Given an input remittance letter and a column header name output a comma-separated list of all invoice numbers """\
|
| 139 |
+
"""that belong to that column."""
|
| 140 |
+
content = dspy.InputField(desc="remittance letter", format=lambda s:s) # s:s so it doesn't skip the new lines
|
| 141 |
+
invoice_column_header = dspy.InputField(desc="invoice column header name")
|
| 142 |
+
candidate_invoice_numbers = dspy.OutputField(desc="comma-separated list of invoice numbers")
|
| 143 |
+
|
| 144 |
+
class InvoiceList(dspy.Module):
|
| 145 |
+
def __init__(self):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.find_invoice_headers = InvoiceColumnHeaders() # here we could load a compiled program also
|
| 148 |
+
self.find_invoice_numbers = dspy.Predict(FindInvoiceList)
|
| 149 |
+
|
| 150 |
+
def forward(self, file_content):
|
| 151 |
+
# Predict column headers (returns a Prediction with a CSV string in "column_header_names")
|
| 152 |
+
predict_column_headers = self.find_invoice_headers(file_content=file_content)
|
| 153 |
+
# Parse CSV into a list
|
| 154 |
+
potential_invoice_column_headers = parse_CSV_string(predict_column_headers.column_header_names)
|
| 155 |
+
|
| 156 |
+
potential_invoices = []
|
| 157 |
+
|
| 158 |
+
for header in potential_invoice_column_headers:
|
| 159 |
+
prediction = self.find_invoice_numbers(content=file_content, invoice_column_header=header)
|
| 160 |
+
potential_invoices.append(prediction.candidate_invoice_numbers)
|
| 161 |
+
|
| 162 |
+
# Remove duplicates
|
| 163 |
+
# potential_invoices = list(set(potential_invoices))
|
| 164 |
+
potential_invoices = parse_list_of_CSV_strings(potential_invoices) # TODO: remove duplicated lists
|
| 165 |
+
# return Prediction(candidate_invoice_numbers=candidates, column_header_names=col_names)
|
| 166 |
+
# return potential_invoices
|
| 167 |
+
# We need to return a Prediction for the Evaluate function later on
|
| 168 |
+
return Prediction(candidate_invoice_numbers=potential_invoices)
|
| 169 |
+
|
| 170 |
+
class FindTotalAmountColumns(dspy.Signature):
|
| 171 |
+
"""Given an input remittance letter, return a list of column header names that may contain the total payment amount."""
|
| 172 |
+
content = dspy.InputField(desc="remittance letter", format=lambda s:s) # s:s so it doesn't skip the new lines
|
| 173 |
+
total_column_header_names = dspy.OutputField(desc="comma-separated list of column header names that may contain "\
|
| 174 |
+
"the remittance letter total payment amount")
|
| 175 |
+
|
| 176 |
+
class TotalAmountColumnHeaders(dspy.Module):
|
| 177 |
+
def __init__(self):
|
| 178 |
+
super().__init__()
|
| 179 |
+
self.potential_total_amount_column_headers = dspy.Predict(FindTotalAmountColumns)
|
| 180 |
+
|
| 181 |
+
def forward(self, file_content):
|
| 182 |
+
prediction = self.potential_total_amount_column_headers(content=file_content)
|
| 183 |
+
return prediction
|
| 184 |
+
|
| 185 |
+
class FindTotalAmount(dspy.Signature):
|
| 186 |
+
"""Given an input remittance letter and a column header name output the total payment amount """\
|
| 187 |
+
"""that belongs to that column."""
|
| 188 |
+
content = dspy.InputField(desc="remittance letter", format=lambda s:s) # s:s so it doesn't skip the new lines
|
| 189 |
+
total_amount_column_header = dspy.InputField(desc="total amount header name")
|
| 190 |
+
total_amount = dspy.OutputField(desc="total payment amount")
|
| 191 |
+
|
| 192 |
+
class RemittanceLetterTotalAmount(dspy.Module):
|
| 193 |
+
def __init__(self):
|
| 194 |
+
super().__init__()
|
| 195 |
+
# self.find_invoice_list = InvoiceList()
|
| 196 |
+
self.find_total_amount_header = TotalAmountColumnHeaders()
|
| 197 |
+
self.find_total_amount = dspy.Predict(FindTotalAmount)
|
| 198 |
+
|
| 199 |
+
def forward(self, file_content):
|
| 200 |
+
# Predict invoice list - we could do this here, but let's just call the 2 modules from a function instead
|
| 201 |
+
# if we called the invoice list prediction here, we should return an object with both the potential total amounts
|
| 202 |
+
# and the potential invoice lists
|
| 203 |
+
# predict_invoice_list = self.find_invoice_list(file_content=file_content)
|
| 204 |
+
|
| 205 |
+
# Predict column headers (returns a Prediction with a CSV string in "column_header_names")
|
| 206 |
+
predict_column_headers = self.find_total_amount_header(file_content=file_content)
|
| 207 |
+
# Parse CSV into a list
|
| 208 |
+
potential_total_amount_column_headers = parse_CSV_string(predict_column_headers.total_column_header_names)
|
| 209 |
+
|
| 210 |
+
potential_total_amounts = []
|
| 211 |
+
|
| 212 |
+
for header in potential_total_amount_column_headers:
|
| 213 |
+
prediction = self.find_total_amount(content=file_content, total_amount_column_header=header)
|
| 214 |
+
potential_total_amounts.append(prediction.total_amount)
|
| 215 |
+
|
| 216 |
+
# Remove duplicates
|
| 217 |
+
potential_total_amounts = list(set(potential_total_amounts))
|
| 218 |
+
return Prediction(candidate_total_amounts=potential_total_amounts) # I could just return "prediction" also (references to candidate_total_amounts should change then)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# Pipeline
|
| 222 |
+
def poc_production_pipeline_without_verification(file_content):
|
| 223 |
+
# TODO: place this in a module - init allows to pass a compiled module and forward handles the data:
|
| 224 |
+
# so we can evaluate the pipeline (check if any tuple matches the verifier)
|
| 225 |
+
|
| 226 |
+
# Get invoice candidates
|
| 227 |
+
invoice_list_baseline = InvoiceList()
|
| 228 |
+
candidate_invoices = invoice_list_baseline(file_content=file_content).candidate_invoice_numbers
|
| 229 |
+
|
| 230 |
+
# Get total amount candidates
|
| 231 |
+
total_amount_baseline = RemittanceLetterTotalAmount()
|
| 232 |
+
|
| 233 |
+
# Format all decimals
|
| 234 |
+
candidate_total_amounts = list(map(format_text_decimal,
|
| 235 |
+
total_amount_baseline(file_content=file_content).candidate_total_amounts))
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# For UI visualisation purposes, create a list of tuples where the second tuple value is empty
|
| 239 |
+
candidate_invoices_for_UI = []
|
| 240 |
+
candidate_total_amounts_for_UI = []
|
| 241 |
+
|
| 242 |
+
for candidate in candidate_invoices:
|
| 243 |
+
candidate_invoices_for_UI.append((candidate,))
|
| 244 |
+
|
| 245 |
+
for candidate in candidate_total_amounts:
|
| 246 |
+
candidate_total_amounts_for_UI.append((candidate,))
|
| 247 |
+
|
| 248 |
+
return candidate_invoices_for_UI, candidate_total_amounts_for_UI
|
| 249 |
+
|
| 250 |
+
def poc_production_pipeline_without_verification_from_PDF(file_path):
|
| 251 |
+
file_content = extract_text_using_pdfplumber(file_path)
|
| 252 |
+
# return str(poc_production_pipeline_without_verification(file_content))
|
| 253 |
+
return poc_production_pipeline_without_verification(file_content)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# Main app
|
| 257 |
+
fake_PDF_examples = get_PDF_examples(pdf_examples_dir)
|
| 258 |
+
|
| 259 |
+
remittance_letter_demo_without_verification_from_PDF = gr.Interface(
|
| 260 |
+
poc_production_pipeline_without_verification_from_PDF,
|
| 261 |
+
[PDF(label="Remittance letter", height=1000)],
|
| 262 |
+
[
|
| 263 |
+
gr.Dataframe(col_count=(1, 'fixed'), label="", headers=["Candidate invoices"], wrap=True),
|
| 264 |
+
gr.Dataframe(col_count=(1, 'fixed'), label="", headers=["Candidate total amounts"], wrap=True)
|
| 265 |
+
],
|
| 266 |
+
examples=fake_PDF_examples,
|
| 267 |
+
allow_flagging='never'
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
remittance_letter_demo_without_verification_from_PDF.launch(debug=True)
|