This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
Zaimki/server/routes/pronounce.js

72 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-11-28 07:52:48 -08:00
import { Router } from 'express';
import { loadTsv } from '../loader';
import {buildPronoun, parsePronouns} from "../../src/buildPronoun";
import {Example} from "../../src/classes";
import sha1 from 'sha1';
import {handleErrorAsync} from "../../src/helpers";
2020-11-28 07:52:48 -08:00
import awsConfig from '../aws';
import Polly from 'aws-sdk/clients/polly';
import S3 from 'aws-sdk/clients/s3';
const router = Router();
router.get('/pronounce/:voice/:pronoun*', handleErrorAsync(async (req, res) => {
2020-11-28 07:52:48 -08:00
const pronounString = req.params.pronoun + req.params[0];
const pronoun = buildPronoun(
parsePronouns(loadTsv('pronouns/pronouns')),
pronounString,
);
if (!pronoun || !req.query.example) {
return res.status(404).json({error: 'Not found'});
}
let [singular, plural, isHonorific] = req.query.example.split('|');
const example = new Example(
Example.parse(singular),
Example.parse(plural || singular),
2020-12-17 01:41:40 -08:00
!!parseInt(isHonorific || '0'),
2020-11-28 07:52:48 -08:00
)
const text = example.pronounce(pronoun);
if (!text || text.length > 256) {
return res.status(404).json({error: 'Not found'});
}
const voice = global.config.pronunciation.voices[req.params.voice];
if (!voice) {
return res.status(404).json({error: 'Not found'});
}
2020-11-28 07:52:48 -08:00
const s3 = new S3(awsConfig);
const polly = new Polly(awsConfig);
const key = `pronunciation/${global.config.locale}-${req.params.voice}/${pronounString}/${sha1(text)}.mp3`;
2020-11-28 07:52:48 -08:00
try {
const s3getResponse = await s3.getObject({Key: key}).promise();
return res.set('content-type', s3getResponse.ContentType).send(s3getResponse.Body);
} catch {
const pollyResponse = await polly.synthesizeSpeech({
TextType: 'ssml',
Text: text,
OutputFormat: 'mp3',
LanguageCode: voice.language,
VoiceId: voice.voice,
Engine: voice.engine,
2020-11-28 07:52:48 -08:00
}).promise();
const s3putResponse = await s3.putObject({
Key: key,
Body: pollyResponse.AudioStream,
ContentType: pollyResponse.ContentType,
}).promise();
return res.set('content-type', pollyResponse.ContentType).send(pollyResponse.AudioStream);
}
}));
2020-11-28 07:52:48 -08:00
export default router;