Skip to content

🎉一个简单的翻译库,支持多翻译引擎。A simple translation library that supports multiple translation engines

License

Notifications You must be signed in to change notification settings

yxw007/translate

Repository files navigation

Translate

English | 简体中文

GitHub top language GitHub License NPM Version Codecov GitHub Actions Workflow Status

❓ Why do I need translate?

  1. a lot of translation tool libraries on the market, basically not very well-maintained
  2. not written by ts, not friendly enough when using the prompts
  3. single function, does not support batch translation Or only support a translation engine
  4. ...

Note: Translate helps you to solve all the above problems, and will expand more in the future!

✨ Features

  • 🌐 Multi-environment support: Node environment, browser environment
  • Easy to use: provides a concise API, you can easily help you to translate
  • 🌍 Multi-translation engine support: Google, Azure Translate, etc. (will expand more in the future)
  • 🛠️ typescript: friendlier code hints and quality assurance
  • 📦 Batch translation: one api request, translate more content, reduce http requests to improve translation efficiency
  • 🔓 completely open source.

🚀 Install

  • npm

    npm install @yxw007/translate
  • yarn

    yarn add @yxw007/translate
  • pnpm

    pnpm i @yxw007/translate

📖 Usage

Node

  • ESM

    import { translator, engines } from "@yxw007/translate"
  • Commonjs

    const { translator, engines }  = required("@yxw007/translate")
  • example

    translator.use(engines.google());
    const res1 = await translator.translate("hello", { from: "en", to: "zh" });
    console.log(res1);
    
    const res2 = await translator.translate(["hello", "good"], { from: "en", to: "zh", engine: "google" });
    console.log(res2);

    输出结果

    ['你好']
    ["你好", "好的"]

Browser

use jsDelivr CDN

  • development

    <script src="https://cdn.jsdelivr.net/npm/@yxw007/translate@0.0.7/dist/browser/index.umd.js"></script>
  • production

    <script src="https://cdn.jsdelivr.net/npm/@yxw007/translate@0.0.7/dist/browser/index.umd.min.js"></script>
  • example

    <!DOCTYPE html>
    ...
    
    <head>
      ...
      <script src="https://cdn.jsdelivr.net/npm/@yxw007/translate@0.0.7/dist/browser/index.umd.js"></script>
    </head>
    
    <body>
      <script>
        (async () => {
          const { engines, translator } = translate;
          translator.use(engines.google());
          const res = await translator.translate("hello", { from: "en", to: "zh" });
          console.log(res);
        })();
      </script>
    </body>
    
    </html>

📚 API

Translator

class Translator {
  private engines: Map<string, Engine>;
  constructor() {
    this.engines = new Map<string, Engine>();
  }
  use(engine: Engine) {
   ...
  }
  translate(text: string | string[], options: TranslateOptions) {
    ...
  }
}

use

Add a translation engine to transitorion engine to translator

type Engine = {
  name: string;
  translate: (text: string | string[], opts: EngineTranslateOptions) => Promise<string[]>;
};

translate

You can pass a text or pass a text array, which will return a translated Promise<string[]>

translate(text: string | string[], options: TranslateOptions)

TranslateOptions

export interface TranslateOptions {
  from: Language;
  to: Language;
  engine?: Engines;
   /**
   * Cache time in milliseconds
   */
  cache_time?: number;
  domain?: string;
}

Each translation of Engine's Option

BaseEngineOption

interface BaseEngineOption {}

AzureEngineOption

interface AzureEngineOption extends BaseEngineOption {
  key: string;
  region: string;
}

Note: Option Param, please get it from the corresponding platform

AmazonEngineOption

interface AmazonEngineOption extends BaseEngineOption{
  region: string;
  accessKeyId: string;
  secretAccessKey: string;
}

Note: Option Param, please get it from the corresponding platform

BaiduEngineOption

export interface BaiduEngineOption extends BaseEngineOption {
  appId: string;
  secretKey: string;
}

Note: Option Param, please get it from the corresponding platform

DeeplEngineOption

export interface DeeplEngineOption {
  key: string;
}

Note: Option Param, please get it from the corresponding platform

🤝 Contribute

Special attention: Please create a new branch based on the master, develop on the new branch, and create PR to Master after development.

  • Installation dependence

    pnpm install
  • Add new Engine

    • Add a new platform ENGINE plugin

      export interface XXEngineOption extends BaseEngineOption {
        key: string;
      }
      
      export function xx(options: XXEngineOption): Engine {
        const { key } = options;
        const base = "https://translate.yandex.net/api/v1.5/tr.json/translate";
        return {
          name: "yandex",
          async translate(text: string | string[], opts: EngineTranslateOptions): Promise<string[]> {
            const { from, to } = opts;
            if (!Array.isArray(text)) {
              text = [text];
            }
            //TODO: Call the platform translation APIplatform translation API
            const translations: string[] = [];
            //TODO: Analyze the corresponding results of the platform API, and resolve the results to the translations back
            for (const translation of body.text) {
              if (translation) {
                translations.push(translation);
              }
            }
            return translations;
          },
        };
      }
    • Add the plugin to Engines(Location:/src/engines/index.ts)

      import { xx } from "./xx";
      export const engines = {
        google,
        azure,
        amazon,
        baidu,
        deepl,
        xx
      } as const;
  • Build

    pnpm build
  • Test

    pnpm test

Tips: At present, the library can be used normally. Welcome everyone to experience. If you have any questions and suggestions, you can mention the feedback to me.If you are interested, you are welcome to join, let us improve this tool together. Help to click star ⭐, let more people know this tool, thank you for everyone🙏

🌹 Thanks

Note:Thanks to franciscop/translate for giving me ideas for a quick implementation of this library, and also indirectly some of his code. Much appreciated.🙏

📄 License

Translate is released under the MIT license. See the LICENSE file.