trace.ai-cli
Version:
A powerful AI-powered CLI tool
63 lines (55 loc) • 2.17 kB
JavaScript
const fs = require('fs').promises;
const fetch = require('node-fetch');
const { encryptData, decryptData } = require('../utils/encryption');
const { getMimeType } = require('../utils/fileUtils');
// Mode selection helper (matches aiService pattern)
function getMode(mode) {
switch (Number(mode)) {
case 1: return 'fast';
case 2: return 'balance';
case 3: return 'think';
default: return 'balance';
}
}
async function convertImageToBase64(imagePath) {
try {
const imageBuffer = await fs.readFile(imagePath);
const base64 = imageBuffer.toString('base64');
const mimeType = getMimeType(imagePath);
return { base64, mimeType };
} catch (error) {
throw new Error(`Failed to read image: ${error.message}`);
}
}
async function extractTextFromImage(imagePath, question = '', mode = 2) {
try {
const { base64, mimeType } = await convertImageToBase64(imagePath);
const selectedMode = getMode(mode);
const prompt = question
? `Analyze this image and answer the following question: ${question}`
: 'Extract and return only the text from this image. Format it naturally. If the image contains no text, describe the image content in detail.';
const response = await fetch('https://traceai.dukeindustries7.workers.dev/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: encryptData({
a: selectedMode,
q: prompt,
r: [],
i: [{ inlineData: { data: base64, mimeType } }],
c: ''
})
});
if (!response.ok) {
throw new Error(`API returned HTTP ${response.status}`);
}
const encryptedResult = await response.text();
const decryptedResult = decryptData(encryptedResult);
return decryptedResult.text || 'Unable to analyze image - the API returned an empty result';
} catch (error) {
console.error('❌ Error analyzing image:', error.message);
throw error;
}
}
module.exports = {
extractTextFromImage
};