recognize.cpp
12.9 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
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
#include <recognize.h>
Recognize::Recognize(char* _pathVideo, char* _id) {
listeners = new list<RecognizeListener*>();
pathVideo = _pathVideo;
inputType = INPUT_PATTERN;
frequency = FREQUENCY_PATTERN;
sizeBlocs = BLOCS_PATTERN;
stringstream ss;
ss << _id;
ss >> id;
confidenceRate=CONFIDENCE_RATE;
PRINTL(util::_DEBUG, "Recognize Done!\n");
}
Recognize::Recognize(char* _pathVideo, char* _id, char* rate) {
listeners = new list<RecognizeListener*>();
pathVideo = _pathVideo;
inputType = INPUT_PATTERN;
frequency = FREQUENCY_PATTERN;
sizeBlocs = BLOCS_PATTERN;
stringstream ss;
ss << _id;
ss >> id;
istringstream(rate) >> confidenceRate;
if (confidenceRate == 0)
confidenceRate=CONFIDENCE_RATE;
PRINTL(util::_DEBUG, "Recognize Done!\n");
}
Recognize::Recognize(char* _pathVideo, int _inputType, char* _id) {
listeners = new list<RecognizeListener*>();
pathVideo = _pathVideo;
inputType = _inputType;
frequency = FREQUENCY_PATTERN;
sizeBlocs = BLOCS_PATTERN;
id = _id;
PRINTL(util::_DEBUG, "Recognize Done!\n");
}
Recognize::~Recognize() {
listeners->clear();
delete listeners;
PRINTL(util::_DEBUG, "Recognize finalized!\n");
}
void Recognize::initialize() {
PRINTL(util::_INFO, "Reconhecendo áudio...\n");
/**printf("*** Initialized Recognition ***\n\nVideo: %s\nType [1-File; 2-Mic]: %d\nFrequency: %d\n\n",
this->pathVideo, this->inputType, this->frequency);**/
ifstream file(pathVideo, ifstream::binary);
if(!file.is_open()){
finish = true;
Logging::instance()->writeLog("recognize.cpp <Error> Arquivo não encontrado.");
throw RecognizeException("Falha ao abrir o arquivo! Verifique se o mesmo existe.");
}
this->Start();
}
void Recognize::Run(){
finish = false;
createDir();
extractAudioFromVideo();
if (RECOGNIZER_MODE == 0){
breakVideoParts(getTimeMediaSec());
executeJuliusEngine();
generateConfidence();
} else {
executeGoogleEngine();
}
finish = true;
notifyEndExtraction(count_lines);
cleanFiles();
}
void Recognize::setFrequency(int freq) {
frequency = freq;
}
void Recognize::setSizeAudioBlocs(int sec) {
sizeBlocs = sec;
}
void Recognize::setPathAudioContents(char* path){
path_contents = path;
}
char* Recognize::extractAudioFromVideo() {
string command = PROGRAM;
command.append(" -i ").
append((string) pathVideo).
append(" -ar ");
string strFreq;
std::stringstream sstr;
sstr << frequency;
strFreq = sstr.str();
//command.append(strFreq).append(" -ac 1 -f wav ").append(PATH_AUDIO_ORIGIN).append(" &");
command.append(strFreq).
append(" -ac 1 -f wav ").
append(path_contents).append("/").append(id).
append(PATH_AUDIO_ORIGIN).append(" -v quiet");
/*string tmp = "echo ";
tmp.append(PATH_AUDIO_ORIGIN).append(" >> ").append(FILENAME_AUDIOLIST);
system(tmp.c_str());*/
system(command.c_str());
}
int Recognize::getTimeMediaSec() {
string command = PROGRAM;
command.append(" -i ").append(path_contents).append("/").append(id).append(PATH_AUDIO_ORIGIN)
.append(" 2>&1 | grep Duration >> outfile");
system(command.c_str());
ifstream in("outfile");
if (!in) return -1;
std::string line;
in >> line >> line;
char* timetok;
timetok = strtok((char*)line.c_str(), " :,.");
int seconds = 0;
seconds += (atoi(timetok) * 60 * 60); // hora
timetok = strtok(NULL, " :,.");
seconds += (atoi(timetok) * 60); // min
timetok = strtok(NULL, " :,.");
seconds += atoi(timetok); // seg
system("rm outfile");
return seconds;
}
void Recognize::breakVideoParts(int timeTotal) {
string ss_str, t_str, command, aplist;
int count = 1;
int ss = 0;
int t = 0;
bool consume = true;
string filename= FILENAME_AUDIOPART;
char tmp [filename.length()];
sprintf(tmp, "%i", ss);
ss_str = tmp;
sprintf(tmp, "%i", sizeBlocs);
t_str = tmp;
if (timeTotal < sizeBlocs)
sizeBlocs = timeTotal;
do {
ss = t;
if(timeTotal >= sizeBlocs && (timeTotal - sizeBlocs) > (sizeBlocs/2)) {
t += sizeBlocs;
timeTotal -= sizeBlocs;
} else {
t += timeTotal;
timeTotal = 0;
consume = false;
sprintf(tmp, "%i", t);
t_str = tmp;
}
sprintf(tmp, "%i", ss);
ss_str = tmp;
pts.push_back(convert_pts(ss_str));
command = "sox ";
command.append(path_contents).append("/").append(id).append(PATH_AUDIO_ORIGIN).append(" ")
.append(path_contents).append("/").append(id).append(PATH_AUDIO_PARTS);
sprintf(tmp, "%i", count++);
filename.append(tmp).append(".wav");
command.append(filename).append(" trim ").append(ss_str).append(" ").append(t_str);
system(command.c_str());
string apcomm = "echo ";
apcomm.append(path_contents).append("/").append(id).append(PATH_AUDIO_PARTS).append(filename).append(" >> ")
.append(path_contents).append("/").append(id).append(FILENAME_AUDIOLIST);
system(apcomm.c_str());
filename = FILENAME_AUDIOPART;
aplist = "";
} while (consume);
}
void Recognize::executeJuliusEngine() {
string type, freqStr;
string command = "julius -quiet -C ";
char cfreq[10];
char* jPath;
jPath = getenv("JCONFIG");
if(jPath != NULL)
command.append(jPath);
else
command.append(PATH_JCONFIG);
command.append(" -input ");
if (inputType == 1)
type = "rawfile";
else
type = "mic";
command.append(type).append(" -filelist ").append(path_contents).append("/").append(id).append(FILENAME_AUDIOLIST);
sprintf(cfreq, "%i", frequency);
command.append(" -smpFreq ").
append(cfreq).
append(" >> ");
command.append(path_contents).append("/").append(id).append(FILENAME_RECOGNIZED_OUT);
//Command of execute Julius
//printf("\n\nCommand for executeJuliusEngine: %s\n", command.c_str());
system(command.c_str());
}
void Recognize::generateConfidence() {
string command = "cat ";
command.append(path_contents).append("/").append(id).append(FILENAME_RECOGNIZED_OUT).append(" | grep ").
append(FIND_CONFIDENCE).append(" >> ").append(path_contents).append("/").append(id).append(FILENAME_CONFIDENCEOUT);
system(command.c_str());
//printf("\n\n---> command: %s\n\n", command.c_str());
string path;
path.append(path_contents).append("/").append(id).append(FILENAME_CONFIDENCEOUT);
ifstream in(path.c_str());
if (!in) {
perror("Error: ");
} else {
string line;
float tmp;
int pass = 0;
do {
getline(in, line);
std::istringstream buf(line);
if (line.length() > 0) {
pass++;
istream_iterator<std::string> beg(buf), end;
vector<string> tokens(beg, end);
float sizeAvgScores = 0;
float sizeLowScores = 0;
float avgScores = 0;
float lowScores = 0;
int i;
for(i=2; i < tokens.size()-1; i++){
istringstream(tokens[i]) >> tmp;
if (tmp > confidenceRate){
avgScores += tmp;
sizeAvgScores++;
}
else{
lowScores += tmp;
sizeLowScores++;
}
}
if (lowScores > 0){
lowScores = lowScores/sizeLowScores;
int i;
for(i=0; i < sizeLowScores/2; i++){
avgScores += lowScores;
sizeAvgScores++;
}
}
scores.push_back(avgScores/sizeAvgScores);
}else if(pass==0){
notifyListeners((char*) "SENTENCA_COM_BAIXA_QUALIDADE", 0);
return;
}
} while (!in.eof());
in.close();
filterOutputJulius();
}
}
bool Recognize::getConfidence(){
//cout << "CONFIDENCE: " << scores[i] << endl;
if (scores.front() < confidenceRate)
return false;
return true;
}
void Recognize::filterOutputJulius() {
std::list<char*> *sentences;
sentences = new std::list<char*>();
string command = "cat ";
command.append(path_contents).append("/").append(id).append(FILENAME_RECOGNIZED_OUT).append(" | grep -e ").
append(FIND_SENTENCE).append(" -e \"").append(AUDIO_SILENT).append("\"").append(" >> ").append(path_contents).append("/").append(id).append(FILENAME_FILTEROUT);
system(command.c_str());
//printf("\n\n---> command: %s\n\n", command.c_str());
count_lines = 0;
string path;
path.append(path_contents).append("/").append(id).append(FILENAME_FILTEROUT);
ifstream in(path.c_str());
string strFilter;
if (!in) {
perror("Error: ");
} else {
string line;
int sizeLine;
char* sentence_ptr;
do {
getline(in, line);
if (line.length() > 0) {
if (line != AUDIO_SILENT){
sizeLine = (int)line.length();
strFilter = line.substr(strlen(FIND_SENTENCE), sizeLine);
sentence_ptr = new char[strFilter.length()+1];
strcpy(sentence_ptr, (char*) strFilter.c_str());
if(getConfidence())
notifyListeners(sentence_ptr, pts.front());
else{
notifyListeners((char*) "SENTENCA_COM_BAIXA_QUALIDADE", pts.front());
}
scores.erase(scores.begin());
count_lines++;
}
pts.erase(pts.begin());
}
} while (!in.eof());
in.close();
//notifyListeners((char*) "SENTENCA_COM_BAIXA_QUALIDADE", pts.front());
}
/*char* ptr_strFilter;
ptr_strFilter = (char*) malloc (strFilter.length()+1);
strcpy(ptr_strFilter, (char*) strFilter.c_str());*/
}
void Recognize::notifyListeners(char* text, int64_t pts) {
//cout << "NOTIFY: " << text << endl;
for(list<RecognizeListener*>::iterator it = listeners->begin(); it != listeners->end(); it++){
//(*it)->notifyTextRecognized((unsigned char*) text, calcula_pts(pts));
(*it)->notifyTextRecognized((unsigned char*) text, pts);
}
}
void Recognize::notifyEndExtraction(int sentences_size) {
PRINTL(util::_DEBUG, "Recognizer concluiu o reconhecimento: %d sentenças.\n", sentences_size);
for(list<RecognizeListener*>::iterator it = listeners->begin(); it != listeners->end(); it++){
(*it)->notifyEnd(sentences_size);
}
}
int64_t Recognize::calcula_pts(double msec) {
return (int64_t)(1000 /*pcr_base*/ + ((msec/1000) * 90000.0));
}
int64_t Recognize::convert_pts(string pts){
int64_t ui64;
stringstream ss;
ss << pts;
ss >> ui64;
return ui64*1000;
}
void Recognize::addListener(RecognizeListener* listener) {
listeners->push_back(listener);
}
bool Recognize::isFinished() {
return finish;
}
void Recognize::cleanFiles() {
string command = "rm -r ";
command.append(path_contents).append("/").append(id).append("/audio");
system(command.c_str());
}
void Recognize::createDir(){
string command = "mkdir -p ";
command.append(path_contents).append("/").append(id).append("/audio")
.append(" && mkdir -p ").append(path_contents).append("/").append(id).append("/audio/parts")
.append(" && mkdir -p ").append(path_contents).append("/").append(id).append("/audio/origin");
system(command.c_str());
}
void Recognize::executeGoogleEngine() {
jlog_set_output(NULL);
Wavcut* wavcut;
Recognizer* recog;
vector<Audiofile> audioList;
string file_in = "";
file_in.append(path_contents).append("/").append(id).append(PATH_AUDIO_ORIGIN);
string path_out= "";
path_out.append(path_contents).append("/").append(id).append("/");
char* pathAudio = new char[file_in.size()+1];
char* outputPath = new char[path_out.size()+1];
char* _id = new char[id.size()+1];
strcpy(pathAudio, file_in.c_str());
strcpy(outputPath, path_out.c_str());
strcpy(_id, id.c_str());
wavcut = new Wavcut(pathAudio,outputPath,_id);
Jconf *jconf;
char* wPath;
wPath = getenv("WCONFIG");
if(wPath != NULL)
jconf = j_config_load_file_new(wPath);
else
jconf = j_config_load_file_new(PATH_WCONFIG);
if(wavcut->initialize(jconf)<2){
wavcut->initialize(load_config());
}
audioList = wavcut->list_audio_files();
delete wavcut;
recog = new Recognizer();
int ii;
count_lines = 0;
for(ii=0; ii < audioList.size(); ii++)
{
/*chama o reconhecedor passando cada arquivo de audio*/
recog->recognize(audioList[ii].file_path);
/*remove o audio ja reconhecido*/
remove(audioList[ii].file_path);
/*segundos do inicio do audio reconhecido*/
//cout<< calcula_pts(audioList[ii].start_seg) << endl;
/* texto do audio reconhecido*/
//cout<< recog->getsentence() << endl;
/* porcentagem de confiança do reconhecimento (de 0 a 1) */
//cout<< recog->getconfidence() << endl;
if(recog->getconfidence() >= confidenceRate)
notifyListeners((char*)recog->getsentence().c_str(), (int64_t)(audioList[ii].start_seg*1000));
else
notifyListeners((char*) "SENTENCA_COM_BAIXA_QUALIDADE", (int64_t)(audioList[ii].start_seg*1000));
if(recog->getconfidence()> 0)
count_lines++;
}
delete recog;
}
Jconf* Recognize::load_config(){
Jconf* jconf;
jconf = j_jconf_new();
char *parametros[12];
parametros[1]="-lv";
parametros[2]="3000";
parametros[3]="-zc";
parametros[4]="150";
parametros[5]="-headmargin";
parametros[6]="200";
parametros[7]="-tailmargin";
parametros[8]="150";
parametros[9]="-rejectshort";
parametros[10]="1500";
//cout << "load_config" << endl;
/* read arguments and set parameters */
if (j_config_load_args(jconf, 11, parametros) == -1) {
fprintf(stderr, "Error reading arguments\n");
}
jconf->input.type = INPUT_WAVEFORM;
jconf->input.speech_input = SP_RAWFILE;
jconf->detect.silence_cut = 1;
return jconf;
}