Skip to content

Instantly share code, notes, and snippets.

@gnh1201
Created October 27, 2023 09:46
Show Gist options
  • Save gnh1201/0ad4805b52d03c9b50a660a4d5df1877 to your computer and use it in GitHub Desktop.
Save gnh1201/0ad4805b52d03c9b50a660a4d5df1877 to your computer and use it in GitHub Desktop.
Cloudflare Workers code to integrate IBM Translator to Mastodon
/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run "npm run dev" in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run "npm run deploy" to publish your worker
*
* Learn more at https://developers.cloudflare.com/workers/
*/
// Namhyeon Go <[email protected], @[email protected]>
// 2023-10-27
const API_KEY = '';
const API_ENDPOINT_URL = '';
function get_languages() {
let langcodes = ["ko", "ja", "en", "es", "de", "pt", "ru", "zh"];
return [
{"code": "en", "name": "English", "targets": langcodes},
{"code": "ko", "name": "Korean", "targets": langcodes},
{"code": "ja", "name": "Japanese", "targets": langcodes},
{"code": "es", "name": "Spanish", "targets": langcodes},
{"code": "de", "name": "German", "targets": langcodes},
{"code": "pt", "name": "Portuguese", "targets": langcodes},
{"code": "ru", "name": "Russian", "targets": langcodes},
{"code": "zh", "name": "Chinese", "targets": langcodes}
];
}
function get_clean_text(s) {
// https://stackoverflow.com/questions/5002111/how-to-strip-html-tags-from-string-in-javascript
// https://stackoverflow.com/questions/10805125/how-to-remove-all-line-breaks-from-a-string
// https://stackoverflow.com/questions/23571013/how-to-remove-url-from-a-string-completely-in-javascript
return String(s)
.replace(/<\/?[^>]+(>|$)/g, '')
.replace(/(\r\n|\n|\r)/gm, '\n')
.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '')
.replace(/#/gi, '')
.trim();
;
}
async function get_translated_text(q, target, source = 'en') {
// 언어 코드 확인
let source_language = get_languages().reduce((a, x) => {
if (x.code == source) a = [x.code, x.name];
return a;
}, ['en', 'English']);
let target_language = get_languages().reduce((a, x) => {
if (x.code == target) a = [x.code, x.name];
return a;
}, ['ko', 'Korean']);
// 사용자 이름과 비밀번호
const username = 'apikey';
const password = API_KEY;
// Base64로 사용자 이름과 비밀번호 인코딩
const base64Credentials = btoa(`${username}:${password}`);
// 요청 옵션
const originalText = get_clean_text(q);
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${base64Credentials}` // Basic 인증 헤더 추가
},
body: JSON.stringify({
"text": [originalText],
"model_id": `${source_language[0]}-${target_language[0]}`
}) // JSON 데이터를 문자열로 변환하여 전송
};
console.log(originalText);
// API 엔드포인트
const apiUrl = API_ENDPOINT_URL + '/v3/translate?version=2018-05-01';
// Fetch API를 사용하여 POST 요청 보내기
const response = await fetch(apiUrl, requestOptions);
const result = await response.json();
console.log(JSON.stringify(result));
// 번역 결과 반환
return {
"translatedText": result.translations.reduce((a, x) => {
a.push(x.translation);
return a;
}, [])
}
}
export default {
async fetch(request, env, ctx) {
const { pathname } = new URL(request.url);
switch (pathname) {
case "/languages":
return Response.json(get_languages());
case "/translate":
if (request.method === "POST") {
try {
const { q, target, source } = JSON.parse(await request.text());
return Response.json(await get_translated_text(q, target, source));
} catch (e) {
return new Response(e.message, {status: 500});
}
} else {
return new Response("Not Allowed Method", {status: 405});
}
default:
return new Response("Not Allowed Method", {status: 405});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment