summaryrefslogtreecommitdiff
path: root/tnet_io/KaldiLib/Labels.cc
blob: 8b04cdec81af413fa03939d48c33474fd5ab3208 (plain) (blame)
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
#include "Labels.h"
#include "Timer.h"
#include "Error.h"
#include <cstdio>
#include <sstream>


namespace TNet {


    ////////////////////////////////////////////////////////////////////////
    // Class LabelRepository::
    void
        LabelRepository::
        Init(const char* pLabelMlfFile, const char* pOutputLabelMapFile, const char* pLabelDir, const char* pLabelExt) {
            InitMap(pLabelMlfFile, pOutputLabelMapFile, pLabelDir, pLabelExt);
        }
    void
        LabelRepository::
        InitExt(const char* pLabelMlfFile, const char* fmt, const char *arg, const char* pLabelDir, const char* pLabelExt) {
            if (strcmp(fmt, "map") == 0)
            {
                InitMap(pLabelMlfFile, arg, pLabelDir, pLabelExt);
                mlf_fmt = MAP;
            }
            else if (strcmp(fmt, "raw") == 0)
            {
                InitRaw(pLabelMlfFile, arg, pLabelDir, pLabelExt);
                mlf_fmt = RAW;
            }
        }

    void
        LabelRepository::
        InitMap(const char* pLabelMlfFile, const char* pOutputLabelMapFile, const char* pLabelDir, const char* pLabelExt)
        {
            assert(NULL != pLabelMlfFile);
            assert(NULL != pOutputLabelMapFile);

            // initialize the label streams
            delete mpLabelStream; //if NULL, does nothing
            delete _mpLabelStream;
            _mpLabelStream = new std::ifstream(pLabelMlfFile);
            mpLabelStream  = new IMlfStream(*_mpLabelStream);

            // Label stream is initialized, just test it
            if(!mpLabelStream->good()) 
                Error(std::string("Cannot open Label MLF file: ")+pLabelMlfFile);

            // Index the labels (good for randomized file lists)
            Timer tim; tim.Start();
            mpLabelStream->Index();
            tim.End(); mIndexTime += tim.Val(); 

            // Read the state-label to state-id map
            ReadOutputLabelMap(pOutputLabelMapFile);

            // Store the label dir/ext
            mpLabelDir = pLabelDir;
            mpLabelExt = pLabelExt;
        }

    void
        LabelRepository::
        InitRaw(const char* pLabelMlfFile, const char *arg, const char* pLabelDir, const char* pLabelExt)
        {
            assert(NULL != pLabelMlfFile);
            std::istringstream iss(arg); 
            size_t dim;
            iss >> dim;
            if (iss.fail() || dim <= 0)
                PError("[lab] malformed dimension specification");
            raw_dim = dim;
            // initialize the label streams
            delete mpLabelStream; //if NULL, does nothing
            delete _mpLabelStream;
            _mpLabelStream = new std::ifstream(pLabelMlfFile);
            mpLabelStream  = new IMlfStream(*_mpLabelStream);

            // Label stream is initialized, just test it
            if(!mpLabelStream->good()) 
                Error(std::string("Cannot open Label MLF file: ")+pLabelMlfFile);

            // Index the labels (good for randomized file lists)
            Timer tim; tim.Start();
            mpLabelStream->Index();
            tim.End(); mIndexTime += tim.Val(); 

            // Read the state-label to state-id map
            //ReadOutputLabelMap(pOutputLabelMapFile);

            // Store the label dir/ext
            mpLabelDir = pLabelDir;
            mpLabelExt = pLabelExt;
        }


    void 
        LabelRepository::
        GenDesiredMatrix(BfMatrix& rDesired, size_t nFrames, size_t sourceRate, const char* pFeatureLogical, bool has_vad)
        {
            //timer
            Timer tim; tim.Start();

            //Get the MLF stream reference...
            IMlfStream& mLabelStream = *mpLabelStream;
            //Build the file name of the label
            MakeHtkFileName(mpLabelFile, pFeatureLogical, mpLabelDir, mpLabelExt);

            //Find block in MLF file
            mLabelStream.Open(mpLabelFile);
            if(!mLabelStream.good()) {
                Error(std::string("Cannot open label MLF record: ") + mpLabelFile);
            }


            //resize the matrix
            if(nFrames < 1) {
                KALDI_ERR << "Number of frames:" << nFrames << " is lower than 1!!!\n"
                    << pFeatureLogical;
            }
            int label_map_size = mLabelMap.size();
            rDesired.Init(nFrames, label_map_size + (has_vad ? 2 : 0), true); //true: Zero()

            //aux variables
            std::string line, state;
            unsigned long long beg, end;
            size_t state_index;
            size_t trunc_frames = 0;
            TagToIdMap::iterator it;
            int vad_state;

            //parse the label file
            while(!mLabelStream.eof()) {
                std::getline(mLabelStream, line);
                if(line == "") continue; //skip newlines/comments from MLF
                if(line[0] == '#') continue;

                std::istringstream& iss = mGenDesiredMatrixStream;
                iss.clear();
                iss.str(line);

                //parse the line
                //begin
                iss >> std::ws >> beg;
                if(iss.fail()) { 
                    KALDI_ERR << "Cannot parse column 1 (begin)\n"
                        << "line: " << line << "\n"
                        << "file: " << mpLabelFile << "\n";
                }
                //end
                iss >> std::ws >> end;
                if(iss.fail()) { 
                    KALDI_ERR << "Cannot parse column 2 (end)\n"
                        << "line: " << line << "\n"
                        << "file: " << mpLabelFile << "\n";
                }
                //state tag
                iss >> std::ws >> state;
                if(iss.fail()) { 
                    KALDI_ERR << "Cannot parse column 3 (state_tag)\n"
                        << "line: " << line << "\n"
                        << "file: " << mpLabelFile << "\n";
                }

                if (has_vad) /* an additional column for vad */
                {
                    iss >> std::ws >> vad_state;
                    if(iss.fail()) { 
                        KALDI_ERR << "Cannot parse column 4 (vad_state)\n"
                            << "line: " << line << "\n"
                            << "file: " << mpLabelFile << "\n";
                    }
                }

                //fprintf(stderr, "Parsed: %lld %lld %s\n", beg, end, state.c_str());

                //divide beg/end by sourceRate and round up to get interval of frames
                beg = (beg+sourceRate/2)/sourceRate;
                end = (end+sourceRate/2)/sourceRate; 
                //beg = (int)round(beg / (double)sourceRate);
                //end = (int)round(end / (double)sourceRate); 

                //find the state id
                it = mLabelMap.find(state);
                if(mLabelMap.end() == it) {
                    Error(std::string("Unknown state tag: '") + state + "' file:'" + mpLabelFile);
                }
                state_index = it->second;

                // Fill the desired matrix
                for(unsigned long long frame=beg; frame<end; frame++) { 
                    //don't write after matrix... (possible longer transcript than feature file)
                    if(frame >= (int)rDesired.Rows()) { trunc_frames++; continue; }

                    //check the next frame is empty:
                    if(0.0 != rDesired[frame].Sum()) {
                        //ERROR!!!
                        //find out what was previously filled!!!
                        BaseFloat max = rDesired[frame].Max();
                        int idx = -1;
                        for(int i=0; i<(int)rDesired[frame].Dim(); i++) { 
                            if(rDesired[frame][i] == max) idx = i; 
                        }
                        for(it=mLabelMap.begin(); it!=mLabelMap.end(); ++it) {
                            if((int)it->second == idx) break;
                        }
                        std::string state_prev = "error";
                        if(it != mLabelMap.end()) {
                            state_prev = it->first;
                        }
                        //print the error message
                        std::ostringstream os; 
                        os << "Frame already assigned to other state, "
                            << " file: " << mpLabelFile 
                            << " frame: " << frame
                            << " nframes: " << nFrames 
                            << " sum: " << rDesired[frame].Sum()  
                            << " previously assigned to: " << state_prev << "(" << idx << ")" 
                            << " now should be assigned to: " << state << "(" << state_index << ")"
                            << "\n";
                        Error(os.str());
                    }

                    //fill the row
                    rDesired[(size_t)frame][state_index] = 1.0f;
                    if (has_vad)
                        rDesired[(size_t)frame][label_map_size + !!vad_state] = 1.0f;
                }
            }

            mLabelStream.Close();

            //check the desired matrix (rows sum up to 1.0)
            for(size_t i=0; i<rDesired.Rows(); ++i) {
                float desired_row_sum = rDesired[i].Sum();
                if(!desired_row_sum == 1.0) {
                    std::ostringstream os;
                    os << "Desired vector sum isn't 1.0, "
                        << " file: " << mpLabelFile 
                        << " row: " << i 
                        << " nframes: " << nFrames 
                        << " content: " << rDesired[i] 
                        << " sum: " << desired_row_sum  << "\n";
                    Error(os.str());
                }
            }

            //warning when truncating many frames
            if(trunc_frames > 10) {
                std::ostringstream os;
                os << "Truncated frames: " << trunc_frames 
                    << " Check sourcerate in features and validity of labels\n";
                Warning(os.str());
            }

            //timer
            tim.End(); mGenDesiredMatrixTime += tim.Val();
        }



    void
        LabelRepository::
        ReadOutputLabelMap(const char* file)
        {
            assert(mLabelMap.size() == 0);
            int i = 0;
            std::string state_tag;
            std::ifstream in(file);
            if(!in.good())
                Error(std::string("Cannot open OutputLabelMapFile: ")+file);

            in >> std::ws;
            while(!in.eof()) {
                in >> state_tag;
                in >> std::ws;
                assert(mLabelMap.find(state_tag) == mLabelMap.end());
                mLabelMap[state_tag] = i++;
            }

            in.close();
            assert(mLabelMap.size() > 0);
        }


    void 
        LabelRepository::
        GenDesiredMatrixExt(std::vector<BfMatrix>& rDesired, size_t nFrames, size_t sourceRate, const char* pFeatureLogical) {
            switch (mlf_fmt)
            {
                case MAP: GenDesiredMatrixExtMap(rDesired, nFrames, sourceRate, pFeatureLogical);
                            break;
                case RAW: GenDesiredMatrixExtRaw(rDesired, nFrames, sourceRate, pFeatureLogical);
                          break;
                default: assert(0);
            }
        }

    void 
        LabelRepository::
        GenDesiredMatrixExtMap(std::vector<BfMatrix>& rDesired, size_t nFrames, size_t sourceRate, const char* pFeatureLogical)
        {
            //timer
            Timer tim; tim.Start();

            //Get the MLF stream reference...
            IMlfStream& mLabelStream = *mpLabelStream;
            //Build the file name of the label
            MakeHtkFileName(mpLabelFile, pFeatureLogical, mpLabelDir, mpLabelExt);

            //Find block in MLF file
            mLabelStream.Open(mpLabelFile);
            if(!mLabelStream.good()) {
                Error(std::string("Cannot open label MLF record: ") + mpLabelFile);
            }


            //resize the matrix
            if(nFrames < 1) {
                KALDI_ERR << "Number of frames:" << nFrames << " is lower than 1!!!\n"
                    << pFeatureLogical;
            }

            size_t prev = rDesired.size();
            rDesired.resize(prev + 1, BfMatrix()); /* state + vad */
            int label_map_size = mLabelMap.size();
            rDesired[prev].Init(nFrames, 1, true); //true: Zero()

            //aux variables
            std::string line, state;
            unsigned long long beg, end;
            size_t state_index;
            size_t trunc_frames = 0;
            TagToIdMap::iterator it;

            //parse the label file
            while(!mLabelStream.eof()) {
                std::getline(mLabelStream, line);
                if(line == "") continue; //skip newlines/comments from MLF
                if(line[0] == '#') continue;

                std::istringstream& iss = mGenDesiredMatrixStream;
                iss.clear();
                iss.str(line);

                //parse the line
                //begin
                iss >> std::ws >> beg;
                if(iss.fail()) { 
                    KALDI_ERR << "Cannot parse column 1 (begin)\n"
                        << "line: " << line << "\n"
                        << "file: " << mpLabelFile << "\n";
                }
                //end
                iss >> std::ws >> end;
                if(iss.fail()) { 
                    KALDI_ERR << "Cannot parse column 2 (end)\n"
                        << "line: " << line << "\n"
                        << "file: " << mpLabelFile << "\n";
                }
                //state tag
                iss >> std::ws >> state;
                if(iss.fail()) { 
                    KALDI_ERR << "Cannot parse column 3 (state_tag)\n"
                        << "line: " << line << "\n"
                        << "file: " << mpLabelFile << "\n";
                }


                //fprintf(stderr, "Parsed: %lld %lld %s\n", beg, end, state.c_str());

                //divide beg/end by sourceRate and round up to get interval of frames
                beg = (beg+sourceRate/2)/sourceRate;
                if (end == (unsigned long long)-1)
                    end = rDesired[prev].Rows();
                else
                    end = (end+sourceRate/2)/sourceRate; 
                //beg = (int)round(beg / (double)sourceRate);
                //end = (int)round(end / (double)sourceRate); 

                //find the state id
                it = mLabelMap.find(state);
                if(mLabelMap.end() == it) {
                    Error(std::string("Unknown state tag: '") + state + "' file:'" + mpLabelFile);
                }
                state_index = it->second;

                // Fill the desired matrix
                for(unsigned long long frame=beg; frame<end; frame++) { 
                    //don't write after matrix... (possible longer transcript than feature file)
                    if(frame >= (int)rDesired[prev].Rows()) { trunc_frames++; continue; }

                    //check the next frame is empty:
                    if(0.0 != rDesired[prev][frame][0]) {
                        //ERROR!!!
                        //find out what was previously filled!!!
                        /*
                        BaseFloat max = rDesired[prev][frame].Max();
                        int idx = -1;
                        for(int i=0; i<(int)rDesired[prev][frame].Dim(); i++) { 
                            if(rDesired[prev][frame][i] == max) idx = i; 
                        }
                        */
                        BaseFloat max = rDesired[prev][frame][0];
                        int idx = round(max);
                        for(it=mLabelMap.begin(); it!=mLabelMap.end(); ++it) {
                            if((int)it->second == idx) break;
                        }
                        std::string state_prev = "error";
                        if(it != mLabelMap.end()) {
                            state_prev = it->first;
                        }
                        //print the error message
                        std::ostringstream os; 
                        os << "Frame already assigned to other state, "
                            << " file: " << mpLabelFile 
                            << " frame: " << frame
                            << " nframes: " << nFrames 
                            << " sum: " << max
                            << " previously assigned to: " << state_prev << "(" << idx << ")" 
                            << " now should be assigned to: " << state << "(" << state_index << ")"
                            << "\n";
                        Error(os.str());
                    }

                    //fill the row
                    //rDesired[prev][(size_t)frame][state_index] = 1.0f;
                    rDesired[prev][(size_t)frame][0] = state_index;
                }
            }

            mLabelStream.Close();
            /*
            //check the desired matrix (rows sum up to 1.0)
            for(size_t i=0; i<rDesired[prev].Rows(); ++i) {
                float desired_row_sum = rDesired[prev][i].Sum();
                if(!desired_row_sum == 1.0) {
                    std::ostringstream os;
                    os << "Desired vector sum isn't 1.0, "
                        << " file: " << mpLabelFile 
                        << " row: " << i 
                        << " nframes: " << nFrames 
                        << " content: " << rDesired[prev][i] 
                        << " sum: " << desired_row_sum  << "\n";
                    Error(os.str());
                }
            }
            */

            //warning when truncating many frames
            if(trunc_frames > 10) {
                std::ostringstream os;
                os << "Truncated frames: " << trunc_frames 
                    << " Check sourcerate in features and validity of labels\n";
                Warning(os.str());
            }

            //timer
            tim.End(); mGenDesiredMatrixTime += tim.Val();
        }

    void 
        LabelRepository::
        GenDesiredMatrixExtRaw(std::vector<BfMatrix>& rDesired, size_t nFrames, size_t sourceRate, const char* pFeatureLogical)
        {
            //timer
            Timer tim; tim.Start();

            //Get the MLF stream reference...
            IMlfStream& mLabelStream = *mpLabelStream;
            //Build the file name of the label
            MakeHtkFileName(mpLabelFile, pFeatureLogical, mpLabelDir, mpLabelExt);

            //Find block in MLF file
            mLabelStream.Open(mpLabelFile);
            if(!mLabelStream.good()) {
                Error(std::string("Cannot open label MLF record: ") + mpLabelFile);
            }


            //resize the matrix
            if(nFrames < 1) {
                KALDI_ERR << "Number of frames:" << nFrames << " is lower than 1!!!\n"
                    << pFeatureLogical;
            }

            size_t prev = rDesired.size();
            rDesired.resize(prev + 1, BfMatrix()); /* state + vad */
            rDesired[prev].Init(nFrames, raw_dim, true); //true: Zero()

            //aux variables
            std::string line, state;
            unsigned long long beg, end;
            size_t trunc_frames = 0;
            Vector<BaseFloat> raw;
            raw.Init(raw_dim);

            //parse the label file
            while(!mLabelStream.eof()) {
                std::getline(mLabelStream, line);
                if(line == "") continue; //skip newlines/comments from MLF
                if(line[0] == '#') continue;

                std::istringstream& iss = mGenDesiredMatrixStream;
                iss.clear();
                iss.str(line);

                //parse the line
                //begin
                iss >> std::ws >> beg;
                if(iss.fail()) { 
                    KALDI_ERR << "Cannot parse column 1 (begin)\n"
                        << "line: " << line << "\n"
                        << "file: " << mpLabelFile << "\n";
                }
                //end
                iss >> std::ws >> end;
                if(iss.fail()) { 
                    KALDI_ERR << "Cannot parse column 2 (end)\n"
                        << "line: " << line << "\n"
                        << "file: " << mpLabelFile << "\n";
                }

                for (size_t i = 0; i < raw_dim; i++)
                {
                    if (iss.eof())
                        PError("[label] insufficient columns for the label: %s", mpLabelFile);
                    iss >> raw[i];
                    if (iss.fail())
                        PError("[label] cannot parse raw value for the label: %s", mpLabelFile);
                }
                /*
                   for (size_t i = 0; i < raw_dim; i++)
                   fprintf(stderr, "%.3f", raw[i]);
                   fprintf(stderr, "\n");
                   */
                //divide beg/end by sourceRate and round up to get interval of frames
                beg = (beg+sourceRate/2)/sourceRate;
                if (end == (unsigned long long)-1)
                    end = rDesired[prev].Rows();
                else
                    end = (end+sourceRate/2)/sourceRate; 
                //printf("end:%lld\n", end);
                //beg = (int)round(beg / (double)sourceRate);
                //end = (int)round(end / (double)sourceRate); 

                // Fill the desired matrix
                for(unsigned long long frame=beg; frame<end; frame++) { 
                    //don't write after matrix... (possible longer transcript than feature file)
                    if(frame >= (int)rDesired[prev].Rows()) { trunc_frames++; continue; }

                    //check the next frame is empty:
                    if(0.0 != rDesired[prev][frame][0]) {
                        //ERROR!!!
                        //find out what was previously filled!!!
                        /*
                           BaseFloat max = rDesired[prev][frame].Max();
                           int idx = -1;
                           for(int i=0; i<(int)rDesired[prev][frame].Dim(); i++) { 
                           if(rDesired[prev][frame][i] == max) idx = i; 
                           }
                           */
                        BaseFloat max = rDesired[prev][frame][0];
                        //print the error message
                        std::ostringstream os; 
                        os << "Frame already assigned to other state, "
                            << " file: " << mpLabelFile 
                            << " frame: " << frame
                            << " nframes: " << nFrames 
                            << " sum: " << max
                            << "\n";
                        Error(os.str());
                    }

                    //fill the row
                    //rDesired[prev][(size_t)frame][state_index] = 1.0f;
                    rDesired[prev][(size_t)frame].Copy(raw);
                }
            }

            mLabelStream.Close();
            /*
            //check the desired matrix (rows sum up to 1.0)
            for(size_t i=0; i<rDesired[prev].Rows(); ++i) {
            float desired_row_sum = rDesired[prev][i].Sum();
            if(!desired_row_sum == 1.0) {
            std::ostringstream os;
            os << "Desired vector sum isn't 1.0, "
            << " file: " << mpLabelFile 
            << " row: " << i 
            << " nframes: " << nFrames 
            << " content: " << rDesired[prev][i] 
            << " sum: " << desired_row_sum  << "\n";
            Error(os.str());
            }
            }
            */

            //warning when truncating many frames
            if(trunc_frames > 10) {
                std::ostringstream os;
                os << "Truncated frames: " << trunc_frames 
                    << " Check sourcerate in features and validity of labels\n";
                Warning(os.str());
            }

            //timer
            tim.End(); mGenDesiredMatrixTime += tim.Val();
        }

}//namespace