/
DanLisow
/
Audio2Text
Обзор
Документация
Войти
/
DanLisow
/
Audio2Text
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
controller/audioController.js
131 строка
4 KB
DanLisow
first-commit
14 фев 2025, 00:13
14 фев 2025, 00:13
5bc9159
Код
Авторство
О чём код?
const axios = require("axios"); const { exec } = require("child_process"); const fs = require("fs"); const path = require("path"); const ffmpeg = require("fluent-ffmpeg"); const util = require("util"); const asyncExec = util.promisify(exec); /** * URL media-сервиса, откуда скачиваем аудио. */ const FTP_SERVER_URL = process.env.MEDIA_FILE_URL; /** * URL, куда отправляем результат транскрипции в media-сервис. */ const MEDIA_TRANSCRIPTION_CALLBACK = process.env.MEDIA_FILE_SEND_URL; /** * Путь к временной папке для сохранения файлов */ const tempDir = path.join(__dirname, "..", "temp"); /** * Скачиваем аудиофайл по URL и сохраняет в outputPath */ async function downloadAudioFile(fileUrl, outputPath) { console.log(`Запрашиваем аудиофайл по URL: ${fileUrl}`); try { const response = await axios.get(fileUrl, { responseType: "arraybuffer" }); fs.writeFileSync(outputPath, response.data); console.log(`Аудиофайл сохранён: ${outputPath}`); } catch (error) { throw new Error(`Произошла ошибка: ${error}`); } } /** * Конвертируем OGG в WAV */ function convertToWav(inputPath, outputPath) { return new Promise((resolve, reject) => { ffmpeg(inputPath) .toFormat("wav") .on("error", (err) => { reject(new Error("Ошибка конвертации аудио: " + err.message)); }) .on("end", () => { console.log(`Конвертация в WAV завершена: ${outputPath}`); resolve(); }) .save(outputPath); }); } /** * Запускаем Python-скрипт transcribe.py для распознавания речи из WAV-файла */ async function runTranscriberScript(wavPath) { const command = `python3 transcribe.py "${wavPath}"`; try { const { stdout } = await asyncExec(command); return stdout.trim(); } catch (err) { throw new Error("Ошибка выполнения Python-скрипта: " + err.message); } } /** * Удаляем список временных файлов */ function cleanupFiles(...files) { for (const file of files) { if (fs.existsSync(file)) { fs.unlinkSync(file); } } } /** * Основной обработчик POST /audio/transcribe */ const transcribeHandler = async (req, res) => { const { id } = req.body; if (!id) { return res.status(400).json({ error: "ID не существует" }); } if (!fs.existsSync(tempDir)) { fs.mkdirSync(tempDir, { recursive: true }); } const audioFilePath = path.join(tempDir, `${id}.ogg`); const wavFilePath = path.join(tempDir, `${id}.wav`); const fileUrl = `${FTP_SERVER_URL}/${id}`; try { await downloadAudioFile(fileUrl, audioFilePath); await convertToWav(audioFilePath, wavFilePath); const transcription = await runTranscriberScript(wavFilePath); console.log("Результат транскрипции:", transcription); if (MEDIA_TRANSCRIPTION_CALLBACK) { console.log(`Отправляем результат в media-сервис: ${MEDIA_TRANSCRIPTION_CALLBACK}`); await axios.post(MEDIA_TRANSCRIPTION_CALLBACK, { id, transcription }); } else { throw new Error("Не задан MEDIA_TRANSCRIPTION_CALLBACK"); } res.json({ message: "Аудио-файл успешно обработан", transcription, }); } catch (error) { console.error("Ошибка во время обработки аудио:", error.message); res.status(500).json({ error: error.message }); } finally { cleanupFiles(audioFilePath, wavFilePath); } }; module.exports = transcribeHandler;