File size: 9,546 Bytes
dbc1132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25633dd
 
 
 
 
 
 
 
 
dbc1132
 
 
 
 
 
25633dd
dbc1132
 
 
 
 
 
 
 
 
 
25633dd
 
 
dbc1132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25633dd
 
 
dbc1132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/**
 * Punctuation and Capitalization using ONNX
 * - English: Full punctuation + capitalization (1-800-BAD-CODE model)
 * - Other languages (DE, FR, IT, NL, ES, PT): Punctuation only (oliverguhr multilingual model)
 */

// English model (punctuation + capitalization)
let pcsSession = null;
let pcsVocab = null;
let pcsVocabReverse = null;

// Multilingual model (punctuation only)
let multilingualSession = null;
let multilingualTokenizer = null;

const PCS_CONFIG = {
    preLabels: ["<NULL>", "¿"],
    postLabels: ["<NULL>", "<ACRONYM>", ".", ",", "?"],
    unkId: 0,
    bosId: 1,
    eosId: 2,
    padId: 3,
};

// Multilingual model label mapping
const MULTILINGUAL_LABELS = {
    0: "",      // No punctuation
    1: ".",     // Period
    2: ",",     // Comma
    3: "?",     // Question mark
    4: "-",     // Hyphen
    5: ":",     // Colon
};

// Languages supported by multilingual model
const MULTILINGUAL_LANGS = ['de', 'fr', 'it', 'nl', 'es', 'pt'];

// Load the English punctuator model and vocab
async function cachedFetch(url) {
    const cache = await caches.open('granite-speech-local-models');
    const cached = await cache.match(url);
    if (cached) return cached;
    const response = await fetch(url);
    if (response.ok) await cache.put(url, response.clone());
    return response;
}

async function loadEnglishPunctuator() {
    if (pcsSession) return;

    console.log('Loading English punctuator model...');

    // Load vocab
    const vocabResponse = await cachedFetch('./pcs_vocab.json');
    const vocabData = await vocabResponse.json();
    pcsVocab = vocabData.vocab;

    // Create reverse vocab (id -> piece)
    pcsVocabReverse = {};
    for (const [piece, id] of Object.entries(pcsVocab)) {
        pcsVocabReverse[id] = piece;
    }

    // Load ONNX model
    const modelResponse = await cachedFetch('./punct_cap_seg_en.onnx');
    const buffer = await modelResponse.arrayBuffer();
    pcsSession = await ort.InferenceSession.create(buffer, {
        executionProviders: ['wasm'],
    });

    console.log('English punctuator model loaded');
}

// Load the multilingual punctuator model
async function loadMultilingualPunctuator() {
    if (multilingualSession) return;

    console.log('Loading multilingual punctuator model...');

    // Load tokenizer from transformers.js
    const { AutoTokenizer } = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.4.2');
    multilingualTokenizer = await AutoTokenizer.from_pretrained('oliverguhr/fullstop-punctuation-multilingual-base');

    // Load ONNX model
    const modelResponse = await cachedFetch('./punct_multilingual_q8.onnx');
    const buffer = await modelResponse.arrayBuffer();
    multilingualSession = await ort.InferenceSession.create(buffer, {
        executionProviders: ['wasm'],
    });

    console.log('Multilingual punctuator model loaded');
}

// Simple Unigram tokenizer for English model (greedy longest match)
function tokenizeEnglish(text) {
    const normalized = text.toLowerCase().replace(/ /g, '▁');
    const tokens = [];
    let i = 0;

    // Add BOS
    tokens.push(PCS_CONFIG.bosId);

    // Prepend ▁ for first word
    let remaining = '▁' + normalized;

    while (remaining.length > 0) {
        let found = false;
        // Try longest match first
        for (let len = Math.min(remaining.length, 20); len > 0; len--) {
            const piece = remaining.substring(0, len);
            if (pcsVocab[piece] !== undefined) {
                tokens.push(pcsVocab[piece]);
                remaining = remaining.substring(len);
                found = true;
                break;
            }
        }
        if (!found) {
            // Unknown character, use UNK and skip
            tokens.push(PCS_CONFIG.unkId);
            remaining = remaining.substring(1);
        }
    }

    // Add EOS
    tokens.push(PCS_CONFIG.eosId);

    return tokens;
}

// Apply punctuation and capitalization for English
async function applyEnglishPunctuation(text) {
    await loadEnglishPunctuator();

    // Tokenize
    const tokenIds = tokenizeEnglish(text);

    // Run inference
    const inputTensor = new ort.Tensor('int64', BigInt64Array.from(tokenIds.map(BigInt)), [1, tokenIds.length]);
    const outputs = await pcsSession.run({ input_ids: inputTensor });

    const prePreds = outputs.pre_preds.data;
    const postPreds = outputs.post_preds.data;
    const capPreds = outputs.cap_preds.data;
    const segPreds = outputs.seg_preds.data;

    // Decode: skip BOS (index 0) and EOS (last index)
    const numTokens = tokenIds.length - 2;
    const result = [];
    let currentSentence = [];

    for (let i = 0; i < numTokens; i++) {
        const tokenId = tokenIds[i + 1];
        const token = pcsVocabReverse[tokenId] || '';
        const outputIdx = i + 1;

        // Handle word boundary
        if (token.startsWith('▁') && currentSentence.length > 0) {
            currentSentence.push(' ');
        }

        // Process each character in token
        const charStart = token.startsWith('▁') ? 1 : 0;
        for (let j = charStart; j < token.length; j++) {
            let char = token[j];

            // Pre-punctuation (e.g., inverted question mark)
            if (j === charStart && prePreds[outputIdx] === 1) {
                currentSentence.push(PCS_CONFIG.preLabels[1]);
            }

            // Capitalization - capPreds is [batch, seq, 16]
            const capOffset = outputIdx * 16 + j;
            if (capPreds[capOffset]) {
                char = char.toUpperCase();
            }

            currentSentence.push(char);

            // Post-punctuation
            const postLabel = postPreds[outputIdx];
            if (postLabel === 1) {  // ACRONYM
                currentSentence.push('.');
            } else if (j === token.length - 1 && postLabel > 1) {
                currentSentence.push(PCS_CONFIG.postLabels[postLabel]);
            }
        }

        // Sentence boundary
        if (segPreds[outputIdx]) {
            result.push(currentSentence.join(''));
            currentSentence = [];
        }
    }

    if (currentSentence.length > 0) {
        result.push(currentSentence.join(''));
    }

    return result.join(' ');
}

// Apply punctuation only for other languages (multilingual model)
async function applyMultilingualPunctuation(text) {
    await loadMultilingualPunctuator();

    // Tokenize using transformers.js tokenizer
    const encoded = await multilingualTokenizer(text, {
        return_tensors: false,
        padding: false,
        truncation: true,
        max_length: 512,
    });

    const inputIds = encoded.input_ids;
    const attentionMask = encoded.attention_mask;

    // Run inference
    const inputIdsTensor = new ort.Tensor('int64', BigInt64Array.from(inputIds.map(BigInt)), [1, inputIds.length]);
    const attentionMaskTensor = new ort.Tensor('int64', BigInt64Array.from(attentionMask.map(BigInt)), [1, attentionMask.length]);

    const outputs = await multilingualSession.run({
        input_ids: inputIdsTensor,
        attention_mask: attentionMaskTensor,
    });

    const logits = outputs.logits.data;
    const numLabels = 6;

    // Get predictions (argmax over logits)
    const predictions = [];
    for (let i = 0; i < inputIds.length; i++) {
        let maxIdx = 0;
        let maxVal = logits[i * numLabels];
        for (let j = 1; j < numLabels; j++) {
            if (logits[i * numLabels + j] > maxVal) {
                maxVal = logits[i * numLabels + j];
                maxIdx = j;
            }
        }
        predictions.push(maxIdx);
    }

    // Decode tokens back to text with punctuation
    const tokens = multilingualTokenizer.model.convert_ids_to_tokens(inputIds);
    const result = [];

    for (let i = 0; i < tokens.length; i++) {
        const token = tokens[i];

        // Skip special tokens
        if (token === '<s>' || token === '</s>' || token === '<pad>') {
            continue;
        }

        // Handle subword tokens (▁ prefix indicates start of new word)
        if (token.startsWith('▁')) {
            if (result.length > 0) {
                result.push(' ');
            }
            result.push(token.substring(1));
        } else {
            result.push(token);
        }

        // Add punctuation after token
        const punct = MULTILINGUAL_LABELS[predictions[i]];
        if (punct) {
            result.push(punct);
        }
    }

    return result.join('');
}

// Main entry point - routes to appropriate model based on language
async function applyPunctuation(text, lang = null) {
    if (!text || text.trim().length === 0) return text;

    // If language specified and supported by multilingual model, use it
    if (lang && MULTILINGUAL_LANGS.includes(lang)) {
        try {
            return await applyMultilingualPunctuation(text);
        } catch (error) {
            console.warn('Multilingual punctuation failed, returning original:', error);
            return text;
        }
    }

    // Default to English model
    try {
        return await applyEnglishPunctuation(text);
    } catch (error) {
        console.warn('English punctuation failed, returning original:', error);
        return text;
    }
}

// Preload English model (called during init)
async function loadPunctuator() {
    await loadEnglishPunctuator();
}

// Export for use in app.js
window.applyPunctuation = applyPunctuation;
window.loadPunctuator = loadPunctuator;
window.MULTILINGUAL_PUNCT_LANGS = MULTILINGUAL_LANGS;