import JamAI from "jamaibase";
import * as fs from "fs";
import * as path from "path";
class ReceiptProcessor {
private client: JamAI;
constructor(projectId: string, pat: string) {
this.client = new JamAI({
projectId: projectId,
token: pat,
});
}
validateImage(imagePath: string): boolean {
if (!fs.existsSync(imagePath)) {
throw new Error(`Image not found: ${imagePath}`);
}
const validExtensions = [".jpg", ".jpeg", ".png"];
const fileExt = path.extname(imagePath).toLowerCase();
if (!validExtensions.includes(fileExt)) {
throw new Error(
`Unsupported file format. Use: ${validExtensions.join(", ")}`
);
}
return true;
}
async processReceipt(
imagePath: string
): Promise<{ shopName: string; total: string } | null> {
try {
this.validateImage(imagePath);
console.log(`Processing receipt: ${imagePath}`);
console.log("Uploading image...");
const fileResponse = await this.client.file.uploadFile({
file_path: imagePath,
});
console.log("Upload successful!");
console.log("Extracting information...");
const response = await this.client.table.addRow({
table_type: "action",
table_id: "receipt",
data: [{ Image: fileResponse.uri }],
concurrent: false,
});
const results = {
shopName: String(
response.rows[0]?.columns["Shop Name"]?.choices[0]?.message
?.content ?? ""
),
total: String(
response.rows[0]?.columns["Total"]?.choices[0]?.message?.content ?? ""
),
};
return results;
} catch (error) {
console.error(`Error: ${error}`);
return null;
}
}
}
async function processFolder(
folderPath: string,
processor: ReceiptProcessor
): Promise<void> {
// Process all receipts in a folder
if (!fs.existsSync(folderPath)) {
console.log(`Folder not found: ${folderPath}`);
return;
}
const results = [];
const files = fs.readdirSync(folderPath);
for (const filename of files) {
if (filename.toLowerCase().match(/\.(jpg|jpeg|png)$/)) {
const imagePath = path.join(folderPath, filename);
const result = await processor.processReceipt(imagePath);
if (result) {
results.push({
filename: filename,
...result,
});
}
}
}
console.log("\n=== Processing Results ===");
for (const result of results) {
console.log(`\nFile: ${result.filename}`);
console.log(`Shop Name: ${result.shopName}`);
console.log(`Total: ${result.total}`);
}
}
// Main execution
async function main() {
// Get credentials from environment variables
const PROJECT_ID = process.env.JAMAI_PROJECT_ID || "your_project_id";
const PAT = process.env.JAMAI_API_KEY || "your_PAT";
const processor = new ReceiptProcessor(PROJECT_ID, PAT);
// Process a single receipt
const singleResult = await processor.processReceipt("path/to/receipt.jpg");
if (singleResult) {
console.log("\nSingle Receipt Result:");
console.log(`Shop Name: ${singleResult.shopName}`);
console.log(`Total: ${singleResult.total}`);
}
// Or process a folder of receipts
// await processFolder("path/to/receipt/folder", processor);
}
main().catch(console.error);