-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtextgrid.js
More file actions
337 lines (301 loc) · 10.4 KB
/
textgrid.js
File metadata and controls
337 lines (301 loc) · 10.4 KB
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
* textgrid
* https://github.com/OpenSourceFieldlinguistics/PraatTextGridJS
*
* Copyright (c) 2014 OpenSourceFieldLinguistics Contribs
* Licensed under the Apache 2.0 license.
*/
(function(exports) {
'use strict';
var TextGrid = {
};
TextGrid.init = function() {
return "init";
};
var createAnObject = function(lines) {
var json = {},
pieces,
key,
value;
for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) {
pieces = lines[lineIndex].split(" = ");
key = pieces[0].trim().replace(/ /g, "_");
value = pieces[1].trim().replace(/"/g, "");
json[key] = value;
}
return json;
};
TextGrid.textgridToJSON = function(textgrid, assumeTiersAreSpeakers) {
var lines = textgrid.split("\n"),
json = {
items: []
},
line,
lineIndex,
pieces,
items = [],
currentItem = null,
type,
fileName = "Unknown",
fileNames = [],
key,
value,
text;
// console.log("File length " + lines.length);
while (lines.length > 0) {
line = lines.shift();
/* keys at the file level */
if (!line) {
line = lines.shift();
if (!line) {
if (currentItem) {
currentItem.fileName = fileName;
json.items.push(currentItem);
}
currentItem = null;
fileName = "Unknown"; /* reset filename if there is are two empty lines */
console.log("Reset filename if there is are two empty lines");
}
} else if (line.search(/ /) !== 0 && line.search(/\t/) !== 0) {
pieces = line.split(" = ");
if (pieces.length === 2) {
key = pieces[0].trim().replace(/ /g, "_");
value = pieces[1].trim().replace(/"/g, "");
json[key] = value;
if (key === "File_name") {
fileName = value + "";
console.log(" Found a file name " + fileName);
fileNames.push(fileName);
}
}
} else {
/* either point or interval introducers, or keys for items */
if (line.search(/\[[\0-9]+\]/) !== -1) {
pieces = line.split("[");
type = pieces[0].trim();
if (type === "item") {
console.log(" Found an item for " + fileName);
if (currentItem) {
currentItem.fileName = fileName;
json.items.push(currentItem);
}
currentItem = {};
} else if (type === "points") {
var p = createAnObject([lines.shift(), lines.shift()]);
currentItem[type] = currentItem[type] || [];
currentItem[type].push(p);
} else if (type === "intervals") {
var interval = createAnObject([lines.shift(), lines.shift(), lines.shift()]);
currentItem[type] = currentItem[type] || [];
currentItem[type].push(interval);
}
} else {
pieces = line.split(" = ");
if (pieces.length === 2) {
key = pieces[0].trim().replace(/ /g, "_");
value = pieces[1].trim().replace(/"/g, "");
if (key.indexOf(":_size") > -1) {
key = key.replace(":_", "_");
value = parseInt(value, 10);
}
currentItem[key] = value;
}
}
}
}
if (currentItem) {
currentItem.fileName = fileName;
json.items.push(currentItem);
}
json.fileNames = fileNames;
return json;
};
TextGrid.textgridToIGT = function(textgrid, assumeTiersAreSpeakers) {
return this.jsonToIGT(this.textgridToJSON(textgrid, assumeTiersAreSpeakers), assumeTiersAreSpeakers);
};
TextGrid.jsonToIGT = function(json, assumeTiersAreSpeakers) {
var tiersByLength = {};
json.intervalsByXmin = {};
json.intervalsByText = {};
var itemIndex;
var intervalIndex;
var xmin,
xmax,
key,
interval,
fileName,
text,
length,
probablyFromElanWithSpeakerEncodedInTierName = false,
probablyFromElanWithSpeakerEncodedInTierNameCount = 0;
var maximizeFindingTextInAudio = /[ #?!'".,\/\(\)\*\#0-9-]/g;
var tierNames = json.items.map(function(tier) {
if (tier.name.indexOf("@") > -1 /* probably elan tiers */ ) {
tier.speaker = tier.name.substring(tier.name.indexOf("@") + 1).trim();
tier.name = tier.name.substring(0, tier.name.indexOf("@")).trim();
probablyFromElanWithSpeakerEncodedInTierNameCount++;
}
if (assumeTiersAreSpeakers) {
tier.speaker = tier.name;
}
if (tier.name === "silences") {
tier.name = "utterances";
}
return tier.name;
});
// console.log(tierNames);
if (tierNames.length - probablyFromElanWithSpeakerEncodedInTierNameCount === 0) {
probablyFromElanWithSpeakerEncodedInTierName = true;
}
if (!json || !json.items) {
return json;
}
for (itemIndex = 0; itemIndex < json.items.length; itemIndex++) {
tiersByLength[json.items[itemIndex].name] = json.items[itemIndex].intervals_size || json.items[itemIndex].points_size;
if (json.items[itemIndex].intervals) {
for (intervalIndex = 0; intervalIndex < json.items[itemIndex].intervals.length; intervalIndex++) {
xmin = this.marginForConsideringIntervalsMatching(json.items[itemIndex].intervals[intervalIndex].xmin);
xmax = this.marginForConsideringIntervalsMatching(json.items[itemIndex].intervals[intervalIndex].xmax);
interval = json.items[itemIndex].intervals[intervalIndex];
interval.fileName = json.items[itemIndex].fileName;
interval.tierName = json.items[itemIndex].name;
interval.speaker = json.items[itemIndex].speaker;
key = xmin + ":" + xmax;
json.intervalsByXmin[key] = json.intervalsByXmin[key] || [];
json.intervalsByXmin[key].push(interval);
text = interval.text ? interval.text.trim().toLocaleLowerCase().replace(maximizeFindingTextInAudio, "") : "";
if (text) {
// if its the only interval, and it says utterance, put the file name there instead under the assumption that the filename is probably meaningful
if (text === "utterance" && json.items[itemIndex].intervals.length < 3) {
text = interval.fileName;
if (text.indexOf(".") > -1) {
text = text.substring(0, interval.fileName.lastIndexOf("."));
}
text = text.trim().replace(/_/g, " ");
// console.log("text replaced with filename. " + text);
interval.text = text;
}
json.intervalsByText[text] = json.intervalsByText[text] || [];
length = json.intervalsByText[text].length;
json.intervalsByText[text][length] = interval;
}
//json.intervalsByXmin[key].push({
//text: interval.text,
//tierName: tierName
//});
//json.intervalsByXmin[xmin + ":" + xmax].push({
//tierName: interval.text
//});
}
}
}
// this.printIGT(json.intervalsByXmin);
json.probablyFromElanWithSpeakerEncodedInTierName = probablyFromElanWithSpeakerEncodedInTierName;
json.isIGTNestedOrAlignedOrBySpeaker = this.isIGTNestedOrAlignedOrBySpeaker(json);
return json;
};
TextGrid.isIGTNestedOrAlignedOrBySpeaker = function(json) {
var intervals = json.intervalsByXmin;
var histogram = {},
bin,
intervalKey,
totalPotentialIGTIntervals = 0,
probablyBySpeaker = false,
probablyAligned = false;
for (var tier in json.items) {
if (json.items.hasOwnProperty(tier) && json.items[tier].speaker) {
probablyBySpeaker = true;
}
}
for (intervalKey in intervals) {
histogram[intervals[intervalKey].length] = histogram[intervals[intervalKey].length] ? histogram[intervals[intervalKey].length] + 1 : 1;
totalPotentialIGTIntervals++;
}
/* Normalize the histogram */
for (bin in histogram) {
histogram[bin] = histogram[bin] / totalPotentialIGTIntervals;
if (bin > 1 && histogram[bin] > 0.10) {
probablyAligned = true;
}
// console.log(histogram[bin]);
}
// If there are more than 4 files, they are probably not IGT across files.
if (json.fileNames && json.fileNames.length > 4) {
probablyAligned = false;
}
// console.log(histogram);
// console.log("probably aligned " + probablyAligned);
return {
histogram: histogram,
probablyAligned: probablyAligned,
probablyBySpeaker: probablyBySpeaker
};
};
TextGrid.marginForConsideringIntervalsMatching = function(value, optionalMillisecond) {
if (optionalMillisecond) {
optionalMillisecond = 100 / optionalMillisecond;
} else {
optionalMillisecond = 100 / 20;
}
return (Math.round(value * optionalMillisecond) / optionalMillisecond).toFixed(2);
};
TextGrid.printIGT = function(igtIntervalsJSON) {
var mapper = function(interval) {
return interval.xmin + "," + interval.xmax + "," + interval.text;
};
for (var interval in igtIntervalsJSON) {
console.log(interval);
if (igtIntervalsJSON.hasOwnProperty(interval)) {
console.log(igtIntervalsJSON[interval].map(mapper));
}
}
};
TextGrid.jsonToTextgrid = function(json) {
var textgrid = '';
// 写入文件头
textgrid += 'File type = "ooTextFile"\n';
textgrid += 'Object class = "TextGrid"\n\n';
// 写入基本属性
textgrid += 'xmin = ' + (json.xmin || 0) + '\n';
textgrid += 'xmax = ' + (json.xmax || 0) + '\n';
textgrid += 'tiers? <exists>\n';
textgrid += 'size = ' + (json.items ? json.items.length : 0) + '\n';
textgrid += 'item []:\n';
// 处理每个层级
if (json.items) {
for (var i = 0; i < json.items.length; i++) {
var item = json.items[i];
// 写入层级头
textgrid += ' item [' + (i + 1) + ']:\n';
// 写入层级属性
textgrid += ' class = "' + (item.class || 'IntervalTier') + '"\n';
textgrid += ' name = "' + (item.name || '') + '"\n';
textgrid += ' xmin = ' + (item.xmin || 0) + '\n';
textgrid += ' xmax = ' + (item.xmax || 0) + '\n';
// 处理区间层级
if (item.class === 'IntervalTier' && item.intervals) {
textgrid += ' intervals: size = ' + item.intervals.length + '\n';
for (var j = 0; j < item.intervals.length; j++) {
var interval = item.intervals[j];
textgrid += ' intervals [' + (j + 1) + ']:\n';
textgrid += ' xmin = ' + (interval.xmin || 0) + '\n';
textgrid += ' xmax = ' + (interval.xmax || 0) + '\n';
textgrid += ' text = "' + (interval.text || '') + '"\n';
}
}
// 处理点层级
else if (item.class === 'TextTier' && item.points) {
textgrid += ' points: size = ' + item.points.length + '\n';
for (var k = 0; k < item.points.length; k++) {
var point = item.points[k];
textgrid += ' points [' + (k + 1) + ']:\n';
textgrid += ' number = ' + (point.number || 0) + '\n';
textgrid += ' text = "' + (point.text || '') + '"\n';
}
}
}
}
return textgrid;
};
exports.TextGrid = TextGrid;
}(typeof exports === "object" && exports || this));