trace.ai-cli
Version:
A powerful AI-powered CLI tool
136 lines (114 loc) • 4.83 kB
JavaScript
const path = require('path');
const fs = require('fs').promises;
const pdfParse = require('pdf-parse');
const { getFileType, readFileContent } = require('../utils/fileUtils');
const { processWithAI } = require('./aiService');
const { extractTextFromImage } = require('./imageService');
async function analyzeFile(filePath, query = '', mode = 2) {
try {
const fileType = getFileType(filePath);
// Handle images - use vision API only for images
if (fileType === 'image') {
const result = await extractTextFromImage(filePath, query, mode);
return { text: result };
}
// Handle documents (PDFs, Word, etc.)
if (fileType === 'document') {
const fileName = path.basename(filePath);
const ext = path.extname(filePath).toLowerCase();
// Extract text from PDF
if (ext === '.pdf') {
try {
const dataBuffer = await fs.readFile(filePath);
const pdfData = await pdfParse(dataBuffer);
const content = pdfData.text;
if (!content || content.trim().length === 0) {
return {
text: `❌ **Unable to Extract Text from PDF**\n\n` +
`The PDF "${fileName}" appears to be empty or contains only images/scanned content.\n\n` +
`**Try using the /image command for scanned PDFs:**\n` +
`\`/image "${filePath}" ${query || 'analyze this document'}\``
};
}
// Build prompt for AI analysis
let prompt;
if (query) {
prompt = `PDF Document: ${fileName}
Content:
\`\`\`
${content}
\`\`\`
User Question: ${query}`;
} else {
prompt = `Analyze this PDF document (${fileName}):
\`\`\`
${content}
\`\`\`
Please provide a comprehensive summary and analysis of the document.`;
}
const result = await processWithAI(prompt, '', mode);
return { text: result || 'No response generated' };
} catch (pdfError) {
return {
text: `❌ **Error Reading PDF**\n\n` +
`Failed to extract text from "${fileName}": ${pdfError.message}\n\n` +
`**Possible reasons:**\n` +
`- The PDF is corrupted or password-protected\n` +
`- The PDF contains only images (scanned document)\n\n` +
`**Try using /image command for scanned PDFs:**\n` +
`\`/image "${filePath}" ${query || 'analyze this document'}\``
};
}
}
// For other document types (Word, Excel, etc.)
return {
text: `❌ **Document Type Not Supported**\n\n` +
`The file "${fileName}" is a ${ext.toUpperCase()} document.\n\n` +
`**Supported formats:**\n` +
`- PDF files (.pdf) - Text extraction supported\n` +
`- Text files (.txt, .md, etc.)\n` +
`- Code files (.js, .py, .java, etc.)\n\n` +
`**For ${ext.toUpperCase()} files:**\n` +
`Please convert to PDF or text format first.`
};
}
// Handle text-based files
const content = await readFileContent(filePath);
const fileName = path.basename(filePath);
let prompt;
if (query) {
prompt = `File: ${fileName} (${fileType})
Content:
\`\`\`
${content}
\`\`\`
User Question: ${query}`;
} else {
if (fileType !== 'Unknown' && fileType !== 'Text' && fileType !== 'Markdown') {
prompt = `Analyze this ${fileType} code file (${fileName}):
\`\`\`
${content}
\`\`\`
Please provide:
1. Code overview and purpose
2. Key functions/components
3. Potential issues or improvements
4. Code quality assessment
5. Suggestions for optimization`;
} else {
prompt = `Analyze this file content (${fileName}):
\`\`\`
${content}
\`\`\`
Please provide a summary and analysis of the content.`;
}
}
const result = await processWithAI(prompt, '', mode);
return { text: result || 'No response generated' };
} catch (error) {
throw error;
}
}
module.exports = {
analyzeFile
};