-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirect-pdf-analysis.js
More file actions
129 lines (109 loc) Β· 3.67 KB
/
Copy pathdirect-pdf-analysis.js
File metadata and controls
129 lines (109 loc) Β· 3.67 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
import fs from 'fs/promises';
import { spawn } from 'child_process';
class DirectPDFAnalyzer {
constructor() {
this.apiKey = process.env.GEMINI_API_KEY;
this.apiUrl = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent';
}
async extractTextDirect(pdfPath) {
return new Promise((resolve, reject) => {
const python = spawn('python', ['-c', `
import pdfplumber
import sys
try:
with pdfplumber.open('${pdfPath}') as pdf:
text = ""
for page in pdf.pages:
try:
page_text = page.extract_text()
if page_text:
text += page_text + "\\n"
except:
continue
print(text)
except Exception as e:
print(f"Error: {e}")
`]);
let output = '';
let error = '';
python.stdout.on('data', (data) => {
output += data.toString();
});
python.stderr.on('data', (data) => {
error += data.toString();
});
python.on('close', (code) => {
if (code === 0 && output.trim()) {
resolve(output.trim());
} else {
reject(new Error(error || 'No text extracted'));
}
});
});
}
async analyzeWithAI(extractedText) {
const prompt = `Analyze this bank statement text and provide comprehensive analysis:
${extractedText}
Return ONLY valid JSON:
{
"accountOverview": {
"accountHolder": "string",
"accountNumber": "string",
"bank": "string",
"statementPeriod": "string",
"currency": "string",
"openingBalance": 0,
"totalInflows": 0,
"totalOutflows": 0,
"closingBalance": 0,
"netFlow": 0,
"totalTurnover": 0
},
"insights": {
"keyFindings": ["string"],
"recommendations": ["string"]
},
"riskAssessment": {
"overallRiskLevel": "Low"
}
}`;
const response = await fetch(`${this.apiUrl}?key=${this.apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: { temperature: 0.1, maxOutputTokens: 4096 }
})
});
const result = await response.json();
const text = result.candidates[0].content.parts[0].text;
const jsonMatch = text.match(/\{[\s\S]*\}/);
return JSON.parse(jsonMatch[0]);
}
async processStatement(pdfPath) {
console.log('π Direct PDF Analysis Starting...');
try {
console.log('π Extracting text...');
const extractedText = await this.extractTextDirect(pdfPath);
console.log(`β
Extracted ${extractedText.length} characters`);
console.log('π€ Analyzing with AI...');
const analysis = await this.analyzeWithAI(extractedText);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const reportId = `direct-${timestamp}`;
await fs.writeFile(`reports/${reportId}.json`, JSON.stringify(analysis, null, 2));
console.log('\nπ DIRECT ANALYSIS COMPLETE');
console.log(`Account: ${analysis.accountOverview.accountHolder}`);
console.log(`Bank: ${analysis.accountOverview.bank}`);
console.log(`Opening: β¦${analysis.accountOverview.openingBalance.toLocaleString()}`);
console.log(`Closing: β¦${analysis.accountOverview.closingBalance.toLocaleString()}`);
console.log(`Risk: ${analysis.riskAssessment.overallRiskLevel}`);
console.log(`\nβ
Report: reports/${reportId}.json`);
return analysis;
} catch (error) {
console.error('β Error:', error.message);
throw error;
}
}
}
const analyzer = new DirectPDFAnalyzer();
analyzer.processStatement('Account_Statement_8234.pdf');