this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add multiple translation instances as fallbacks with retries

+39 -17
+39 -17
src/components/translation-block.jsx
··· 1 1 import './translation-block.css'; 2 2 3 + import pRetry from 'p-retry'; 3 4 import pThrottle from 'p-throttle'; 4 5 import { useEffect, useRef, useState } from 'preact/hooks'; 5 6 ··· 15 16 interval: 2000, 16 17 }); 17 18 19 + // Using other API instances instead of lingva.ml because of this bug (slashes don't work): 20 + // https://github.com/thedaviddelta/lingva-translate/issues/68 21 + const LINGVA_INSTANCES = [ 22 + 'lingva.garudalinux.org', 23 + 'lingva.lunar.icu', 24 + 'translate.plausibility.cloud', 25 + ]; 26 + let currentLingvaInstance = 0; 27 + 18 28 function lingvaTranslate(text, source, target) { 19 29 console.log('TRANSLATE', text, source, target); 20 - // Using another API instance instead of lingva.ml because of this bug (slashes don't work): 21 - // https://github.com/thedaviddelta/lingva-translate/issues/68 22 - return fetch( 23 - `https://lingva.garudalinux.org/api/v1/${source}/${target}/${encodeURIComponent( 24 - text, 25 - )}`, 26 - ) 27 - .then((res) => res.json()) 28 - .then((res) => { 29 - return { 30 - provider: 'lingva', 31 - content: res.translation, 32 - detectedSourceLanguage: res.info?.detectedSource, 33 - info: res.info, 34 - }; 35 - }); 30 + const fetchCall = () => { 31 + let instance = LINGVA_INSTANCES[currentLingvaInstance]; 32 + return fetch( 33 + `https://${instance}/api/v1/${source}/${target}/${encodeURIComponent( 34 + text, 35 + )}`, 36 + ) 37 + .then((res) => res.json()) 38 + .then((res) => { 39 + return { 40 + provider: 'lingva', 41 + content: res.translation, 42 + detectedSourceLanguage: res.info?.detectedSource, 43 + info: res.info, 44 + }; 45 + }); 46 + }; 47 + return pRetry(fetchCall, { 48 + retries: 3, 49 + onFailedAttempt: (e) => { 50 + currentLingvaInstance = 51 + (currentLingvaInstance + 1) % LINGVA_INSTANCES.length; 52 + console.log( 53 + 'Retrying translation with another instance', 54 + currentLingvaInstance, 55 + ); 56 + }, 57 + }); 36 58 // return masto.v1.statuses.translate(id, { 37 59 // lang: DEFAULT_LANG, 38 60 // }); ··· 66 88 const translate = async () => { 67 89 setUIState('loading'); 68 90 try { 69 - const { content, detectedSourceLanguage, provider, ...props } = 91 + const { content, detectedSourceLanguage, provider, error, ...props } = 70 92 await onTranslate(text, apiSourceLang.current, targetLang); 71 93 if (content) { 72 94 if (detectedSourceLanguage) {