Skip to content

Commit

Permalink
feat: detect the input language to improve the experience
Browse files Browse the repository at this point in the history
  • Loading branch information
DreamOfIce committed Aug 3, 2023
1 parent 8e17b06 commit 2353234
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 24 deletions.
6 changes: 4 additions & 2 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,7 @@ parserOptions:
plugins:
- "@typescript-eslint"
rules:
"@typescript-eslint/no-namespace": off
"@typescript-eslint/require-await": off
"@typescript-eslint/no-namespace":
off
# "@typescript-eslint/require-await": off
"@typescript-eslint/no-non-null-assertion": off
20 changes: 11 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
"ts-node": "npm:@dreamofice/ts-node@^10.9.2"
},
"dependencies": {
"@koishijs/translator": "^1.1.0"
"@koishijs/translator": "^1.1.0",
"fasttext.wasm": "^1.0.1"
},
"devDependencies": {
"@commitlint/cli": "^17.6.6",
Expand All @@ -57,23 +58,24 @@
"@typescript-eslint/eslint-plugin": "^5.61.0",
"@typescript-eslint/parser": "^5.61.0",
"dotenv-cli": "^7.2.1",
"eslint": "^8.43.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-import": "^2.27.5",
"eslint": "^8.46.0",
"eslint-config-prettier": "^8.10.0",
"eslint-plugin-import": "^2.28.0",
"husky": "^8.0.3",
"koishi": "^4.13.6",
"koishi": "^4.14.0",
"nano-staged": "^0.8.0",
"pinst": "^3.0.0",
"prettier": "^2.8.8",
"prettier-plugin-packagejson": "^2.4.3",
"release-it": "^15.11.0",
"tsup": "^7.1.0",
"prettier": "^3.0.1",
"prettier-plugin-packagejson": "^2.4.5",
"release-it": "^16.1.3",
"tsup": "^7.2.0",
"typescript": "^5.1.6"
},
"peerDependencies": {
"koishi": "^4.13.6"
},
"koishi": {
"browser": true,
"description": {
"en": "Deepl translation",
"zh": "使用 Deepl 翻译"
Expand Down
31 changes: 25 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,41 @@
import Translator from "@koishijs/translator";
import { FastText } from "fasttext.wasm";
import { Context, Logger, Schema, SessionError } from "koishi";
import type { Response } from "./types";
import { defineLocales, generateRequestBody } from "./utils";

const logger = new Logger("translator-deepl");

class DeeplTranslator extends Translator<DeeplTranslator.Config> {
private id = Math.random() * 2 ** 32;
private fastText?: FastText;

public constructor(ctx: Context, config: DeeplTranslator.Config) {
super(ctx, config);
defineLocales(ctx);
}

public async translate(options: Translator.Result): Promise<string> {
const { input, source, target = "ZH" } = options;
if (!this.fastText) {
this.fastText = await FastText.create();
await this.fastText.loadModel();
}
const {
input,
source,
target = this.fastText.detect(input).toUpperCase() ===
this.config.defaultTargetLang[0]!
? this.config.defaultTargetLang[1]!
: this.config.defaultTargetLang[0]!,
} = options;
const { data, status } = await this.ctx.http.axios<Response>("/jsonrpc", {
method: "post",
baseURL: "https://www2.deepl.com",
data: generateRequestBody(
this.id++,
input,
target.toUpperCase(),
source?.toUpperCase()
source?.toUpperCase(),
),
headers: {
Accept: "*/*",
Expand Down Expand Up @@ -52,7 +66,7 @@ class DeeplTranslator extends Translator<DeeplTranslator.Config> {
data.error
? `: ${data.error?.message}(${data.error?.code})`
: ""
}`
}`,
);
throw new SessionError(".deepl.unknownError");
}
Expand All @@ -67,10 +81,15 @@ class DeeplTranslator extends Translator<DeeplTranslator.Config> {
}

namespace DeeplTranslator {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface Config {}
export interface Config {
defaultTargetLang: string[];
}

export const Config: Schema<Config> = Schema.object({});
export const Config: Schema<Config> = Schema.object({
defaultTargetLang: Schema.tuple([String, String])
.description("默认的目标语言, 当输入语言为第一个时使用第二个")
.default(["ZH", "EN"]),
});
}

export default DeeplTranslator;
2 changes: 1 addition & 1 deletion src/types/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export interface Response {
{
alternatives: string[];
text: string;
}
},
];
lang: string;
lang_is_confident: boolean;
Expand Down
12 changes: 6 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@ import type { Context, I18n } from "koishi";
import * as locales from "./locales";
import type { Request } from "./types";

export const defineLocales = (ctx: Context) =>
Object.entries(locales).forEach(([lang, locale]) =>
ctx.i18n.define(lang, locale as unknown as I18n.Store)
);

const getTimestamp = (str: string) => {
const timestamp = new Date().getUTCMilliseconds();
const iCount = [...str].filter((c) => c === "i").length;
Expand All @@ -22,11 +17,16 @@ const stringifyRequest = (req: Request) => {
: json;
};

export const defineLocales = (ctx: Context) =>
Object.entries(locales).forEach(([lang, locale]) =>
ctx.i18n.define(lang, locale as unknown as I18n.Store),
);

export const generateRequestBody = (
id: number,
text: string,
targetLang: string,
sourceLang?: string
sourceLang?: string,
): string =>
stringifyRequest({
jsonrpc: "2.0",
Expand Down

0 comments on commit 2353234

Please sign in to comment.