UNPKG

mtengines

Version:

Machine Translation (MT) library written in TypeScript

175 lines 6.74 kB
/******************************************************************************* * Copyright (c) 2023-2026 Maxprograms. * * This program and the accompanying materials * are made available under the terms of the Eclipse License 1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/epl-v10.html * * Contributors: * Maxprograms - initial API and implementation *******************************************************************************/ import Anthropic from '@anthropic-ai/sdk'; import { MTMatch } from "./MTMatch.js"; import { MTUtils } from "./MTUtils.js"; export class AnthropicTranslator { model; anthropic; srcLang = ''; tgtLang = ''; constructor(apiKey, model) { if (model) { this.model = model; } this.anthropic = new Anthropic({ apiKey: apiKey }); } getName() { return 'Anthropic Claude'; } setModel(model) { this.model = model; } getShortName() { return 'Anthropic'; } getSourceLanguages() { return MTUtils.getLanguages(); } getTargetLanguages() { return MTUtils.getLanguages(); } setSourceLanguage(lang) { this.srcLang = lang; } getSourceLanguage() { return this.srcLang; } setTargetLanguage(lang) { this.tgtLang = lang; } getTargetLanguage() { return this.tgtLang; } translate(source) { if (this.srcLang === '' || this.tgtLang === '') { return Promise.reject(new Error('Source and Target languages must be set before translation.')); } let prompt = MTUtils.getRole(this.srcLang, this.tgtLang) + ' ' + MTUtils.translatePropmt(source, this.srcLang, this.tgtLang); return new Promise((resolve, reject) => { this.createMessage(prompt).then((message) => { let jsonString = JSON.stringify(message, null, 2); let jsonObject = JSON.parse(jsonString); let translation = jsonObject.content[0].text.trim(); if (translation.startsWith('"""') && translation.endsWith('"""')) { translation = translation.substring(3, translation.length - 3).trim(); } resolve(translation); }).catch((error) => { reject(error); }); }); } getMTMatch(source, terms) { let prompt = MTUtils.getRole(this.srcLang, this.tgtLang) + ' ' + MTUtils.generatePrompt(source, this.srcLang, this.tgtLang, terms); return new Promise((resolve, reject) => { this.createMessage(prompt).then((message) => { let jsonString = JSON.stringify(message, null, 2); let jsonObject = JSON.parse(jsonString); let translation = jsonObject.content[0].text.trim(); if (translation.startsWith('```xml') && translation.endsWith('```')) { translation = translation.substring(6, translation.length - 3).trim(); } if (translation.startsWith('```') && translation.endsWith('```')) { translation = translation.substring(3, translation.length - 3).trim(); } let target = MTUtils.toXMLElement(translation); let space = source.getAttribute('xml:space'); if (space) { target.setAttribute(space); } resolve(new MTMatch(source, target, this.getShortName())); }).catch((error) => { reject(error); }); }); } async createMessage(source) { if (!this.model) { throw new Error('Model is not set.'); } return await this.anthropic.messages.create({ model: this.model, max_tokens: 1024, messages: [{ role: "user", content: source }], }); } handlesTags() { return true; } fixesMatches() { return true; } fixMatch(originalSource, matchSource, matchTarget) { let prompt = MTUtils.getRole(this.srcLang, this.tgtLang) + ' ' + MTUtils.fixMatchPrompt(originalSource, matchSource, matchTarget); return new Promise((resolve, reject) => { this.createMessage(prompt).then((message) => { let jsonString = JSON.stringify(message, null, 2); let jsonObject = JSON.parse(jsonString); let translation = jsonObject.content[0].text; let target = MTUtils.toXMLElement(translation); let space = originalSource.getAttribute('xml:space'); if (space) { target.setAttribute(space); } resolve(new MTMatch(originalSource, target, this.getShortName())); }).catch((error) => { reject(error); }); }); } fixesTags() { return true; } fixTags(source, target) { let prompt = MTUtils.getRole(this.srcLang, this.tgtLang) + ' ' + MTUtils.fixTagsPrompt(source, target, this.srcLang, this.tgtLang); return new Promise((resolve, reject) => { this.createMessage(prompt).then((message) => { let jsonString = JSON.stringify(message, null, 2); let jsonObject = JSON.parse(jsonString); let translation = jsonObject.content[0].text; let target = MTUtils.toXMLElement(translation); let space = source.getAttribute('xml:space'); if (space) { target.setAttribute(space); } resolve(target); }).catch((error) => { reject(error); }); }); } async getAvailableModels() { if (!this.anthropic.apiKey) { return Promise.reject(new Error('API key is not set.')); } try { const response = await fetch('https://api.anthropic.com/v1/models', { method: 'GET', headers: { 'x-api-key': this.anthropic.apiKey, 'anthropic-version': '2023-06-01' } }); if (!response.ok) { throw new Error('HTTP error! status: ' + response.status); } const data = await response.json(); return data.data.map((model) => [model.id, model.display_name]); } catch (error) { console.error('Error fetching available models:', error); throw error; } } } //# sourceMappingURL=AnthropicTranslator.js.map