Files
ai-bayarea/BuyerSheetParser.ts
2026-07-11 17:08:41 -05:00

308 lines
12 KiB
TypeScript

import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.js';
import * as fs from 'fs';
export interface BuyerSheetData {
is_buyer_sheet: boolean;
name_company: string | null;
prospective_buyer: string | null;
company: string | null;
phone: string | null;
cell: string | null;
email: string | null;
address: string | null;
state: string | null;
how_did_you_hear: string | null;
interested_in_updates: boolean | null;
types_of_business_raw: string | null;
background_experience: string | null;
total_purchase_price: string | null;
down_payment: string | null;
down_payment_raw: string | null;
date_of_introduction: string | null;
_checkbox_pending: boolean;
_parser: string;
_info_page: number;
_ca_page: number;
}
const LABELS = [
"NAME / COMPANY", "PHONE", "ADDRESS", "EMAIL ADDRESS",
"HOW DID YOU HEAR", "ARE YOU INTERESTED", "TYPES OF BUSINESSES",
"BACKGROUND", "TOTAL PURCHASE PRICE", "DOWN PAYMENT",
"INCOME REQUIREMENTS", "ACCOUNTANT", "ATTORNEY", "BANK",
];
export class DeterministicParser {
public async parsePdf(filePath: string): Promise<BuyerSheetData> {
const dataBuffer = fs.readFileSync(filePath);
const loadingTask = pdfjsLib.getDocument({ data: new Uint8Array(dataBuffer) });
const pdfDocument = await loadingTask.promise;
const page = await pdfDocument.getPage(1);
const textContent = await page.getTextContent();
// 1. Textfragmente mit X, Y und Breite (Width) auslesen
const mappedItems = textContent.items
.filter((item: any) => item.str.trim() !== '')
.map((item: any) => ({
text: item.str,
x: item.transform[4],
y: item.transform[5],
width: item.width
}))
.sort((a, b) => b.y - a.y || a.x - b.x); // Y absteigend (oben nach unten)
// 2. Zeilen bilden (Y-Toleranz)
const linesGrouped: { y: number, items: any[] }[] = [];
let currentY: number | null = null;
let currentItems = [];
for (const item of mappedItems) {
if (currentY === null || Math.abs(item.y - currentY) <= 3) {
currentItems.push(item);
currentY = currentY === null ? item.y : currentY;
} else {
linesGrouped.push({ y: currentY, items: currentItems });
currentItems = [item];
currentY = item.y;
}
}
if (currentItems.length > 0 && currentY !== null) {
linesGrouped.push({ y: currentY, items: currentItems });
}
// 3. Zerrissene Wörter reparieren (Kerning)
const lines: { y: number, text: string }[] = [];
for (const group of linesGrouped) {
group.items.sort((a, b) => a.x - b.x);
let lineStr = "";
let prevEnd = -1;
for (const item of group.items) {
if (prevEnd !== -1) {
const gap = item.x - prevEnd;
// Wenn die Lücke größer als ~4 Pixel ist, ist es ein echtes Leerzeichen
if (gap > 4) {
lineStr += " ";
}
}
lineStr += item.text;
prevEnd = item.x + item.width;
}
lines.push({ y: group.y, text: lineStr });
}
// 4. Y-Intervall Parsing (Die "Nutzer-Idee")
const rawResults: Record<string, string[]> = {};
LABELS.forEach(lbl => rawResults[lbl] = []);
let currentLabel: string | null = null;
// Längste Labels zuerst suchen, damit "EMAIL ADDRESS" vor "ADDRESS" gefunden wird
const sortedLabels = [...LABELS].sort((a, b) => b.length - a.length);
for (const line of lines) {
const textUpper = line.text.toUpperCase().replace(/\s+/g, '');
// Boilerplate ignorieren, der Labels enthält ("VERIFICATION OF DOWN PAYMENT")
if (textUpper.includes("SELLERMAYREQUIREVERIFICATION")) continue;
let foundLabel: string | null = null;
for (const lbl of sortedLabels) {
const lblClean = lbl.toUpperCase().replace(/\s+/g, '');
if (textUpper.includes(lblClean)) {
foundLabel = lbl;
break;
}
}
if (foundLabel) {
currentLabel = foundLabel;
// Falls der Wert direkt auf derselben Zeile steht (z.B. "NAME/COMPANY: Gunnar Schultz")
if (line.text.includes(':')) {
const parts = line.text.split(':');
const val = parts.slice(1).join(':').replace(/_+/g, '').trim(); // Unterstriche entfernen
if (val.length > 0) {
rawResults[currentLabel].push(val);
}
}
} else if (currentLabel) {
// Diese Zeile ist kein Label, gehört also zum aktuellen Bereich!
const cleanVal = line.text.replace(/_+/g, '').trim();
// Footer und Artefakte ignorieren
if (cleanVal.length > 0 && !cleanVal.includes("Doc ID") && !cleanVal.includes("Bizmatch")) {
rawResults[currentLabel].push(cleanVal);
}
}
}
// --- NEU: Visuelle Checkbox Erkennung ---
const visualCheckboxResult = await this.detectGraphicCheckbox(page, mappedItems);
return this.mapToTargetStructure(rawResults, filePath, visualCheckboxResult);
}
private mapToTargetStructure(
raw: Record<string, string[]>,
filePath: string,
visualCheckboxResult: boolean | null // <-- Neuer Parameter
): BuyerSheetData {
const getVal = (label: string) => raw[label] && raw[label].length > 0 ? raw[label].join(' ') : null;
const nameCompany = getVal("NAME / COMPANY");
// ==========================================
// 1. Telefon & Handy (Cell) separieren
// ==========================================
let phoneRaw = getVal("PHONE");
let phoneClean: string | null = null;
let cellClean: string | null = null;
if (phoneRaw) {
// Alles vor "FAX:" oder "CELL:" ist die Telefonnummer
const phoneMatch = phoneRaw.split(/FAX:|CELL:/)[0];
phoneClean = phoneMatch ? phoneMatch.trim() : null;
// Alles nach "CELL:" ist die Handynummer
const cellMatch = phoneRaw.match(/CELL:\s*(.*)/);
cellClean = cellMatch && cellMatch[1] ? cellMatch[1].trim() : null;
}
// ==========================================
// 2. Adresse bereinigen
// ==========================================
let addressClean = getVal("ADDRESS");
if (addressClean) {
// Den statischen Formulart-Subtext entfernen
addressClean = addressClean.replace(/PO BOX \/ STREET\s+CITY \/ STATE \/ ZIP/g, '').trim();
if (addressClean === '') addressClean = null;
}
// ==========================================
// 3. Checkbox Auswertung (Hybrid)
// ==========================================
const interestedRaw = getVal("ARE YOU INTERESTED");
let interestedInUpdates: boolean | null = null;
let checkboxPending = true;
if (interestedRaw) {
// 1. Zuerst Text-Prüfung versuchen (wie vorher)
if (/(✔|☑|X|✓)\s*YES/i.test(interestedRaw) || /YES\s*(✔|☑|X|✓)/i.test(interestedRaw)) {
interestedInUpdates = true;
checkboxPending = false;
} else if (/(✔|☑|X|✓)\s*NO/i.test(interestedRaw) || /NO\s*(✔|☑|X|✓)/i.test(interestedRaw)) {
interestedInUpdates = false;
checkboxPending = false;
}
}
// 2. Wenn Text-Prüfung versagt hat, nutzen wir unser visuelles X-Koordinaten Ergebnis!
if (checkboxPending && visualCheckboxResult !== null) {
interestedInUpdates = visualCheckboxResult;
checkboxPending = false;
}
// ==========================================
// 4. Down Payment & Datum
// ==========================================
const downPaymentRaw = getVal("DOWN PAYMENT")?.replace(/[^0-9,]/g, '') || null;
const downPaymentClean = downPaymentRaw ? downPaymentRaw.replace(/,/g, '') : null;
let dateOfIntro = null;
const dateMatch = filePath.match(/(\d{2})(\d{2})(\d{2})\.pdf$/);
if (dateMatch) {
dateOfIntro = `20${dateMatch[3]}-${dateMatch[1]}-${dateMatch[2]}`;
}
// ==========================================
// 5. JSON Return mit dynamischen Flags
// ==========================================
return {
is_buyer_sheet: true, // Wird in der Praxis dynamisch gesetzt
name_company: nameCompany,
prospective_buyer: nameCompany ? nameCompany.split('/')[0].trim() : null,
company: null,
phone: phoneClean,
cell: cellClean,
email: getVal("EMAIL ADDRESS"),
address: addressClean,
state: null,
how_did_you_hear: getVal("HOW DID YOU HEAR"),
interested_in_updates: interestedInUpdates,
types_of_business_raw: getVal("TYPES OF BUSINESSES"),
background_experience: getVal("BACKGROUND"),
total_purchase_price: getVal("TOTAL PURCHASE PRICE"),
down_payment: downPaymentClean,
down_payment_raw: downPaymentRaw,
date_of_introduction: dateOfIntro,
_checkbox_pending: checkboxPending,
_parser: "deterministic",
_info_page: 1, // Wird in der Praxis über eine Schleife ermittelt
_ca_page: 2 // Wird in der Praxis über eine Schleife ermittelt
};
}
private async detectGraphicCheckbox(page: any, textItems: any[]): Promise<boolean | null> {
let yesX = null, noX = null, targetY = null;
// 1. Koordinaten von YES und NO suchen
for (const item of textItems) {
const textUpper = item.text.toUpperCase().trim();
if (textUpper.includes("YES")) { yesX = item.x; targetY = item.y; }
}
for (const item of textItems) {
const textUpper = item.text.toUpperCase().trim();
// Wir suchen NO auf derselben Höhe (Toleranz 5px)
if (textUpper.includes("NO") && targetY !== null && Math.abs(item.y - targetY) < 5) {
noX = item.x;
}
}
if (yesX === null || noX === null || targetY === null) return null;
// ==========================================
// BILD-ERKENNUNG (Der 16x16 Stempel-Trick)
// ==========================================
const opList = await page.getOperatorList();
let currentTransform = [1, 0, 0, 1, 0, 0];
for (let i = 0; i < opList.fnArray.length; i++) {
const fn = opList.fnArray[i];
const args = opList.argsArray[i];
if (fn === pdfjsLib.OPS.transform) {
currentTransform = args;
}
// Wenn ein Bild auf die Seite gezeichnet wird
else if (
fn === pdfjsLib.OPS.paintImageXObject ||
fn === pdfjsLib.OPS.paintInlineImageXObject ||
fn === pdfjsLib.OPS.paintJpegXObject
) {
const width = Math.abs(currentTransform[0]);
const height = Math.abs(currentTransform[3]);
const imgX = currentTransform[4];
const imgY = currentTransform[5];
// Wir filtern nach "Stempeln" (kleine Bilder unter 40x40 Pixeln)
if (width < 40 && height < 40) {
// Befindet sich der Stempel auf unserer Ziel-Zeile?
// (Wir erlauben 50px Toleranz, da Y=378 vs Y=417)
if (Math.abs(imgY - targetY) < 50) {
const distToYes = Math.abs(imgX - yesX);
const distToNo = Math.abs(imgX - noX);
// Wenn das Bildchen näher an YES ist
if (distToYes < distToNo) {
return true;
} else {
return false;
}
}
}
}
}
return null;
}
}