From 8e17117854ecfcc7a9042c321694049f2b2be300 Mon Sep 17 00:00:00 2001 From: Himickoff Date: Sat, 13 Jul 2024 19:13:08 +0700 Subject: [PATCH] Fix quartes Google translator, when translating direct speech, for some reason adds an additional quotation mark, which breaks the syntax 1.Before submitting text for translation, we replace all quotation marks with special markers (__OPEN_QUOTE__ and __CLOSE_QUOTE__). This ensures that quotes are not changed or deleted during translation. 2.Similarly, we replace asterisks with markers (__OPEN_STAR__ and __CLOSE_STAR__). 3.After receiving the translated text, we replace all markers back to the corresponding characters. --- src/endpoints/translate.js | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/endpoints/translate.js b/src/endpoints/translate.js index f0c699d92..a62f4e080 100644 --- a/src/endpoints/translate.js +++ b/src/endpoints/translate.js @@ -64,7 +64,7 @@ router.post('/libre', jsonParser, async (request, response) => { router.post('/google', jsonParser, async (request, response) => { try { const { generateRequestUrl, normaliseResponse } = require('google-translate-api-browser'); - const text = request.body.text; + let text = request.body.text; const lang = request.body.lang; if (!text || !lang) { @@ -73,6 +73,20 @@ router.post('/google', jsonParser, async (request, response) => { console.log('Input text: ' + text); + // Заменяем кавычки на специальные маркеры перед переводом + const openQuote = '__OPEN_QUOTE__'; + const closeQuote = '__CLOSE_QUOTE__'; + text = text.replace(/"/g, (match, offset) => { + return offset % 2 === 0 ? openQuote : closeQuote; + }); + + // Заменяем звездочки на специальные маркеры + const openStar = '__OPEN_STAR__'; + const closeStar = '__CLOSE_STAR__'; + text = text.replace(/\*/g, (match, offset) => { + return offset % 2 === 0 ? openStar : closeStar; + }); + const url = generateRequestUrl(text, { to: lang }); https.get(url, (resp) => { @@ -87,8 +101,12 @@ router.post('/google', jsonParser, async (request, response) => { const result = normaliseResponse(JSON.parse(data)); console.log('Translated text: ' + result.text); - // Заменяем кавычки «» на "" - const fixedText = result.text.replace(/«/g, '"').replace(/»/g, '"'); + // Восстанавливаем кавычки и звездочки после перевода + let fixedText = result.text + .replace(new RegExp(openQuote, 'g'), '"') + .replace(new RegExp(closeQuote, 'g'), '"') + .replace(new RegExp(openStar, 'g'), '*') + .replace(new RegExp(closeStar, 'g'), '*'); return response.send(fixedText); } catch (error) {