This commit is contained in:
2026-07-12 12:30:20 -05:00
parent 888c5c1543
commit 0989c06b8f
23 changed files with 3324 additions and 119 deletions

View File

@@ -2,6 +2,7 @@ import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.js';
import * as fs from 'fs';
export interface BuyerSheetData {
file_name: string; // NEU
is_buyer_sheet: boolean;
name_company: string | null;
prospective_buyer: string | null;
@@ -21,8 +22,8 @@ export interface BuyerSheetData {
date_of_introduction: string | null;
_checkbox_pending: boolean;
_parser: string;
_info_page: number;
_ca_page: number;
_info_page: number | null;
_ca_page: number | null;
}
const LABELS = [
@@ -34,16 +35,69 @@ const LABELS = [
export class DeterministicParser {
public async parsePdf(filePath: string): Promise<BuyerSheetData> {
public async parsePdf(filePath: string, fileName: string): Promise<BuyerSheetData | null> {
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();
// Regel: Alles über 10 Seiten wird radikal ignoriert
if (pdfDocument.numPages > 10) {
return null;
}
// 1. Textfragmente mit X, Y und Breite (Width) auslesen
const mappedItems = textContent.items
let infoPageNum: number | null = null;
let caPageNum: number | null = null;
let infoPageObj: any = null;
let infoPageTextContent: any = null;
// ==========================================
// 1. Dynamische Seitensuche (Visuell sortiert & kugelsicher)
// ==========================================
for (let i = 1; i <= pdfDocument.numPages; i++) {
const page = await pdfDocument.getPage(i);
const textContent = await page.getTextContent();
// Elemente mit Koordinaten versehen und wie ein Mensch lesen (von oben nach unten, links nach rechts)
const sortedItems = textContent.items
.map((item: any) => ({
text: item.str,
x: item.transform[4],
y: item.transform[5]
}))
.sort((a: any, b: any) => {
// Y-Toleranz für Buchstaben auf derselben Zeile
if (Math.abs(b.y - a.y) > 5) {
return b.y - a.y;
}
return a.x - b.x;
});
// Wir werfen ALLE Leerzeichen, Striche, Punkte und unsichtbare Artefakte weg.
// Übrig bleibt eine reine, unverwüstliche Buchstabenkette.
const textRaw = sortedItems.map((i: any) => i.text).join('').toUpperCase().replace(/[^A-Z]/g, '');
// Anker-Suche in der sauberen Zeichenkette
if (textRaw.includes('BUYERINFORMATIONSHEET')) {
infoPageNum = i;
infoPageObj = page;
infoPageTextContent = textContent;
}
if (textRaw.includes('PROSPECTIVEBUYERAGREESTOKEEPANDHOLDCONFIDENTIAL')) {
caPageNum = i;
}
}
// ==========================================
// 2. Fallback für Bild/Scan PDFs
// ==========================================
if (!infoPageNum || !infoPageObj || !infoPageTextContent) {
return this.createEmptyFallback(fileName, filePath, infoPageNum, caPageNum);
}
// ==========================================
// 3. Werte-Extraktion (nur auf der Info-Seite!)
// ==========================================
const mappedItems = infoPageTextContent.items
.filter((item: any) => item.str.trim() !== '')
.map((item: any) => ({
text: item.str,
@@ -51,9 +105,8 @@ export class DeterministicParser {
y: item.transform[5],
width: item.width
}))
.sort((a, b) => b.y - a.y || a.x - b.x); // Y absteigend (oben nach unten)
.sort((a: any, b: any) => b.y - a.y || a.x - b.x);
// 2. Zeilen bilden (Y-Toleranz)
const linesGrouped: { y: number, items: any[] }[] = [];
let currentY: number | null = null;
let currentItems = [];
@@ -72,7 +125,6 @@ export class DeterministicParser {
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);
@@ -82,10 +134,7 @@ export class DeterministicParser {
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 += " ";
}
if (gap > 4) lineStr += " ";
}
lineStr += item.text;
prevEnd = item.x + item.width;
@@ -93,18 +142,13 @@ export class DeterministicParser {
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;
@@ -118,75 +162,87 @@ export class DeterministicParser {
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);
}
const val = parts.slice(1).join(':').replace(/_+/g, '').trim();
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);
const visualCheckboxResult = await this.detectGraphicCheckbox(infoPageObj, mappedItems);
return this.mapToTargetStructure(rawResults, filePath, fileName, visualCheckboxResult, infoPageNum, caPageNum);
}
private createEmptyFallback(fileName: string, filePath: string, infoPage: number | null, caPage: number | null): BuyerSheetData {
let dateOfIntro = null;
const dateMatch = filePath.match(/(\d{2})(\d{2})(\d{2})\.pdf$/);
if (dateMatch) dateOfIntro = `20${dateMatch[3]}-${dateMatch[1]}-${dateMatch[2]}`;
return {
file_name: fileName,
is_buyer_sheet: false,
name_company: null,
prospective_buyer: null,
company: null,
phone: null,
cell: null,
email: null,
address: null,
state: null,
how_did_you_hear: null,
interested_in_updates: null,
types_of_business_raw: null,
background_experience: null,
total_purchase_price: null,
down_payment: null,
down_payment_raw: null,
date_of_introduction: dateOfIntro,
_checkbox_pending: true,
_parser: "deterministic", // Signal für den AI-Pass
_info_page: infoPage,
_ca_page: caPage
};
}
private mapToTargetStructure(
raw: Record<string, string[]>,
filePath: string,
visualCheckboxResult: boolean | null // <-- Neuer Parameter
fileName: string,
visualCheckboxResult: boolean | null,
infoPageNum: number | null,
caPageNum: number | null
): 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;
let phoneClean = null;
let cellClean = 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;
@@ -195,30 +251,21 @@ export class DeterministicParser {
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]}`;
}
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
file_name: fileName,
is_buyer_sheet: true,
name_company: nameCompany,
prospective_buyer: nameCompany ? nameCompany.split('/')[0].trim() : null,
company: null,
@@ -237,31 +284,25 @@ export class DeterministicParser {
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
_info_page: infoPageNum,
_ca_page: caPageNum
};
}
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 (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];
@@ -269,10 +310,7 @@ export class DeterministicParser {
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
if (fn === pdfjsLib.OPS.transform) currentTransform = args;
else if (
fn === pdfjsLib.OPS.paintImageXObject ||
fn === pdfjsLib.OPS.paintInlineImageXObject ||
@@ -283,25 +321,13 @@ export class DeterministicParser {
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;
}
}
if (width < 40 && height < 40 && Math.abs(imgY - targetY) < 50) {
const distToYes = Math.abs(imgX - yesX);
const distToNo = Math.abs(imgX - noX);
return distToYes < distToNo;
}
}
}
return null;
}
}
}