提交 ecb83c89 编写于 作者: a865501259's avatar a865501259

format: some code style

上级 0daa4eac
#!/usr/bin/env node
(async function () {
'use script';
process.on('uncaughtException', err => {
console.error('got an error: %s', err);
process.exitCode = 1;
});
const updateNotifier = require('update-notifier');
const whatTime = require('what-time');
const minimatch = require('minimatch');
const async = require('async');
const fs = require('fs');
const path = require('path');
const listMd = require('./src/util/readmd.js');
const meow = require('meow');
const mergeConfig = require('./src/config/mergeConfig.js');
const {g, y, yow, m, b, r, relaPath, insert_flg} = require('./src/util/util.js');
// Cli cmd
const cli = meow(`
"use script";
process.on("uncaughtException", (err) => {
console.error("got an error: %s", err);
process.exitCode = 1;
});
const updateNotifier = require("update-notifier");
const whatTime = require("what-time");
const minimatch = require("minimatch");
const async = require("async");
const fs = require("fs");
const path = require("path");
const listMd = require("./src/util/readmd.js");
const meow = require("meow");
const mergeConfig = require("./src/config/mergeConfig.js");
const {
g,
y,
yow,
m,
b,
r,
relaPath,
insert_flg,
} = require("./src/util/util.js");
// Cli cmd
const cli = meow(`
Usage
$ translateMds [folder/file name] [options]
Example
$ translateMds md/
${b('[options]')}
${g('-a API')} : default < baidu > ${y('{google|baidu|youdao}')}
${g('-f from ')} : default < auto detect >
${g('-t to ')} : default < zh >
${g('-N num ')} : default < 1 > ${y('{async number}')}
${g('-R rewrite')} : default < false > ${y('{yes/no rewrite translate file}')}
🌟${m('[high user options]')}❤️
${g('-D debug')}
${g('-C cache')} : default: false ${y('cache in disk')}
${g('-G google.com')} : default: false ${y('{ cn => com with Google api }')}
${g('-F force')} : default: false ${y('{ If, translate result is no 100%, force wirte md file }')}
${g('-M match')} : default [ ". ", "! "//...] ${y('{match this str, merge translate result }')}
${g('-S skips')} : default ["... ", "etc. ", "i.e. "] ${y('{match this str will, skip merge translate result }')}
${g('-T types')} : default ["html", "code"] ${y('{pass the md AST type}')}
${g('--timewait ')} : default < 80 > ${y('{each fetch api wait time}')}
${g('--values [path]')} : default: false ${y('{write the original of wait for translate file}')} ${r('[single file]')}
${g('--translate [path]')} : default: false ${y('{use this file translate}')} ${r('[single file]')}
${g('--text-glob [pattern]')} : default: false ${y('{text must be match, then be transalte}')}
${g('--no-disk')} : default: false ${y('{do not use cached Result}')}
${g('--cache-name [filename]')}: default: "translateMds" ${y('named the cache file')}
${g('--glob [pattern]')} : default: false ${y('{file must be match, then be transalte}')}
${g('--ignore [relative file/folder]')} : default: false ${y('{ignore files/folders string, split with `,` }')}
$ translateMds -T 'inlineCode,linkReference,link,heading' readme.md
${b("[options]")}
${g("-a API")} : default < baidu > ${y("{google|baidu|youdao}")}
${g("-f from ")} : default < auto detect >
${g("-t to ")} : default < zh >
${g("-N num ")} : default < 1 > ${y("{async number}")}
${g("-R rewrite")} : default < false > ${y(
"{yes/no rewrite translate file}"
)}
🌟${m("[high user options]")}❤️
${g("-D debug")}
${g("-C cache")} : default: false ${y("cache in disk")}
${g("-G google.com")} : default: false ${y(
"{ cn => com with Google api }"
)}
${g("-F force")} : default: false ${y(
"{ If, translate result is no 100%, force wirte md file }"
)}
${g("-M match")} : default [ ". ", "! "//...] ${y(
"{match this str, merge translate result }"
)}
${g("-S skips")} : default ["... ", "etc. ", "i.e. "] ${y(
"{match this str will, skip merge translate result }"
)}
${g("-T types")} : default ["html", "code"] ${y(
"{pass the md AST type}"
)}
${g("--timewait ")} : default < 80 > ${y(
"{each fetch api wait time}"
)}
${g("--values [path]")} : default: false ${y(
"{write the original of wait for translate file}"
)} ${r("[single file]")}
${g("--translate [path]")} : default: false ${y(
"{use this file translate}"
)} ${r("[single file]")}
${g("--text-glob [pattern]")} : default: false ${y(
"{text must be match, then be transalte}"
)}
${g("--no-disk")} : default: false ${y(
"{do not use cached Result}"
)}
${g("--cache-name [filename]")}: default: "translateMds" ${y(
"named the cache file"
)}
${g("--glob [pattern]")} : default: false ${y(
"{file must be match, then be transalte}"
)}
${g("--ignore [relative file/folder]")} : default: false ${y(
"{ignore files/folders string, split with `,` }"
)}
`);
updateNotifier({pkg: cli.pkg}).notify();
updateNotifier({ pkg: cli.pkg }).notify();
// Fix write file Path is absoulte
const dir = cli.input[0];
if (!dir) {
console.error(g('--> v' + cli.pkg.version), cli.help);
// Fix write file Path is absoulte
const dir = cli.input[0];
if (!dir) {
console.error(g("--> v" + cli.pkg.version), cli.help);
process.exit(1);
}
// Merge config
const {
debug,
tranFr,
tranTo,
api,
rewrite,
asyncNum,
Force,
ignores,
glob,
Cache
} = mergeConfig(cli);
const translateMds = require('./src/translateMds.js');
const {loggerStart, loggerText, loggerStop, oneOra} = require('./src/config/loggerConfig.js'); // Winston config
// after workOptions ready
const {writeDataToFile} = require('./src/util/writeDataToFile.js');
console.log(b(`> ${yow(`Cache:${Cache}`)} Starting 翻译`) + r(dir));
// Get floder markdown files Array
const getList = await listMd(path.resolve(process.cwd(), dir), {deep: 'all'});
console.log(b(`总文件数 ${getList.length}, 有些文件会跳过`));
let Done = 0;
const noDone = [];
let showAsyncnum = 0;
loggerStart('translate running ... >> ');
async.mapLimit(getList, asyncNum, runTranslate,
(err, IsTranslateS) => {
loggerStop();
if (noDone.length > 0) {
process.exitCode = 1;
}
if (err) {
throw err;
}
Done++;
if (IsTranslateS.every(x => Boolean(x))) {
oneOra('All Done');
} else {
if (debug !== 'debug') {
oneOra(`Some No Done , ${yow('use')} cli-option${r(' { -D } ')} find the Err`);
}
if (!Force) {
oneOra(`Or ${yow('use')} cli-option${r(' { -F } ')} Force put the translate Result`);
}
if (debug === 'debug' || Force) {
oneOra(`[${g('DEBUG')}:${debug === 'debug'}|${g('Force')}:${Force}] mode`);
}
}
oneOra(`time:${whatTime(process.uptime())}`);
}
);
/**
* @description async Translate filename value , Return true or false
* @param {String} value
* @returns {Boolean}
*/
async function runTranslate(value) {
const rePath = relaPath(value);
loggerText(`++++ <😊 > ${rePath}`);
let State = true;
Done++;
const localDone = Done;
// Filter same file
if (value.endsWith(`.${tranTo}.md`) || !value.endsWith('.md')) {
loggerText(b(`- 翻译的 - 或者 不是 md 文件的 ${g(rePath)}`));
return State;
}
if (value.match(/\.[a-zA-Z]{2}\.md+/)) { // TOGO country short name
loggerText(b(`- 有后缀为 *.国家简写.md ${g(rePath)}`));
return State;
}
if (!rewrite && fs.existsSync(insert_flg(value, `.${tranTo}`, 3))) {
loggerText(b(`已翻译, 不覆盖 ${g(rePath)}`));
return State;
}
if (glob && glob.some(g =>!minimatch(value, g, {matchBase: true})) ) {
loggerText(b(`glob, no match ${g(rePath)}`));
return State;
}
if (ignores && ignores.some(ignore => value.includes(path.resolve(ignore)))) {
loggerText(b(`ignore, ${g(rePath)}`));
return State;
}
loggerText(`1. do 第${localDone}文件 ${rePath}`);
// Open async num
showAsyncnum++;
const startTime = new Date().getTime();
const _translateMds = await translateMds([value, api, tranFr, tranTo], debug, true);
// Succeed / force wirte data
if (_translateMds.every(x => !x.error && x.text) || Force) { // Translate no ok
const _tranData = _translateMds.map(x => x.text); // Single file translate data
await writeDataToFile(_tranData, value).then(text => loggerText(text));
}
let Err;
for (const _t of _translateMds) {
if (_t.error) {
Err = _t.error;
break;
}
}
const endtime = new Date().getTime() - startTime;
const humanTime = whatTime(endtime / 1000);
if (State && !Err) {
oneOra(`已搞定 第 ${localDone} 文件 - 并发${b(showAsyncnum)} -- ${b(humanTime)} - ${rePath}`);
} else {
State = false; // Translate no ok
if (!State) { // Write data no ok | translate no ok
noDone.push(value); // If process exit code
oneOra(`没完成 第 ${localDone} 文件 - 并发${b(showAsyncnum)} -- ${b(humanTime)} - ${rePath} \n ${Err}`, 'fail');
}
}
showAsyncnum--;
return State;
}
process.on('exit', _ => {
loggerStop();
});
}
// Merge config
const {
debug,
tranFr,
tranTo,
api,
rewrite,
asyncNum,
Force,
ignores,
glob,
Cache,
} = mergeConfig(cli);
const translateMds = require("./src/translateMds.js");
const {
loggerStart,
loggerText,
loggerStop,
oneOra,
} = require("./src/config/loggerConfig.js"); // Winston config
// after workOptions ready
const { writeDataToFile } = require("./src/util/writeDataToFile.js");
console.log(b(`> ${yow(`Cache:${Cache}`)} Starting 翻译`) + r(dir));
// Get floder markdown files Array
const getList = await listMd(path.resolve(process.cwd(), dir), {
deep: "all",
});
console.log(b(`总文件数 ${getList.length}, 有些文件会跳过`));
let Done = 0;
const noDone = [];
let showAsyncnum = 0;
loggerStart("translate running ... >> ");
async.mapLimit(getList, asyncNum, runTranslate, (err, IsTranslateS) => {
loggerStop();
if (noDone.length > 0) {
process.exitCode = 1;
}
if (err) {
throw err;
}
Done++;
if (IsTranslateS.every((x) => Boolean(x))) {
oneOra("All Done");
} else {
if (debug !== "debug") {
oneOra(
`Some No Done , ${yow("use")} cli-option${r(" { -D } ")} find the Err`
);
}
if (!Force) {
oneOra(
`Or ${yow("use")} cli-option${r(
" { -F } "
)} Force put the translate Result`
);
}
if (debug === "debug" || Force) {
oneOra(
`[${g("DEBUG")}:${debug === "debug"}|${g("Force")}:${Force}] mode`
);
}
}
oneOra(`time:${whatTime(process.uptime())}`);
});
/**
* @description async Translate filename value , Return true or false
* @param {String} value
* @returns {Boolean}
*/
async function runTranslate(value) {
const rePath = relaPath(value);
loggerText(`++++ <😊 > ${rePath}`);
let State = true;
Done++;
const localDone = Done;
// Filter same file
if (value.endsWith(`.${tranTo}.md`) || !value.endsWith(".md")) {
loggerText(b(`- 翻译的 - 或者 不是 md 文件的 ${g(rePath)}`));
return State;
}
if (value.match(/\.[a-zA-Z]{2}\.md+/)) {
// TOGO country short name
loggerText(b(`- 有后缀为 *.国家简写.md ${g(rePath)}`));
return State;
}
if (!rewrite && fs.existsSync(insert_flg(value, `.${tranTo}`, 3))) {
loggerText(b(`已翻译, 不覆盖 ${g(rePath)}`));
return State;
}
if (glob && glob.some((g) => !minimatch(value, g, { matchBase: true }))) {
loggerText(b(`glob, no match ${g(rePath)}`));
return State;
}
if (
ignores &&
ignores.some((ignore) => value.includes(path.resolve(ignore)))
) {
loggerText(b(`ignore, ${g(rePath)}`));
return State;
}
loggerText(`1. do 第${localDone}文件 ${rePath}`);
// Open async num
showAsyncnum++;
const startTime = new Date().getTime();
const _translateMds = await translateMds(
[value, api, tranFr, tranTo],
debug,
true
);
// Succeed / force wirte data
if (_translateMds.every((x) => !x.error && x.text) || Force) {
// Translate no ok
const _tranData = _translateMds.map((x) => x.text); // Single file translate data
await writeDataToFile(_tranData, value).then((text) => loggerText(text));
}
let Err;
for (const _t of _translateMds) {
if (_t.error) {
Err = _t.error;
break;
}
}
const endtime = new Date().getTime() - startTime;
const humanTime = whatTime(endtime / 1000);
if (State && !Err) {
oneOra(
`已搞定 第 ${localDone} 文件 - 并发${b(showAsyncnum)} -- ${b(
humanTime
)} - ${rePath}`
);
} else {
State = false; // Translate no ok
if (!State) {
// Write data no ok | translate no ok
noDone.push(value); // If process exit code
oneOra(
`没完成 第 ${localDone} 文件 - 并发${b(showAsyncnum)} -- ${b(
humanTime
)} - ${rePath} \n ${Err}`,
"fail"
);
}
}
showAsyncnum--;
return State;
}
process.on("exit", (_) => {
loggerStop();
});
})();
此差异已折叠。
const tjs = require('translation.js-fix')
const tjs = require("translation.js-fix");
// log
const {logger, loggerStart, loggerText, oneOra } = require('./config/loggerConfig.js')
const {
logger,
loggerStart,
loggerText,
oneOra,
} = require("./config/loggerConfig.js");
// get config.json
const {getOptions} = require('./config/work-options.js')
const configs = getOptions()
let tranF = configs['from'],
tranT = configs['to'],
COM = configs['com'],
Force = configs['force']
timeWait = configs['timewait'],
getValuesFile = configs['getvalues'],
zhSymbal = configs['zh'],
gotTranslateFile = configs['translate'],
apis = configs['apis'];
const { getOptions } = require("./config/work-options.js");
const configs = getOptions();
let tranF = configs["from"],
tranT = configs["to"],
COM = configs["com"],
Force = configs["force"];
(timeWait = configs["timewait"]),
(getValuesFile = configs["getvalues"]),
(zhSymbal = configs["zh"]),
(gotTranslateFile = configs["translate"]),
(apis = configs["apis"]);
// Cache right result
let cache = configs['cache'];
let cacheName = configs['cacheName'];
let diskState = configs["disk"]
const {setDisk, getDisk} = require("./util/diskCache")(cacheName)
let cache = configs["cache"];
let cacheName = configs["cacheName"];
let diskState = configs["disk"];
const { setDisk, getDisk } = require("./util/diskCache")(cacheName);
// Fix china symbal
const fixZhtoEn = require("./Fix/fixZhtoEn.js")
const fixZhtoEn = require("./Fix/fixZhtoEn.js");
// Fix result.length no equal
const { translateLengthEquals } = require("./Fix/lengthEqual.js")
const { translateLengthEquals } = require("./Fix/lengthEqual.js");
// Fix Too Big Array to Chunk
const { fixFileTooBig, indexMergeArr } = require("./Fix/fixFileTooBig.js")
const {tc,time,g,y,yow,m,b,r,relaPath,newObject,asyncWrite,asyncRead} = require('./util/util.js')
const debugMsg = require("./util/debugMsg.js")
const MAXstring = 1300
const { fixFileTooBig, indexMergeArr } = require("./Fix/fixFileTooBig.js");
const {
tc,
time,
g,
y,
yow,
m,
b,
r,
relaPath,
newObject,
asyncWrite,
asyncRead,
} = require("./util/util.js");
const debugMsg = require("./util/debugMsg.js");
const MAXstring = 1300;
//
// get translate result
......@@ -47,67 +63,72 @@ const MAXstring = 1300
* @returns {String[]}
*/
async function translateValue(value, api) {
let thisTranString
if (value instanceof Array) {
thisTranString = value.join('\n')
} else {
thisTranString = value
}
await time(timeWait)
if (tranT === 'zh') tranT = 'zh-CN'
let tjsOpts = {
text: thisTranString,
to: tranT,
com: COM
}
if(tranF){
tjsOpts['from'] = tranF
}
return tjs[api].translate(tjsOpts).then(result => {
if (!result.result) {
throw new Error('「结果为空」')
}
if (value.length == result.result.length) {
return result.result
}
if (value.length > result.result.length) {
return translateValue(value.slice(result.result.length), api).then(youdao => {
// tjs translate youdao BUG and tjs baidu will return undefined
if (youdao) {
if (youdao instanceof Array) {
youdao.forEach(x => result.result.push(x))
} else {
result.result.push(youdao)
}
}
return result.result
}).catch(x =>{
if(api == "baidu"){
result.result = result.result.concat(value.slice(result.result.length))
}
return result.result
})
}
return result.result
}).catch(err => {
throw err
})
let thisTranString;
if (value instanceof Array) {
thisTranString = value.join("\n");
} else {
thisTranString = value;
}
await time(timeWait);
if (tranT === "zh") tranT = "zh-CN";
let tjsOpts = {
text: thisTranString,
to: tranT,
com: COM,
};
if (tranF) {
tjsOpts["from"] = tranF;
}
return tjs[api]
.translate(tjsOpts)
.then((result) => {
if (!result.result) {
throw new Error("「结果为空」");
}
if (value.length == result.result.length) {
return result.result;
}
if (value.length > result.result.length) {
return translateValue(value.slice(result.result.length), api)
.then((youdao) => {
// tjs translate youdao BUG and tjs baidu will return undefined
if (youdao) {
if (youdao instanceof Array) {
youdao.forEach((x) => result.result.push(x));
} else {
result.result.push(youdao);
}
}
return result.result;
})
.catch((x) => {
if (api == "baidu") {
result.result = result.result.concat(
value.slice(result.result.length)
);
}
return result.result;
});
}
return result.result;
})
.catch((err) => {
throw err;
});
}
const { getTypeValue, setTypeValue} = require('./typeSetAndGet')
const { getTypeValue, setTypeValue } = require("./typeSetAndGet");
/**
* @description translate AST Key == value, return new Object
* @param {Object} obj - AST
* @param {Object} obj - remark AST
* @param {Object} Opts - options
* @param {String} Opts.api - defuault api
* @param {String} Opts.name - file name
......@@ -115,202 +136,218 @@ const { getTypeValue, setTypeValue} = require('./typeSetAndGet')
* @returns {Object} - newObject
*/
async function setObjectKey(obj, opts) {
let allAPi = apis
let api = opts.api
let howManyValNoTran = 0
let errMsg = ""
let tranArray = []
let thisTranArray = []
let resultArray = []
let newObj = newObject(obj)
let tips = `${r("If slow/stagnant , should try again")}`
// put obj values to tranArray
let sum = getTypeValue(obj, tranArray)
if (!sum || !tranArray.length) {
loggerText("no value " + sum, {
level: "error"
})
return "no value"
}
if (tranArray.length) {
// remove all \n
tranArray = tranArray.map(x => {
if (x.indexOf('\n') >= 0) {
return x.replace(/[\n]/g, ' ')
}
return x
})
thisTranArray = tranArray
tranArray = []
// --values {cli options}
if(getValuesFile){
await asyncWrite(getValuesFile,thisTranArray).then(function(ok){
loggerText(`${getValuesFile} saved`)
})
return `you want ${g(relaPath(getValuesFile))} values save, so ${r('skip')} translate`
}
}
if(gotTranslateFile){ // custom translate file with single file
let tContent = await asyncRead(gotTranslateFile)
let relaP = relaPath(gotTranslateFile)
if(tContent.length === thisTranArray.length){
oneOra(`you choose ${y(relaP)} be The translation`)
resultArray = tContent
}else{
throw new Error(`${g(relaP)} value length ${r('no equal')}\n translate-content:${y(tContent.length)}\n wait-translate:${y(thisTranArray.length)}`)
}
}else{
// Fix file Too Big
let chunkTranArray = fixFileTooBig(thisTranArray)
for (let third in chunkTranArray) {
let thisChunkTran = chunkTranArray[third]
let thisInfo = ""
let isWork = true
// auto change translate source
allAPi = allAPi.filter(x => x != api)
allAPi.push(api)
let thisResult = []
// get cache disk with chunk result
let cacheRes = getDisk(cacheName, {source:thisChunkTran.join("\n")})
if(cacheRes && cacheRes.result && diskState){
thisResult = cacheRes.result
isWork = false
thisInfo = y(`result: come from Cache disk`+diskState)
let allAPi = apis;
let api = opts.api;
let howManyValNoTran = 0;
let errMsg = "";
let tranArray = [];
let thisTranArray = [];
let resultArray = [];
let newObj = newObject(obj);
let tips = `${r("If slow/stagnant , should try again")}`;
// put obj values to tranArray
let sum = getTypeValue(obj, tranArray);
if (!sum || !tranArray.length) {
loggerText("no value " + sum, {
level: "error",
});
return "no value";
}
if (tranArray.length) {
// remove all \n
tranArray = tranArray.map((x) => {
if (x.indexOf("\n") >= 0) {
return x.replace(/[\n]/g, " ");
}
return x;
});
thisTranArray = tranArray;
tranArray = [];
// --values {cli options}
if (getValuesFile) {
await asyncWrite(getValuesFile, thisTranArray).then(function (ok) {
loggerText(`${getValuesFile} saved`);
});
return `you want ${g(relaPath(getValuesFile))} values save, so ${r(
"skip"
)} translate`;
}
}
if (gotTranslateFile) {
// custom translate file with single file
let tContent = await asyncRead(gotTranslateFile);
let relaP = relaPath(gotTranslateFile);
if (tContent.length === thisTranArray.length) {
oneOra(`you choose ${y(relaP)} be The translation`);
resultArray = tContent;
} else {
throw new Error(
`${g(relaP)} value length ${r("no equal")}\n translate-content:${y(
tContent.length
)}\n wait-translate:${y(thisTranArray.length)}`
);
}
} else {
// Fix file Too Big
let chunkTranArray = fixFileTooBig(thisTranArray);
for (let third in chunkTranArray) {
let thisChunkTran = chunkTranArray[third];
let thisInfo = "";
let isWork = true;
// auto change translate source
allAPi = allAPi.filter((x) => x != api);
allAPi.push(api);
let thisResult = [];
// get cache disk with chunk result
let cacheRes = getDisk(cacheName, { source: thisChunkTran.join("\n") });
if (cacheRes && cacheRes.result && diskState) {
thisResult = cacheRes.result;
isWork = false;
thisInfo = y(`result: come from Cache disk` + diskState);
}
if (isWork)
for (let i in allAPi) {
// Auto next api
loggerText(
`2. ${yow(relaPath(opts.name))} use ${g(api)} ${
resultArray.length
}/${thisTranArray.length} - ${tips}`
);
try {
if (thisChunkTran.join("").length > MAXstring) {
// string > 300
let thisChunkTranL_2 = Math.ceil(thisChunkTran.length / 2);
let left = indexMergeArr(thisChunkTran, 0, thisChunkTranL_2);
let right = indexMergeArr(
thisChunkTran,
thisChunkTranL_2,
thisChunkTranL_2
);
let t0 = await translateValue(left, api);
let t1 = await translateValue(right, api);
thisResult = t0.concat(t1);
} else {
thisResult = await translateValue(thisChunkTran, api);
} // get Result Arr
} catch (error) {
if (!error.code) {
loggerText(`${error.message} tjs-error, api:${y(api)}`, {
level: "error",
color: "red",
});
} else {
loggerText(`${error.code} ,api:${y(api)}`, {
level: "error",
color: "red",
});
}
thisResult = [];
}
// debug
debugMsg(1, thisChunkTran, thisResult);
// result-1 return translate value, break for allAPi
if (
thisResult.length > 0 &&
thisResult.length >= thisChunkTran.length
) {
let markChunkTran = [].concat(thisChunkTran); // mark some emoji, display the split
if (thisChunkTran.length < thisResult.length) {
// Fix use Fix/lengthEqual.js in every Chunk
markChunkTran = translateLengthEquals(thisChunkTran, thisResult); // Fix
}
if(isWork)
for (let i in allAPi) { // Auto next api
loggerText(`2. ${yow(relaPath(opts.name))} use ${g(api)} ${resultArray.length}/${thisTranArray.length} - ${tips}`)
try {
if (thisChunkTran.join("").length > MAXstring) { // string > 300
let thisChunkTranL_2 = Math.ceil(thisChunkTran.length / 2)
let left = indexMergeArr(thisChunkTran, 0, thisChunkTranL_2)
let right = indexMergeArr(thisChunkTran, thisChunkTranL_2, thisChunkTranL_2)
let t0 = await translateValue(left, api)
let t1 = await translateValue(right, api)
thisResult = t0.concat(t1)
} else {
thisResult = await translateValue(thisChunkTran, api)
} // get Result Arr
} catch (error) {
if (!error.code) {
loggerText(`${error.message} tjs-error, api:${y(api)}`, {
level: "error",
color: "red"
})
} else {
loggerText(`${error.code} ,api:${y(api)}`, {
level: "error",
color: "red"
})
}
thisResult = []
}
// debug
debugMsg(1, thisChunkTran, thisResult)
// result-1 return translate value, break for allAPi
if (thisResult.length > 0 && thisResult.length >= thisChunkTran.length) {
let markChunkTran = [].concat(thisChunkTran); // mark some emoji, display the split
if (thisChunkTran.length < thisResult.length) {
// Fix use Fix/lengthEqual.js in every Chunk
markChunkTran = translateLengthEquals(thisChunkTran, thisResult) // Fix
}
if (markChunkTran.length != thisResult.length) { // debug only unequal
debugMsg(2, markChunkTran, thisResult)
}
if (markChunkTran.length != thisResult.length) {
// debug only unequal
if (thisChunkTran.length == thisResult.length) {
// Fix Upper/Lower case
for (let i in thisChunkTran) {
if (thisChunkTran[i].trim().toLowerCase() == thisResult[i].trim().toLowerCase()) {
thisResult[i] = thisChunkTran[i]
}
}
break
}
}
debugMsg(2, markChunkTran, thisResult);
}
api = allAPi[i]
// result-2 return source value
if ((+i + 1) == allAPi.length) {
// ending is no result
// count how many string no translate
howManyValNoTran += thisChunkTran.length
isWork = false
thisResult = thisChunkTran // Add source tran
errMsg = `PS: can not get translation from API`
}
}
resultArray = resultArray.concat(thisResult) // Add result
loggerText(`3. translate loading - ${resultArray.length}/${thisTranArray.length} < ${thisInfo}`)
if(errMsg && !Force){
break;
}else if(!errMsg && cache && !thisInfo){ // cache with cache-name
let cacheStruct = {
time: new Date().getTime(),
api: api,
f:tranF,
t:tranT,
source: thisChunkTran.join("\n"),
result: thisResult
if (thisChunkTran.length == thisResult.length) {
// Fix Upper/Lower case
for (let i in thisChunkTran) {
if (
thisChunkTran[i].trim().toLowerCase() ==
thisResult[i].trim().toLowerCase()
) {
thisResult[i] = thisChunkTran[i];
}
setDisk(cacheName, {source:cacheStruct.source}, cacheStruct)
loggerText(`3.1. ${g("cached")} the translate result`)
}
break;
}
}
api = allAPi[i];
// result-2 return source value
if (+i + 1 == allAPi.length) {
// ending is no result
// count how many string no translate
howManyValNoTran += thisChunkTran.length;
isWork = false;
thisResult = thisChunkTran; // Add source tran
errMsg = `PS: can not get translation from API`;
}
}
}
}
if(!errMsg || Force){
// default: zh symbal ,。!
!zhSymbal && (resultArray = fixZhtoEn(resultArray))
setTypeValue(newObj, resultArray)
resultArray = resultArray.concat(thisResult); // Add result
loggerText(
`3. translate loading - ${resultArray.length}/${thisTranArray.length} < ${thisInfo}`
);
if (errMsg && !Force) {
break;
} else if (!errMsg && cache && !thisInfo) {
// cache with cache-name
let cacheStruct = {
time: new Date().getTime(),
api: api,
f: tranF,
t: tranT,
source: thisChunkTran.join("\n"),
result: thisResult,
};
setDisk(cacheName, { source: cacheStruct.source }, cacheStruct);
loggerText(`3.1. ${g("cached")} the translate result`);
}
}
}
if (!errMsg || Force) {
// default: zh symbal ,。!
!zhSymbal && (resultArray = fixZhtoEn(resultArray));
if (howManyValNoTran > 0) {
newObj.Error = `translated number: ${resultArray.length - howManyValNoTran}/${thisTranArray.length} ${errMsg}`
}
setTypeValue(newObj, resultArray);
}
if (howManyValNoTran > 0) {
newObj.Error = `translated number: ${
resultArray.length - howManyValNoTran
}/${thisTranArray.length} ${errMsg}`;
}
return newObj
return newObj;
}
module.exports = {
setObjectKey,
translateValue
}
setObjectKey,
translateValue,
};
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册