import JamAI from "jamaibase";
import * as fs from "fs";
import * as path from "path";
class AudioProcessor {
private client: JamAI;
constructor(projectId: string, pat: string) {
this.client = new JamAI({
projectId: projectId,
token: pat,
});
}
validateAudio(audioPath: string): boolean {
if (!fs.existsSync(audioPath)) {
throw new Error(`Audio file not found: ${audioPath}`);
}
const validExtensions = [".mp3", ".wav"];
const fileExt = path.extname(audioPath).toLowerCase();
if (!validExtensions.includes(fileExt)) {
throw new Error(
`Unsupported file format. Use: ${validExtensions.join(", ")}`
);
}
return true;
}
async processAudio(
audioPath: string
): Promise<{ transcription: string; summary: string } | null> {
try {
this.validateAudio(audioPath);
console.log(`Processing audio: ${audioPath}`);
console.log("Uploading audio...");
const fileResponse = await this.client.file.uploadFile({
file_path: audioPath,
});
console.log("Upload successful!");
console.log("Extracting information...");
const response = await this.client.table.addRow({
table_type: "action",
table_id: "AudioProcessor",
data: [{ Audio: fileResponse.uri }],
concurrent: false,
});
const results = {
transcription: String(
response.rows[0]?.columns["Transcription"]?.choices[0]?.message
?.content ?? ""
),
summary: String(
response.rows[0]?.columns["Summary"]?.choices[0]?.message?.content ??
""
),
};
return results;
} catch (error) {
console.error(`Error: ${error}`);
return null;
}
}
}
async function processFolder(
folderPath: string,
processor: AudioProcessor
): Promise<void> {
// Process all audio files 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(/\.(mp3|wav)$/)) {
const audioPath = path.join(folderPath, filename);
const result = await processor.processAudio(audioPath);
if (result) {
results.push({
filename: filename,
...result,
});
}
}
}
console.log("\n=== Processing Results ===");
for (const result of results) {
console.log(`\nFile: ${result.filename}`);
console.log(`Transcription: ${result.transcription}`);
console.log(`Summary: ${result.summary}`);
}
}
// Main execution
async function main() {
// Get credentials from environment variables
const PROJECT_ID = "your_project_id";
const PAT = "your_PAT";
const processor = new AudioProcessor(PROJECT_ID, PAT);
// Process a single audio file
const singleResult = await processor.processAudio("path/to/audio.mp3");
if (singleResult) {
console.log("\nSingle Audio Result:");
console.log(`Transcription: ${singleResult.transcription}`);
console.log(`Summary: ${singleResult.summary}`);
}
// Or process a folder of audio files
// await processFolder("path/to/audio/folder", processor);
}
main().catch(console.error);