RASMUS commited on
Commit
5a33bec
·
verified ·
1 Parent(s): 59c6002

Upload webapp/src/tokenizer.ts with huggingface_hub

Browse files
Files changed (1) hide show
  1. webapp/src/tokenizer.ts +60 -0
webapp/src/tokenizer.ts ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Tokenizer } from '@huggingface/tokenizers'
2
+
3
+ export const SPACE_TOKEN = '[SPACE]'
4
+ export const START_TEXT_TOKEN = 255
5
+ export const STOP_TEXT_TOKEN = 0
6
+
7
+ export type BrowserTokenizer = Tokenizer
8
+
9
+ export function normalizeFinnishText(text: string): string {
10
+ if (text.length === 0) {
11
+ return 'You need to add some text for me to talk.'
12
+ }
13
+
14
+ let normalized = text
15
+ if (normalized[0]?.toLowerCase() === normalized[0] && normalized[0] !== normalized[0]?.toUpperCase()) {
16
+ normalized = normalized[0].toUpperCase() + normalized.slice(1)
17
+ }
18
+
19
+ normalized = normalized.split(/\s+/).join(' ')
20
+
21
+ const punctuationReplacements: Array<[string, string]> = [
22
+ ['...', ', '],
23
+ ['…', ', '],
24
+ [':', ','],
25
+ [' - ', ', '],
26
+ [';', ', '],
27
+ ['—', '-'],
28
+ ['–', '-'],
29
+ [' ,', ','],
30
+ ['“', '"'],
31
+ ['”', '"'],
32
+ ['‘', "'"],
33
+ ['’', "'"],
34
+ ]
35
+
36
+ for (const [from, to] of punctuationReplacements) {
37
+ normalized = normalized.replaceAll(from, to)
38
+ }
39
+
40
+ normalized = normalized.trimEnd()
41
+ const sentenceEnders = new Set(['.', '!', '?', '-', ','])
42
+ if (!sentenceEnders.has(normalized.at(-1) ?? '')) {
43
+ normalized += '.'
44
+ }
45
+
46
+ return normalized
47
+ }
48
+
49
+ export function createTokenizer(tokenizerJson: Record<string, unknown>, tokenizerConfig: Record<string, unknown> = {}): BrowserTokenizer {
50
+ return new Tokenizer(tokenizerJson, tokenizerConfig)
51
+ }
52
+
53
+ export function encodeFinnishText(tokenizer: BrowserTokenizer, text: string): number[] {
54
+ const prepared = normalizeFinnishText(text).replaceAll(' ', SPACE_TOKEN)
55
+ return tokenizer.encode(prepared, { add_special_tokens: false }).ids
56
+ }
57
+
58
+ export function wrapTextTokens(tokenIds: number[]): number[] {
59
+ return [START_TEXT_TOKEN, ...tokenIds, STOP_TEXT_TOKEN]
60
+ }