tinyfix-tr 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +138 -2
- package/dist/pkg/src/context.d.ts +13 -0
- package/dist/pkg/src/context.js +80 -0
- package/dist/pkg/src/data.d.ts +50 -0
- package/dist/pkg/src/data.js +495 -0
- package/dist/pkg/src/engine.d.ts +39 -0
- package/dist/pkg/src/engine.js +357 -0
- package/dist/pkg/src/index.d.ts +30 -0
- package/dist/pkg/src/index.js +85 -0
- package/dist/pkg/src/protocol.d.ts +64 -0
- package/dist/pkg/src/protocol.js +1 -0
- package/dist/pkg/src/types.d.ts +184 -0
- package/dist/pkg/src/types.js +16 -0
- package/dist/pkg/src/worker.d.ts +11 -0
- package/dist/pkg/src/worker.js +111 -0
- package/dist/pkg/src/workerClient.d.ts +3 -0
- package/dist/pkg/src/workerClient.js +202 -0
- package/dist/src/context-vocab.d.ts +1 -0
- package/dist/src/context-vocab.js +2 -0
- package/dist/src/context.d.ts +92 -0
- package/dist/src/context.js +390 -0
- package/dist/src/corrector.d.ts +338 -0
- package/dist/src/corrector.js +2684 -0
- package/dist/src/known.d.ts +88 -0
- package/dist/src/known.js +286 -0
- package/dist/src/lexicon-binary.d.ts +85 -0
- package/dist/src/lexicon-binary.js +805 -0
- package/dist/src/lexicon.d.ts +24 -0
- package/dist/src/lexicon.js +79 -0
- package/dist/src/morphology/analyzer.d.ts +30 -0
- package/dist/src/morphology/analyzer.js +311 -0
- package/dist/src/morphology/binary.d.ts +22 -0
- package/dist/src/morphology/binary.js +372 -0
- package/dist/src/morphology/dictionary.d.ts +21 -0
- package/dist/src/morphology/dictionary.js +559 -0
- package/dist/src/morphology/fuzzy.d.ts +44 -0
- package/dist/src/morphology/fuzzy.js +599 -0
- package/dist/src/morphology/index.d.ts +40 -0
- package/dist/src/morphology/index.js +81 -0
- package/dist/src/morphology/morphotactics.d.ts +148 -0
- package/dist/src/morphology/morphotactics.js +1871 -0
- package/dist/src/morphology/phonetics.d.ts +71 -0
- package/dist/src/morphology/phonetics.js +309 -0
- package/dist/src/morphology/prior.d.ts +61 -0
- package/dist/src/morphology/prior.js +457 -0
- package/dist/src/morphology/types.d.ts +110 -0
- package/dist/src/morphology/types.js +32 -0
- package/dist/src/rules/proper-names.d.ts +145 -0
- package/dist/src/rules/proper-names.js +1217 -0
- package/dist/src/rules/turkish-rules.d.ts +126 -0
- package/dist/src/rules/turkish-rules.js +365 -0
- package/dist/src/sentence.d.ts +83 -0
- package/dist/src/sentence.js +2408 -0
- package/dist/src/turkish.d.ts +20 -0
- package/dist/src/turkish.js +94 -0
- package/package.json +60 -4
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
import { KnownMisspellings } from "../../src/known.js";
|
|
2
|
+
import { Lexicon } from "../../src/lexicon.js";
|
|
3
|
+
import { TurkishMorphology } from "../../src/morphology/index.js";
|
|
4
|
+
import { createOnnxContextSession, wrapContextModel } from "./context.js";
|
|
5
|
+
import { CONTEXT_MODEL_FILE } from "./types.js";
|
|
6
|
+
/** Zorunlu tarayıcı veri dosyaları (ikili sözlük + biçimbilim + bilinen yanlışlar). */
|
|
7
|
+
export const DATA_FILES = [
|
|
8
|
+
"lexicon.bin",
|
|
9
|
+
"morph.bin",
|
|
10
|
+
"known.tsv",
|
|
11
|
+
];
|
|
12
|
+
/** Eski düz metin TSV dosya listesi (geriye dönük uyumluluk için). */
|
|
13
|
+
export const LEGACY_DATA_FILES = [
|
|
14
|
+
"unigrams.tsv",
|
|
15
|
+
"bigrams.tsv",
|
|
16
|
+
"known.tsv",
|
|
17
|
+
];
|
|
18
|
+
export { CONTEXT_MODEL_FILE };
|
|
19
|
+
/** Varsayılan sözlük ve model dizini. */
|
|
20
|
+
export const DEFAULT_BASE_URL = "/models/";
|
|
21
|
+
/** İndirme ilerlemesini tahmin etmek için dosyaların yaklaşık ağırlıkları (Content-Length yoksa). */
|
|
22
|
+
const FILE_WEIGHTS = {
|
|
23
|
+
"lexicon.bin": 0.94,
|
|
24
|
+
"morph.bin": 0.05,
|
|
25
|
+
"known.tsv": 0.01,
|
|
26
|
+
"unigrams.tsv": 0.60,
|
|
27
|
+
"bigrams.tsv": 0.26,
|
|
28
|
+
"context.onnx": 0.25,
|
|
29
|
+
};
|
|
30
|
+
const DOWNLOAD_SHARE = 0.9;
|
|
31
|
+
const PROGRESS_THROTTLE_MS = 40;
|
|
32
|
+
const DOWNLOAD_ATTEMPTS = 3;
|
|
33
|
+
const nextTask = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
34
|
+
/** Verilen bellek içi verinin ikili (`BinaryData`) biçimde olup olmadığını söyler. */
|
|
35
|
+
export function isBinaryData(data) {
|
|
36
|
+
return "lexicon" in data && data.lexicon instanceof Uint8Array;
|
|
37
|
+
}
|
|
38
|
+
/** Göreli veya mutlak URL/yol değerini sona `/` ekleyerek çözümler. */
|
|
39
|
+
export function resolveBaseUrl(baseUrl = DEFAULT_BASE_URL) {
|
|
40
|
+
const raw = String(baseUrl);
|
|
41
|
+
const withSlash = raw.endsWith("/") ? raw : `${raw}/`;
|
|
42
|
+
if (typeof location !== "undefined" && typeof location.href === "string") {
|
|
43
|
+
return new URL(withSlash, location.href).href;
|
|
44
|
+
}
|
|
45
|
+
return withSlash;
|
|
46
|
+
}
|
|
47
|
+
function buildFileUrl(baseUrl, file) {
|
|
48
|
+
if (/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(baseUrl)) {
|
|
49
|
+
return new URL(file, baseUrl).href;
|
|
50
|
+
}
|
|
51
|
+
return `${baseUrl}${file}`;
|
|
52
|
+
}
|
|
53
|
+
function parseContentLength(response) {
|
|
54
|
+
// Sıkıştırılmış yanıtlarda Content-Length aktarım boyutudur, reader ise açılmış baytları verir.
|
|
55
|
+
const encoding = response.headers.get("content-encoding");
|
|
56
|
+
if (encoding && encoding !== "identity")
|
|
57
|
+
return null;
|
|
58
|
+
const header = response.headers.get("content-length");
|
|
59
|
+
if (!header)
|
|
60
|
+
return null;
|
|
61
|
+
const value = Number(header);
|
|
62
|
+
return Number.isFinite(value) && value > 0 ? value : null;
|
|
63
|
+
}
|
|
64
|
+
function summarizeDownload(states, files, activeFile) {
|
|
65
|
+
let loaded = 0;
|
|
66
|
+
let totalSum = 0;
|
|
67
|
+
let allTotalsKnown = true;
|
|
68
|
+
for (const file of files) {
|
|
69
|
+
const state = states[file];
|
|
70
|
+
loaded += state.loaded;
|
|
71
|
+
if (state.total !== null && state.loaded <= state.total) {
|
|
72
|
+
totalSum += state.total;
|
|
73
|
+
}
|
|
74
|
+
else if (state.done && state.loaded > 0) {
|
|
75
|
+
totalSum += state.loaded;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
allTotalsKnown = false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
let downloadRatio;
|
|
82
|
+
if (allTotalsKnown && totalSum > 0) {
|
|
83
|
+
downloadRatio = Math.min(1, loaded / totalSum);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
downloadRatio = 0;
|
|
87
|
+
const totalWeight = files.reduce((sum, file) => sum + FILE_WEIGHTS[file], 0) || 1;
|
|
88
|
+
for (const file of files) {
|
|
89
|
+
const state = states[file];
|
|
90
|
+
let fileRatio = 0;
|
|
91
|
+
if (state.done) {
|
|
92
|
+
fileRatio = 1;
|
|
93
|
+
}
|
|
94
|
+
else if (state.total !== null && state.total > 0) {
|
|
95
|
+
fileRatio = Math.min(0.98, state.loaded / state.total);
|
|
96
|
+
}
|
|
97
|
+
else if (state.loaded > 0) {
|
|
98
|
+
// Boyut bilinmiyorsa yumuşak asimptotik ilerleme (0.9'u aşmaz).
|
|
99
|
+
fileRatio = 0.9 * (1 - Math.exp(-state.loaded / (4 * 1024 * 1024)));
|
|
100
|
+
}
|
|
101
|
+
downloadRatio += (fileRatio * FILE_WEIGHTS[file]) / totalWeight;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const ratio = Math.min(DOWNLOAD_SHARE, Math.max(0, Math.round(downloadRatio * DOWNLOAD_SHARE * 1000) / 1000));
|
|
105
|
+
return {
|
|
106
|
+
ratio,
|
|
107
|
+
loaded,
|
|
108
|
+
total: allTotalsKnown && totalSum > 0 ? totalSum : null,
|
|
109
|
+
stage: "downloading",
|
|
110
|
+
file: activeFile,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
async function readResponseText(response, onChunk) {
|
|
114
|
+
if (!response.body) {
|
|
115
|
+
const text = await response.text();
|
|
116
|
+
onChunk(new TextEncoder().encode(text).byteLength);
|
|
117
|
+
return text;
|
|
118
|
+
}
|
|
119
|
+
const reader = response.body.getReader();
|
|
120
|
+
const decoder = new TextDecoder("utf-8");
|
|
121
|
+
let output = "";
|
|
122
|
+
try {
|
|
123
|
+
for (;;) {
|
|
124
|
+
const { done, value } = await reader.read();
|
|
125
|
+
if (done)
|
|
126
|
+
break;
|
|
127
|
+
if (value) {
|
|
128
|
+
output += decoder.decode(value, { stream: true });
|
|
129
|
+
onChunk(value.byteLength);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
output += decoder.decode();
|
|
133
|
+
return output;
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
reader.releaseLock();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async function readResponseBytes(response, onChunk) {
|
|
140
|
+
if (!response.body) {
|
|
141
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
142
|
+
onChunk(bytes.byteLength);
|
|
143
|
+
return bytes;
|
|
144
|
+
}
|
|
145
|
+
const reader = response.body.getReader();
|
|
146
|
+
const chunks = [];
|
|
147
|
+
let totalLength = 0;
|
|
148
|
+
try {
|
|
149
|
+
for (;;) {
|
|
150
|
+
const { done, value } = await reader.read();
|
|
151
|
+
if (done)
|
|
152
|
+
break;
|
|
153
|
+
if (value) {
|
|
154
|
+
chunks.push(value);
|
|
155
|
+
totalLength += value.byteLength;
|
|
156
|
+
onChunk(value.byteLength);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
reader.releaseLock();
|
|
162
|
+
}
|
|
163
|
+
if (chunks.length === 1)
|
|
164
|
+
return chunks[0];
|
|
165
|
+
const output = new Uint8Array(totalLength);
|
|
166
|
+
let offset = 0;
|
|
167
|
+
for (const chunk of chunks) {
|
|
168
|
+
output.set(chunk, offset);
|
|
169
|
+
offset += chunk.byteLength;
|
|
170
|
+
}
|
|
171
|
+
return output;
|
|
172
|
+
}
|
|
173
|
+
function createEmptyStates() {
|
|
174
|
+
return {
|
|
175
|
+
"lexicon.bin": { loaded: 0, total: null, done: false },
|
|
176
|
+
"morph.bin": { loaded: 0, total: null, done: false },
|
|
177
|
+
"known.tsv": { loaded: 0, total: null, done: false },
|
|
178
|
+
"unigrams.tsv": { loaded: 0, total: null, done: false },
|
|
179
|
+
"bigrams.tsv": { loaded: 0, total: null, done: false },
|
|
180
|
+
"context.onnx": { loaded: 0, total: null, done: false },
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
async function fetchBundle(baseUrl, mode, options = {}) {
|
|
184
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
185
|
+
if (typeof fetchFn !== "function") {
|
|
186
|
+
throw new Error("autr: Bu ortamda fetch işlevi bulunamadı.");
|
|
187
|
+
}
|
|
188
|
+
const resolvedBase = resolveBaseUrl(baseUrl);
|
|
189
|
+
const states = createEmptyStates();
|
|
190
|
+
let activeFiles = [
|
|
191
|
+
...(mode.wantCore ? (mode.forceLegacyTsv ? LEGACY_DATA_FILES : DATA_FILES) : []),
|
|
192
|
+
...(mode.wantContext ? [CONTEXT_MODEL_FILE] : []),
|
|
193
|
+
];
|
|
194
|
+
let lastEmit = 0;
|
|
195
|
+
let maxRatio = 0;
|
|
196
|
+
const emit = (file, force = false) => {
|
|
197
|
+
if (!options.onProgress)
|
|
198
|
+
return;
|
|
199
|
+
const now = Date.now();
|
|
200
|
+
if (!force && now - lastEmit < PROGRESS_THROTTLE_MS)
|
|
201
|
+
return;
|
|
202
|
+
lastEmit = now;
|
|
203
|
+
const summary = summarizeDownload(states, activeFiles, file);
|
|
204
|
+
if (summary.ratio < maxRatio) {
|
|
205
|
+
summary.ratio = maxRatio;
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
maxRatio = summary.ratio;
|
|
209
|
+
}
|
|
210
|
+
options.onProgress(summary);
|
|
211
|
+
};
|
|
212
|
+
emit(undefined, true);
|
|
213
|
+
// Optional manifest.json next to the files, with each file's real size (written by the site's build).
|
|
214
|
+
// Also tells us immediately whether the host serves the binary bundle (lexicon.bin) or legacy TSVs.
|
|
215
|
+
const manifest = await fetchFn(buildFileUrl(resolvedBase, "manifest.json"), {
|
|
216
|
+
signal: options.signal,
|
|
217
|
+
})
|
|
218
|
+
.then((response) => (response.ok ? response.json() : {}))
|
|
219
|
+
.catch(() => ({}));
|
|
220
|
+
const readTracked = async (file, response, readBody) => {
|
|
221
|
+
const size = manifest[file];
|
|
222
|
+
states[file].total = parseContentLength(response) ?? (typeof size === "number" && size > 0 ? size : null);
|
|
223
|
+
emit(file, true);
|
|
224
|
+
const data = await readBody(response, (bytes) => {
|
|
225
|
+
states[file].loaded += bytes;
|
|
226
|
+
emit(file, false);
|
|
227
|
+
});
|
|
228
|
+
states[file].done = true;
|
|
229
|
+
emit(file, true);
|
|
230
|
+
return data;
|
|
231
|
+
};
|
|
232
|
+
const downloadOne = async (file, readBody) => {
|
|
233
|
+
const url = buildFileUrl(resolvedBase, file);
|
|
234
|
+
const response = await fetchFn(url, { signal: options.signal });
|
|
235
|
+
if (!response.ok) {
|
|
236
|
+
throw new Error(`autr: ${file} yüklenemedi (${response.status}) — ${url}`);
|
|
237
|
+
}
|
|
238
|
+
return readTracked(file, response, readBody);
|
|
239
|
+
};
|
|
240
|
+
// A download can be cut off, for example while a service worker installs and fetches the same files on the first
|
|
241
|
+
// visit. A network failure (not an HTTP error) is retried a few times before giving up.
|
|
242
|
+
const downloadWithRetry = async (file, readBody) => {
|
|
243
|
+
for (let attempt = 1;; attempt++) {
|
|
244
|
+
try {
|
|
245
|
+
return await downloadOne(file, readBody);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
const isNetworkFailure = error instanceof TypeError;
|
|
249
|
+
if (!isNetworkFailure || attempt >= DOWNLOAD_ATTEMPTS || options.signal?.aborted)
|
|
250
|
+
throw error;
|
|
251
|
+
states[file].loaded = 0;
|
|
252
|
+
await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
const downloadOptionalMorph = async () => {
|
|
257
|
+
const url = buildFileUrl(resolvedBase, "morph.bin");
|
|
258
|
+
const response = await fetchFn(url, { signal: options.signal });
|
|
259
|
+
if (response.status === 404) {
|
|
260
|
+
states["morph.bin"].total = 0;
|
|
261
|
+
states["morph.bin"].done = true;
|
|
262
|
+
emit("morph.bin", true);
|
|
263
|
+
return undefined;
|
|
264
|
+
}
|
|
265
|
+
if (!response.ok) {
|
|
266
|
+
throw new Error(`autr: morph.bin yüklenemedi (${response.status}) — ${url}`);
|
|
267
|
+
}
|
|
268
|
+
return readTracked("morph.bin", response, readResponseBytes);
|
|
269
|
+
};
|
|
270
|
+
const downloadCore = async () => {
|
|
271
|
+
if (!mode.wantCore)
|
|
272
|
+
return {};
|
|
273
|
+
const manifestHasBinary = typeof manifest["lexicon.bin"] === "number";
|
|
274
|
+
const manifestHasLegacy = !manifestHasBinary && typeof manifest["unigrams.tsv"] === "number";
|
|
275
|
+
if (mode.forceLegacyTsv || manifestHasLegacy) {
|
|
276
|
+
activeFiles = [...LEGACY_DATA_FILES, ...(mode.wantContext ? [CONTEXT_MODEL_FILE] : [])];
|
|
277
|
+
const [unigrams, bigrams, known] = await Promise.all([
|
|
278
|
+
downloadWithRetry("unigrams.tsv", readResponseText),
|
|
279
|
+
downloadWithRetry("bigrams.tsv", readResponseText),
|
|
280
|
+
downloadWithRetry("known.tsv", readResponseText),
|
|
281
|
+
]);
|
|
282
|
+
return { raw: { unigrams, bigrams, known } };
|
|
283
|
+
}
|
|
284
|
+
if (manifestHasBinary) {
|
|
285
|
+
const hasMorph = typeof manifest["morph.bin"] === "number";
|
|
286
|
+
activeFiles = [
|
|
287
|
+
"lexicon.bin",
|
|
288
|
+
...(hasMorph ? ["morph.bin"] : []),
|
|
289
|
+
"known.tsv",
|
|
290
|
+
...(mode.wantContext ? [CONTEXT_MODEL_FILE] : []),
|
|
291
|
+
];
|
|
292
|
+
const [lexicon, morphology, known] = await Promise.all([
|
|
293
|
+
downloadWithRetry("lexicon.bin", readResponseBytes),
|
|
294
|
+
hasMorph ? downloadWithRetry("morph.bin", readResponseBytes) : Promise.resolve(undefined),
|
|
295
|
+
downloadWithRetry("known.tsv", readResponseText),
|
|
296
|
+
]);
|
|
297
|
+
return { binary: { lexicon, morphology, known } };
|
|
298
|
+
}
|
|
299
|
+
// No manifest.json: try lexicon.bin first; if 404, seamlessly fall back to legacy TSV files.
|
|
300
|
+
const lexUrl = buildFileUrl(resolvedBase, "lexicon.bin");
|
|
301
|
+
let lexResponse;
|
|
302
|
+
for (let attempt = 1;; attempt++) {
|
|
303
|
+
try {
|
|
304
|
+
lexResponse = await fetchFn(lexUrl, { signal: options.signal });
|
|
305
|
+
break;
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
const isNetworkFailure = error instanceof TypeError;
|
|
309
|
+
if (!isNetworkFailure || attempt >= DOWNLOAD_ATTEMPTS || options.signal?.aborted)
|
|
310
|
+
throw error;
|
|
311
|
+
await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (lexResponse.status === 404) {
|
|
315
|
+
activeFiles = [...LEGACY_DATA_FILES, ...(mode.wantContext ? [CONTEXT_MODEL_FILE] : [])];
|
|
316
|
+
const [unigrams, bigrams, known] = await Promise.all([
|
|
317
|
+
downloadWithRetry("unigrams.tsv", readResponseText),
|
|
318
|
+
downloadWithRetry("bigrams.tsv", readResponseText),
|
|
319
|
+
downloadWithRetry("known.tsv", readResponseText),
|
|
320
|
+
]);
|
|
321
|
+
return { raw: { unigrams, bigrams, known } };
|
|
322
|
+
}
|
|
323
|
+
if (!lexResponse.ok) {
|
|
324
|
+
throw new Error(`autr: lexicon.bin yüklenemedi (${lexResponse.status}) — ${lexUrl}`);
|
|
325
|
+
}
|
|
326
|
+
// Stream lexicon.bin while fetching morph.bin and known.tsv in parallel.
|
|
327
|
+
const [lexicon, morphology, known] = await Promise.all([
|
|
328
|
+
readTracked("lexicon.bin", lexResponse, readResponseBytes),
|
|
329
|
+
downloadOptionalMorph(),
|
|
330
|
+
downloadWithRetry("known.tsv", readResponseText),
|
|
331
|
+
]);
|
|
332
|
+
return { binary: { lexicon, morphology, known } };
|
|
333
|
+
};
|
|
334
|
+
const contextPromise = mode.wantContext
|
|
335
|
+
? downloadWithRetry(CONTEXT_MODEL_FILE, readResponseBytes)
|
|
336
|
+
.then((bytes) => ({ bytes, error: null }))
|
|
337
|
+
.catch((error) => {
|
|
338
|
+
if (options.signal?.aborted)
|
|
339
|
+
throw error;
|
|
340
|
+
states[CONTEXT_MODEL_FILE].total = states[CONTEXT_MODEL_FILE].loaded;
|
|
341
|
+
states[CONTEXT_MODEL_FILE].done = true;
|
|
342
|
+
emit(CONTEXT_MODEL_FILE, true);
|
|
343
|
+
return { bytes: null, error };
|
|
344
|
+
})
|
|
345
|
+
: Promise.resolve({ bytes: null, error: null });
|
|
346
|
+
const [core, contextResult] = await Promise.all([downloadCore(), contextPromise]);
|
|
347
|
+
return {
|
|
348
|
+
binary: core.binary,
|
|
349
|
+
raw: core.raw,
|
|
350
|
+
contextBytes: contextResult.bytes,
|
|
351
|
+
contextError: contextResult.error,
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/** `baseUrl` altından eski ham TSV dosyalarını (`unigrams.tsv`, `bigrams.tsv`, `known.tsv`) indirir. */
|
|
355
|
+
export async function fetchRawData(baseUrl = DEFAULT_BASE_URL, options = {}) {
|
|
356
|
+
const bundle = await fetchBundle(baseUrl, { wantCore: true, forceLegacyTsv: true, wantContext: false }, options);
|
|
357
|
+
return bundle.raw;
|
|
358
|
+
}
|
|
359
|
+
function parseMorphologyInput(input) {
|
|
360
|
+
if (!input)
|
|
361
|
+
return undefined;
|
|
362
|
+
if (input instanceof Uint8Array)
|
|
363
|
+
return TurkishMorphology.fromBinary(input);
|
|
364
|
+
if (typeof input === "string")
|
|
365
|
+
return TurkishMorphology.fromDictionaries([input]);
|
|
366
|
+
return TurkishMorphology.fromDictionaries(input);
|
|
367
|
+
}
|
|
368
|
+
/** Ham TSV metinlerini motorun kullandığı `Lexicon`, `KnownMisspellings` ve isteğe bağlı `TurkishMorphology` yapılarına dönüştürür. */
|
|
369
|
+
export async function parseRawData(raw, options = {}) {
|
|
370
|
+
const minCount = options.minCount ?? 1;
|
|
371
|
+
const minPair = options.minPair ?? 1;
|
|
372
|
+
const lexicon = Lexicon.fromTsv(raw.unigrams, raw.bigrams, minCount, minPair);
|
|
373
|
+
if (options.yieldToMain)
|
|
374
|
+
await nextTask();
|
|
375
|
+
const known = KnownMisspellings.fromTsv(raw.known);
|
|
376
|
+
const morphology = parseMorphologyInput(raw.morphology);
|
|
377
|
+
return { lexicon, known, morphology };
|
|
378
|
+
}
|
|
379
|
+
/** Sıkıştırılmış ikili sözlük (`lexicon.bin` + `morph.bin` + `known.tsv`) verisini motorun yapılarına dönüştürür. */
|
|
380
|
+
export async function parseBinaryData(binary, options = {}) {
|
|
381
|
+
const lexicon = Lexicon.fromBinary(binary.lexicon);
|
|
382
|
+
if (options.yieldToMain)
|
|
383
|
+
await nextTask();
|
|
384
|
+
const known = KnownMisspellings.fromTsv(binary.known);
|
|
385
|
+
const morphology = binary.morphology ? TurkishMorphology.fromBinary(binary.morphology) : undefined;
|
|
386
|
+
return { lexicon, known, morphology };
|
|
387
|
+
}
|
|
388
|
+
/** Sözlüğü, biçimbilimi (ve istenirse bağlam modelini) indirir, ayrıştırır ve yükleme ilerlemesini bildirir. */
|
|
389
|
+
export async function loadData(options = {}) {
|
|
390
|
+
const wantContext = Boolean(options.context);
|
|
391
|
+
const prebuiltContext = options.contextModel && options.context !== false ? wrapContextModel(options.contextModel) : null;
|
|
392
|
+
const shouldFetchContext = wantContext && !prebuiltContext;
|
|
393
|
+
const shouldFetchCore = !options.data;
|
|
394
|
+
let binaryData;
|
|
395
|
+
let rawData;
|
|
396
|
+
let contextBytes = null;
|
|
397
|
+
let contextDownloadError = null;
|
|
398
|
+
let totalBytes = null;
|
|
399
|
+
let loadedBytes = 0;
|
|
400
|
+
if (options.data) {
|
|
401
|
+
if (isBinaryData(options.data))
|
|
402
|
+
binaryData = options.data;
|
|
403
|
+
else
|
|
404
|
+
rawData = options.data;
|
|
405
|
+
}
|
|
406
|
+
if (!shouldFetchCore && !shouldFetchContext) {
|
|
407
|
+
const encoder = new TextEncoder();
|
|
408
|
+
if (binaryData) {
|
|
409
|
+
loadedBytes =
|
|
410
|
+
binaryData.lexicon.byteLength +
|
|
411
|
+
(binaryData.morphology?.byteLength ?? 0) +
|
|
412
|
+
encoder.encode(binaryData.known).byteLength;
|
|
413
|
+
}
|
|
414
|
+
else if (rawData) {
|
|
415
|
+
loadedBytes =
|
|
416
|
+
encoder.encode(rawData.unigrams).byteLength +
|
|
417
|
+
encoder.encode(rawData.bigrams).byteLength +
|
|
418
|
+
encoder.encode(rawData.known).byteLength;
|
|
419
|
+
}
|
|
420
|
+
totalBytes = loadedBytes;
|
|
421
|
+
}
|
|
422
|
+
else {
|
|
423
|
+
const downloadState = { last: null };
|
|
424
|
+
const bundle = await fetchBundle(options.baseUrl ?? DEFAULT_BASE_URL, { wantCore: shouldFetchCore, wantContext: shouldFetchContext }, {
|
|
425
|
+
fetch: options.fetch,
|
|
426
|
+
signal: options.signal,
|
|
427
|
+
onProgress: (progress) => {
|
|
428
|
+
downloadState.last = progress;
|
|
429
|
+
options.onProgress?.(progress);
|
|
430
|
+
},
|
|
431
|
+
});
|
|
432
|
+
if (shouldFetchCore) {
|
|
433
|
+
binaryData = bundle.binary;
|
|
434
|
+
rawData = bundle.raw;
|
|
435
|
+
}
|
|
436
|
+
contextBytes = bundle.contextBytes;
|
|
437
|
+
contextDownloadError = bundle.contextError;
|
|
438
|
+
if (downloadState.last) {
|
|
439
|
+
loadedBytes = downloadState.last.loaded;
|
|
440
|
+
totalBytes = downloadState.last.total;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
options.onProgress?.({
|
|
444
|
+
ratio: 0.92,
|
|
445
|
+
loaded: loadedBytes,
|
|
446
|
+
total: totalBytes,
|
|
447
|
+
stage: "parsing",
|
|
448
|
+
});
|
|
449
|
+
if (options.yieldToMain)
|
|
450
|
+
await nextTask();
|
|
451
|
+
const parsed = binaryData
|
|
452
|
+
? await parseBinaryData(binaryData, { yieldToMain: options.yieldToMain })
|
|
453
|
+
: await parseRawData(rawData, {
|
|
454
|
+
minCount: options.minCount,
|
|
455
|
+
minPair: options.minPair,
|
|
456
|
+
yieldToMain: options.yieldToMain,
|
|
457
|
+
});
|
|
458
|
+
let contextSession = prebuiltContext;
|
|
459
|
+
if (contextDownloadError !== null) {
|
|
460
|
+
const reason = contextDownloadError instanceof Error ? contextDownloadError.message : String(contextDownloadError);
|
|
461
|
+
options.onWarning?.(`autr: Bağlam modeli (${CONTEXT_MODEL_FILE}) indirilemedi (${reason}); bağlam modeli olmadan devam ediliyor.`);
|
|
462
|
+
}
|
|
463
|
+
else if (contextBytes) {
|
|
464
|
+
options.onProgress?.({
|
|
465
|
+
ratio: 0.96,
|
|
466
|
+
loaded: loadedBytes,
|
|
467
|
+
total: totalBytes,
|
|
468
|
+
stage: "parsing",
|
|
469
|
+
file: CONTEXT_MODEL_FILE,
|
|
470
|
+
});
|
|
471
|
+
if (options.yieldToMain)
|
|
472
|
+
await nextTask();
|
|
473
|
+
try {
|
|
474
|
+
const loader = options.loadContextSession ?? createOnnxContextSession;
|
|
475
|
+
const resolvedWasmPaths = options.wasmPaths !== undefined ? resolveBaseUrl(options.wasmPaths) : undefined;
|
|
476
|
+
contextSession = await loader(contextBytes, { wasmPaths: resolvedWasmPaths });
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
if (options.signal?.aborted)
|
|
480
|
+
throw error;
|
|
481
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
482
|
+
options.onWarning?.(`autr: Bağlam modeli başlatılamadı (${reason}); bağlam modeli olmadan devam ediliyor.`);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
options.onProgress?.({
|
|
486
|
+
ratio: 1,
|
|
487
|
+
loaded: loadedBytes,
|
|
488
|
+
total: totalBytes,
|
|
489
|
+
stage: "ready",
|
|
490
|
+
});
|
|
491
|
+
return {
|
|
492
|
+
...parsed,
|
|
493
|
+
contextSession,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { CAREFUL, type Correction, type Settings } from "../../src/corrector.ts";
|
|
2
|
+
import type { LoadedData } from "./data.ts";
|
|
3
|
+
import type { CheckOptions, ContextSession, Fix, FixKind, FixScope, InspectResult, Mode } from "./types.ts";
|
|
4
|
+
/** Temkinli kip: motorun doğrulanan varsayılan eşikleri. */
|
|
5
|
+
export { CAREFUL };
|
|
6
|
+
/** Dengeli kip: `CAREFUL` ayarından biraz daha cesur eşikler. */
|
|
7
|
+
export declare const BALANCED: Settings;
|
|
8
|
+
/** Motorun iç düzeltme türünü dışarıya açılan anlaşılır Türkçe türe eşler. */
|
|
9
|
+
/**
|
|
10
|
+
* Birleştirme, ayırma ve bağlam modeli kararları komşu kelimelere ya da kelime çiftlerinin sıklığına bakar; iki
|
|
11
|
+
* kelimeyi kapsayan her düzeltme de öyledir ("hiç bir" → "hiçbir"). Geri kalanı yalnızca kelimeye bakar.
|
|
12
|
+
*/
|
|
13
|
+
export declare function correctionScope(correction: Pick<Correction, "kind" | "original">): FixScope;
|
|
14
|
+
export declare function mapCorrectionKind(correction: Pick<Correction, "kind" | "original" | "replacement">): FixKind;
|
|
15
|
+
/** Motorun doğal logaritmik `margin` değerini 0–1 aralığında güven puanına dönüştürür. */
|
|
16
|
+
export declare function marginToConfidence(margin: number): number;
|
|
17
|
+
/** Verilen düzeltmeleri metne uygular. Çakışma veya uyuşmazlık durumunda hata fırlatır. */
|
|
18
|
+
export declare function applyFixes(text: string, fixes: readonly Fix[]): string;
|
|
19
|
+
/** Çekirdek motoru (ve isteğe bağlı bağlam modelini) paket API'si ile sarmalayan çalışma motoru. */
|
|
20
|
+
export declare class TdkaiEngine {
|
|
21
|
+
private readonly corrector;
|
|
22
|
+
private readonly ignored;
|
|
23
|
+
private contextSession;
|
|
24
|
+
private asyncQueue;
|
|
25
|
+
private mode;
|
|
26
|
+
private disposed;
|
|
27
|
+
constructor(data: LoadedData, mode?: Mode, ignored?: Iterable<string>, contextSession?: ContextSession | null);
|
|
28
|
+
get hasContext(): boolean;
|
|
29
|
+
private assertActive;
|
|
30
|
+
setMode(mode: Mode): void;
|
|
31
|
+
ignore(word: string): void;
|
|
32
|
+
unignore(word: string): void;
|
|
33
|
+
private filterCorrections;
|
|
34
|
+
private filterFlags;
|
|
35
|
+
private enqueueAsync;
|
|
36
|
+
check(text: string, options?: CheckOptions): Promise<Fix[]>;
|
|
37
|
+
inspect(text: string, options?: CheckOptions): Promise<InspectResult>;
|
|
38
|
+
dispose(): Promise<void>;
|
|
39
|
+
}
|