-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
signwriting-translation.service.ts
149 lines (122 loc) · 4.61 KB
/
signwriting-translation.service.ts
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
import {Injectable} from '@angular/core';
import {catchError, from, Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {AssetsService} from '../../core/services/assets/assets.service';
import {filter, map} from 'rxjs/operators';
import {ComlinkWorkerInterface, ModelRegistry, TranslationResponse} from '@sign-mt/browsermt';
type TranslationDirection = 'spoken-to-signed' | 'signed-to-spoken';
@Injectable({
providedIn: 'root',
})
export class SignWritingTranslationService {
worker: ComlinkWorkerInterface;
loadedModel: string;
constructor(private http: HttpClient, private assets: AssetsService) {}
async initWorker() {
if (this.worker) {
return;
}
const {createBergamotWorker} = await import(/* webpackChunkName: "@sign-mt/browsermt" */ '@sign-mt/browsermt');
this.worker = createBergamotWorker('/browsermt/worker.js');
await this.worker.importBergamotWorker('bergamot-translator-worker.js', 'bergamot-translator-worker.wasm');
}
async createModelRegistry(modelPath: string) {
const modelRegistry = {};
const modelFiles = await this.assets.getDirectory(modelPath);
for (const [name, path] of modelFiles.entries()) {
const fileType = name.split('.').shift();
modelRegistry[fileType] = {name: path, size: 0, estimatedCompressedSize: 0, modelType: 'prod'};
}
return modelRegistry;
}
async loadOfflineModel(direction: TranslationDirection, from: string, to: string) {
const modelName = `${from}${to}`;
if (this.loadedModel === modelName) {
return;
}
const modelPath = `models/browsermt/${direction}/${from}-${to}/`;
const state = this.assets.stat(modelPath);
if (!state.exists) {
throw new Error(`Model '${modelPath}' not found locally`);
}
const modelRegistry = {[modelName]: await this.createModelRegistry(modelPath)} as ModelRegistry;
await this.initWorker();
await this.worker.loadModel(from, to, modelRegistry);
this.loadedModel = modelName;
}
async translateOffline(
direction: TranslationDirection,
text: string,
from: string,
to: string
): Promise<TranslationResponse> {
await this.loadOfflineModel(direction, from, to);
let translations = await this.worker.translate(from, to, [text], [{isHtml: false}]);
if (typeof translations[0] === 'string') {
translations = translations.map((t: any) => ({text: t}));
}
translations = translations.map(({text}) => ({text: this.postProcessSignWriting(text)}));
return translations[0];
}
translateOnline(
direction: TranslationDirection,
text: string,
sentences: string[],
from: string,
to: string
): Observable<TranslationResponse> {
// TODO use the new API (when bergamot model is trained)
// const query = new URLSearchParams({from, to, text});
// return this.http.get<TranslationResponse>(`https://sign.mt/api/${direction}?${query}`);'
const url = 'https://sign.mt/api/spoken-text-to-signwriting';
const body = {
data: {
texts: sentences.map(s => s.trim()),
spoken_language: from,
signed_language: to,
},
};
interface SpokenToSignWritingResponse {
result: {
input: string[];
output: string[];
};
}
return this.http
.post<SpokenToSignWritingResponse>(url, body)
.pipe(map(res => ({text: res.result.output.join(' ')})));
}
translateSpokenToSignWriting(
text: string,
sentences: string[],
spokenLanguage: string,
signedLanguage: string
): Observable<TranslationResponse> {
const direction: TranslationDirection = 'spoken-to-signed';
const offlineSpecific = () => {
const newText = `${this.preProcessSpokenText(text)}`;
return from(this.translateOffline(direction, newText, spokenLanguage, signedLanguage));
};
const offlineGeneric = () => {
const newText = `$${spokenLanguage} $${signedLanguage} ${this.preProcessSpokenText(text)}`;
return from(this.translateOffline(direction, newText, 'spoken', 'signed'));
};
const online = () => this.translateOnline(direction, text, sentences, spokenLanguage, signedLanguage);
return offlineSpecific().pipe(
catchError(offlineGeneric),
filter(() => !('navigator' in globalThis) || navigator.onLine),
catchError(online)
);
}
preProcessSpokenText(text: string) {
return text.replace('\n', ' ');
}
postProcessSignWriting(text: string) {
// remove all tokens that start with a $
text = text.replace(/\$[^\s]+/g, '');
// space signs correctly
text = text.replace(/ /g, '');
text = text.replace(/(\d)M/g, '$1 M');
return text;
}
}