yomichan/ext/bg/js/translator.js

531 lines
19 KiB
JavaScript
Raw Normal View History

2016-03-20 17:52:27 +00:00
/*
2020-01-01 17:00:00 +00:00
* Copyright (C) 2016-2020 Alex Yatskov <alex@foosoft.net>
2016-03-20 17:52:27 +00:00
* Author: Alex Yatskov <alex@foosoft.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2020-01-01 17:00:31 +00:00
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2016-03-20 17:52:27 +00:00
*/
2016-03-24 02:25:32 +00:00
2016-03-20 17:52:27 +00:00
class Translator {
2016-03-26 21:16:21 +00:00
constructor() {
2017-07-10 21:30:34 +00:00
this.database = null;
this.deinflector = null;
this.tagCache = {};
2016-03-26 21:16:21 +00:00
}
2017-07-10 21:10:58 +00:00
async prepare() {
2017-07-10 21:30:34 +00:00
if (!this.database) {
this.database = new Database();
2017-07-10 21:10:58 +00:00
await this.database.prepare();
2017-07-10 21:30:34 +00:00
}
if (!this.deinflector) {
const url = chrome.runtime.getURL('/bg/lang/deinflect.json');
2017-07-20 04:28:09 +00:00
const reasons = await requestJson(url, 'GET');
2017-07-10 21:30:34 +00:00
this.deinflector = new Deinflector(reasons);
2017-07-10 21:10:58 +00:00
}
2016-03-20 17:52:27 +00:00
}
2016-03-21 01:45:37 +00:00
async purgeDatabase() {
this.tagCache = {};
await this.database.purge();
}
async deleteDictionary(dictionaryName) {
this.tagCache = {};
await this.database.deleteDictionary(dictionaryName);
}
async getSequencedDefinitions(definitions, mainDictionary) {
const definitionsBySequence = dictTermsMergeBySequence(definitions, mainDictionary);
const defaultDefinitions = definitionsBySequence['-1'];
2019-11-27 03:01:54 +00:00
const sequenceList = Object.keys(definitionsBySequence).map((v) => Number(v)).filter((v) => v >= 0);
const sequencedDefinitions = sequenceList.map((key) => ({
definitions: definitionsBySequence[key],
rawDefinitions: []
}));
for (const definition of await this.database.findTermsBySequenceBulk(sequenceList, mainDictionary)) {
sequencedDefinitions[definition.index].rawDefinitions.push(definition);
}
return {sequencedDefinitions, defaultDefinitions};
}
2019-10-19 16:24:38 +00:00
async getMergedSecondarySearchResults(text, expressionsMap, secondarySearchTitles) {
if (secondarySearchTitles.length === 0) {
return [];
2019-10-19 16:24:38 +00:00
}
const expressionList = [];
const readingList = [];
2019-10-19 16:24:38 +00:00
for (const expression of expressionsMap.keys()) {
if (expression === text) { continue; }
2019-10-19 16:24:38 +00:00
for (const reading of expressionsMap.get(expression).keys()) {
expressionList.push(expression);
readingList.push(reading);
2019-10-19 16:24:38 +00:00
}
}
const definitions = await this.database.findTermsExactBulk(expressionList, readingList, secondarySearchTitles);
for (const definition of definitions) {
const definitionTags = await this.expandTags(definition.definitionTags, definition.dictionary);
definitionTags.push(dictTagBuildSource(definition.dictionary));
definition.definitionTags = definitionTags;
const termTags = await this.expandTags(definition.termTags, definition.dictionary);
definition.termTags = termTags;
}
if (definitions.length > 1) {
definitions.sort((a, b) => a.index - b.index);
}
return definitions;
2019-10-19 16:24:38 +00:00
}
async getMergedDefinition(text, dictionaries, sequencedDefinition, defaultDefinitions, secondarySearchTitles, mergedByTermIndices) {
const result = sequencedDefinition.definitions;
const rawDefinitionsBySequence = sequencedDefinition.rawDefinitions;
for (const definition of rawDefinitionsBySequence) {
const definitionTags = await this.expandTags(definition.definitionTags, definition.dictionary);
definitionTags.push(dictTagBuildSource(definition.dictionary));
definition.definitionTags = definitionTags;
const termTags = await this.expandTags(definition.termTags, definition.dictionary);
definition.termTags = termTags;
}
const definitionsByGloss = dictTermsMergeByGloss(result, rawDefinitionsBySequence);
2019-10-19 16:24:38 +00:00
const secondarySearchResults = await this.getMergedSecondarySearchResults(text, result.expressions, secondarySearchTitles);
2017-10-15 02:19:16 +00:00
dictTermsMergeByGloss(result, defaultDefinitions.concat(secondarySearchResults), definitionsByGloss, mergedByTermIndices);
for (const gloss in definitionsByGloss) {
const definition = definitionsByGloss[gloss];
dictTagsSort(definition.definitionTags);
result.definitions.push(definition);
}
dictTermsSort(result.definitions, dictionaries);
const expressions = [];
2019-12-27 20:08:55 +00:00
for (const [expression, readingMap] of result.expressions.entries()) {
for (const [reading, termTags] of readingMap.entries()) {
2019-11-27 03:01:54 +00:00
const score = termTags.map((tag) => tag.score).reduce((p, v) => p + v, 0);
2019-12-27 20:08:55 +00:00
expressions.push(Translator.createExpression(expression, reading, dictTagsSort(termTags), Translator.scoreToTermFrequency(score)));
}
}
result.expressions = expressions;
result.expression = Array.from(result.expression);
result.reading = Array.from(result.reading);
return result;
}
2017-10-17 08:16:38 +00:00
2019-11-05 01:43:40 +00:00
async findTerms(text, details, options) {
2019-11-05 01:09:34 +00:00
switch (options.general.resultOutputMode) {
case 'group':
2019-11-05 01:43:40 +00:00
return await this.findTermsGrouped(text, details, options);
2019-11-05 01:09:34 +00:00
case 'merge':
2019-11-05 01:43:40 +00:00
return await this.findTermsMerged(text, details, options);
2019-11-05 01:09:34 +00:00
case 'split':
2019-11-05 01:43:40 +00:00
return await this.findTermsSplit(text, details, options);
2019-11-05 01:09:34 +00:00
default:
return [[], 0];
}
}
2019-11-05 01:43:40 +00:00
async findTermsGrouped(text, details, options) {
2019-11-05 01:09:34 +00:00
const dictionaries = dictEnabledSet(options);
2019-11-05 00:35:57 +00:00
const titles = Object.keys(dictionaries);
2019-11-05 01:43:40 +00:00
const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details);
2019-11-05 00:35:57 +00:00
const definitionsGrouped = dictTermsGroup(definitions, dictionaries);
await this.buildTermFrequencies(definitionsGrouped, titles);
if (options.general.compactTags) {
for (const definition of definitionsGrouped) {
dictTermsCompressTags(definition.definitions);
}
}
2019-11-05 01:09:34 +00:00
return [definitionsGrouped, length];
2019-11-05 00:35:57 +00:00
}
2019-11-05 01:43:40 +00:00
async findTermsMerged(text, details, options) {
2019-11-05 01:09:34 +00:00
const dictionaries = dictEnabledSet(options);
2019-11-27 03:01:54 +00:00
const secondarySearchTitles = Object.keys(options.dictionaries).filter((dict) => options.dictionaries[dict].allowSecondarySearches);
const titles = Object.keys(dictionaries);
2019-11-05 01:43:40 +00:00
const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details);
const {sequencedDefinitions, defaultDefinitions} = await this.getSequencedDefinitions(definitions, options.general.mainDictionary);
const definitionsMerged = [];
const mergedByTermIndices = new Set();
for (const sequencedDefinition of sequencedDefinitions) {
const result = await this.getMergedDefinition(
text,
dictionaries,
sequencedDefinition,
defaultDefinitions,
secondarySearchTitles,
mergedByTermIndices
);
definitionsMerged.push(result);
}
const strayDefinitions = defaultDefinitions.filter((definition, index) => !mergedByTermIndices.has(index));
for (const groupedDefinition of dictTermsGroup(strayDefinitions, dictionaries)) {
2019-12-29 03:55:29 +00:00
groupedDefinition.expressions = [Translator.createExpression(groupedDefinition.expression, groupedDefinition.reading)];
definitionsMerged.push(groupedDefinition);
}
2019-08-31 01:06:21 +00:00
await this.buildTermFrequencies(definitionsMerged, titles);
2017-10-12 06:59:09 +00:00
if (options.general.compactTags) {
for (const definition of definitionsMerged) {
dictTermsCompressTags(definition.definitions);
}
}
2019-11-05 01:09:34 +00:00
return [dictTermsSort(definitionsMerged), length];
}
2019-11-05 01:43:40 +00:00
async findTermsSplit(text, details, options) {
2019-11-05 01:09:34 +00:00
const dictionaries = dictEnabledSet(options);
2017-09-14 06:22:41 +00:00
const titles = Object.keys(dictionaries);
2019-11-05 01:43:40 +00:00
const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details);
2017-09-14 06:22:41 +00:00
2019-08-31 01:06:21 +00:00
await this.buildTermFrequencies(definitions, titles);
2017-09-14 06:22:41 +00:00
2019-11-05 01:09:34 +00:00
return [definitions, length];
2017-07-10 21:10:58 +00:00
}
2019-11-05 01:43:40 +00:00
async findTermsInternal(text, dictionaries, alphanumeric, details) {
if (!alphanumeric && text.length > 0) {
const c = text[0];
if (!jpIsKana(c) && !jpIsKanji(c)) {
2019-11-05 01:09:34 +00:00
return [[], 0];
}
}
2019-08-31 01:06:21 +00:00
const titles = Object.keys(dictionaries);
2019-11-05 01:52:08 +00:00
const deinflections = (
details.wildcard ?
2019-11-24 02:48:24 +00:00
await this.findTermWildcard(text, titles, details.wildcard) :
2019-11-05 01:52:08 +00:00
await this.findTermDeinflections(text, titles)
);
2016-03-21 03:34:50 +00:00
2017-07-10 21:10:58 +00:00
let definitions = [];
for (const deinflection of deinflections) {
for (const definition of deinflection.definitions) {
const definitionTags = await this.expandTags(definition.definitionTags, definition.dictionary);
definitionTags.push(dictTagBuildSource(definition.dictionary));
const termTags = await this.expandTags(definition.termTags, definition.dictionary);
2017-09-13 01:29:16 +00:00
2019-12-27 20:08:55 +00:00
const {expression, reading} = definition;
const furiganaSegments = jpDistributeFurigana(expression, reading);
2017-07-10 21:10:58 +00:00
definitions.push({
source: deinflection.source,
reasons: deinflection.reasons,
score: definition.score,
id: definition.id,
dictionary: definition.dictionary,
2019-12-27 20:08:55 +00:00
expression,
reading,
furiganaSegments,
2017-07-10 21:10:58 +00:00
glossary: definition.glossary,
definitionTags: dictTagsSort(definitionTags),
termTags: dictTagsSort(termTags),
sequence: definition.sequence
2017-07-10 21:10:58 +00:00
});
2017-01-08 19:18:55 +00:00
}
2017-07-10 21:10:58 +00:00
}
definitions = dictTermsUndupe(definitions);
definitions = dictTermsSort(definitions, dictionaries);
2017-01-08 19:18:55 +00:00
2017-07-10 21:10:58 +00:00
let length = 0;
for (const definition of definitions) {
length = Math.max(length, definition.source.length);
}
2019-11-05 01:09:34 +00:00
return [definitions, length];
2016-03-21 01:45:37 +00:00
}
2019-11-24 02:48:24 +00:00
async findTermWildcard(text, titles, wildcard) {
const definitions = await this.database.findTermsBulk([text], titles, wildcard);
2019-11-05 01:52:08 +00:00
if (definitions.length === 0) {
return [];
}
return [{
source: text,
term: text,
rules: 0,
definitions,
reasons: []
}];
}
async findTermDeinflections(text, titles) {
const text2 = jpKatakanaToHiragana(text);
2019-08-31 01:06:21 +00:00
const deinflections = (text === text2 ? this.getDeinflections(text) : this.getDeinflections2(text, text2));
if (deinflections.length === 0) {
return [];
}
const uniqueDeinflectionTerms = [];
const uniqueDeinflectionArrays = [];
const uniqueDeinflectionsMap = {};
for (const deinflection of deinflections) {
const term = deinflection.term;
let deinflectionArray;
if (hasOwn(uniqueDeinflectionsMap, term)) {
deinflectionArray = uniqueDeinflectionsMap[term];
} else {
deinflectionArray = [];
uniqueDeinflectionTerms.push(term);
uniqueDeinflectionArrays.push(deinflectionArray);
uniqueDeinflectionsMap[term] = deinflectionArray;
}
deinflectionArray.push(deinflection);
}
2019-11-24 02:48:24 +00:00
const definitions = await this.database.findTermsBulk(uniqueDeinflectionTerms, titles, null);
2019-08-31 01:06:21 +00:00
for (const definition of definitions) {
const definitionRules = Deinflector.rulesToRuleFlags(definition.rules);
for (const deinflection of uniqueDeinflectionArrays[definition.index]) {
const deinflectionRules = deinflection.rules;
if (deinflectionRules === 0 || (definitionRules & deinflectionRules) !== 0) {
deinflection.definitions.push(definition);
}
}
2019-08-31 01:06:21 +00:00
}
2019-11-27 03:01:54 +00:00
return deinflections.filter((e) => e.definitions.length > 0);
2019-08-31 01:06:21 +00:00
}
getDeinflections(text) {
const deinflections = [];
2016-11-13 03:29:30 +00:00
for (let i = text.length; i > 0; --i) {
const textSubstring = text.substring(0, i);
deinflections.push(...this.deinflector.deinflect(textSubstring));
2016-11-13 03:29:30 +00:00
}
2017-07-10 21:10:58 +00:00
return deinflections;
2016-03-21 03:34:50 +00:00
}
getDeinflections2(text1, text2) {
2019-08-31 01:06:21 +00:00
const deinflections = [];
for (let i = text1.length; i > 0; --i) {
const text1Substring = text1.substring(0, i);
const text2Substring = text2.substring(0, i);
deinflections.push(...this.deinflector.deinflect(text1Substring));
if (text1Substring !== text2Substring) {
deinflections.push(...this.deinflector.deinflect(text2Substring));
2019-08-31 01:06:21 +00:00
}
}
return deinflections;
}
async findKanji(text, options) {
const dictionaries = dictEnabledSet(options);
2017-07-10 21:10:58 +00:00
const titles = Object.keys(dictionaries);
const kanjiUnique = {};
const kanjiList = [];
2017-07-10 21:10:58 +00:00
for (const c of text) {
if (!hasOwn(kanjiUnique, c)) {
kanjiList.push(c);
kanjiUnique[c] = true;
2017-07-10 21:10:58 +00:00
}
}
const definitions = await this.database.findKanjiBulk(kanjiList, titles);
if (definitions.length === 0) {
return definitions;
}
if (definitions.length > 1) {
definitions.sort((a, b) => a.index - b.index);
}
const kanjiList2 = [];
2017-02-26 19:12:54 +00:00
for (const definition of definitions) {
kanjiList2.push(definition.character);
2017-09-18 02:16:08 +00:00
const tags = await this.expandTags(definition.tags, definition.dictionary);
2017-07-10 21:10:58 +00:00
tags.push(dictTagBuildSource(definition.dictionary));
2017-09-18 02:16:08 +00:00
2017-03-03 05:01:49 +00:00
definition.tags = dictTagsSort(tags);
2017-09-18 02:57:39 +00:00
definition.stats = await this.expandStats(definition.stats, definition.dictionary);
2017-09-23 15:46:34 +00:00
definition.frequencies = [];
}
for (const meta of await this.database.findKanjiMetaBulk(kanjiList2, titles)) {
if (meta.mode !== 'freq') { continue; }
definitions[meta.index].frequencies.push({
character: meta.character,
frequency: meta.data,
dictionary: meta.dictionary
});
2016-08-08 02:56:50 +00:00
}
2016-09-11 19:40:45 +00:00
return definitions;
2016-08-08 05:42:56 +00:00
}
2017-09-13 23:42:04 +00:00
2019-08-31 01:06:21 +00:00
async buildTermFrequencies(definitions, titles) {
const terms = [];
for (const definition of definitions) {
if (definition.expressions) {
terms.push(...definition.expressions);
} else {
terms.push(definition);
}
}
if (terms.length === 0) {
return;
}
2019-08-31 01:06:21 +00:00
// Create mapping of unique terms
const expressionsUnique = [];
const termsUnique = [];
const termsUniqueMap = {};
for (let i = 0, ii = terms.length; i < ii; ++i) {
const term = terms[i];
const expression = term.expression;
term.frequencies = [];
2019-08-31 01:06:21 +00:00
if (hasOwn(termsUniqueMap, expression)) {
2019-08-31 01:06:21 +00:00
termsUniqueMap[expression].push(term);
} else {
const termList = [term];
expressionsUnique.push(expression);
termsUnique.push(termList);
termsUniqueMap[expression] = termList;
}
}
const metas = await this.database.findTermMetaBulk(expressionsUnique, titles);
for (const meta of metas) {
if (meta.mode !== 'freq') {
continue;
}
for (const term of termsUnique[meta.index]) {
term.frequencies.push({
expression: meta.expression,
frequency: meta.data,
dictionary: meta.dictionary
});
2017-09-23 15:46:34 +00:00
}
2017-09-14 06:22:41 +00:00
}
}
2017-09-18 02:16:08 +00:00
async expandTags(names, title) {
const tagMetaList = await this.getTagMetaList(names, title);
return tagMetaList.map((meta, index) => {
const name = names[index];
const tag = dictTagSanitize(Object.assign({}, meta !== null ? meta : {}, {name}));
return dictTagSanitize(tag);
});
2017-09-13 23:42:04 +00:00
}
2017-09-18 02:16:08 +00:00
2017-09-18 02:57:39 +00:00
async expandStats(items, title) {
const names = Object.keys(items);
const tagMetaList = await this.getTagMetaList(names, title);
2017-09-18 02:16:08 +00:00
const stats = {};
for (let i = 0; i < names.length; ++i) {
const name = names[i];
const meta = tagMetaList[i];
if (meta === null) { continue; }
const category = meta.category;
const group = (
hasOwn(stats, category) ?
stats[category] :
(stats[category] = [])
);
const stat = Object.assign({}, meta, {name, value: items[name]});
2017-09-21 06:15:02 +00:00
group.push(dictTagSanitize(stat));
2017-09-18 02:16:08 +00:00
}
const sortCompare = (a, b) => a.notes - b.notes;
2017-09-22 06:20:51 +00:00
for (const category in stats) {
stats[category].sort(sortCompare);
2017-09-22 06:20:51 +00:00
}
2017-09-18 02:57:39 +00:00
return stats;
2017-09-18 02:16:08 +00:00
}
async getTagMetaList(names, title) {
const tagMetaList = [];
const cache = (
hasOwn(this.tagCache, title) ?
this.tagCache[title] :
(this.tagCache[title] = {})
);
for (const name of names) {
const base = Translator.getNameBase(name);
if (hasOwn(cache, base)) {
tagMetaList.push(cache[base]);
} else {
const tagMeta = await this.database.findTagForTitle(base, title);
cache[base] = tagMeta;
tagMetaList.push(tagMeta);
}
}
return tagMetaList;
}
2019-12-27 20:08:55 +00:00
static createExpression(expression, reading, termTags=null, termFrequency=null) {
const furiganaSegments = jpDistributeFurigana(expression, reading);
return {
expression,
reading,
furiganaSegments,
termTags,
termFrequency
};
}
static scoreToTermFrequency(score) {
if (score > 0) {
return 'popular';
} else if (score < 0) {
return 'rare';
} else {
return 'normal';
}
}
static getNameBase(name) {
const pos = name.indexOf(':');
return (pos >= 0 ? name.substring(0, pos) : name);
}
2016-03-20 17:52:27 +00:00
}