~ubuntu-branches/ubuntu/maverick/speech-tools/maverick

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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
/*************************************************************************/
/*                                                                       */
/*                Centre for Speech Technology Research                  */
/*                     University of Edinburgh, UK                       */
/*                         Copyright (c) 1998                            */
/*                        All Rights Reserved.                           */
/*                                                                       */
/*  Permission is hereby granted, free of charge, to use and distribute  */
/*  this software and its documentation without restriction, including   */
/*  without limitation the rights to use, copy, modify, merge, publish,  */
/*  distribute, sublicense, and/or sell copies of this work, and to      */
/*  permit persons to whom this work is furnished to do so, subject to   */
/*  the following conditions:                                            */
/*   1. The code must retain the above copyright notice, this list of    */
/*      conditions and the following disclaimer.                         */
/*   2. Any modifications must be clearly marked as such.                */
/*   3. Original authors' names are not deleted.                         */
/*   4. The authors' names are not used to endorse or promote products   */
/*      derived from this software without specific prior written        */
/*      permission.                                                      */
/*                                                                       */
/*  THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK        */
/*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING      */
/*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT   */
/*  SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE     */
/*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    */
/*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   */
/*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          */
/*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       */
/*  THIS SOFTWARE.                                                       */
/*                                                                       */
/*************************************************************************/
/*                   Author :  Alan W Black                              */
/*                   Date   :  February 1998                             */
/*-----------------------------------------------------------------------*/
/*             Generalised relations in utterances                       */
/*                                                                       */
/*=======================================================================*/
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <fstream>
#include "ling_class/EST_Relation.h"
#include "ling_class/EST_Item.h"
#include "relation_io.h"

VAL_REGISTER_CLASS(relation,EST_Relation)

EST_Relation::EST_Relation(const EST_String &name)
{
    p_name = name;
    p_head = 0;
    p_tail = 0;
    p_utt = 0;
}

EST_Relation::EST_Relation()
{
    p_head = 0;
    p_tail = 0;
    p_utt = 0;
}

void EST_Relation::copy(const EST_Relation &r)
{
    // Do a *full* copy include the contents of all the items
    // But not the name (?)
    EST_String tmp_name;
    p_name = r.p_name;
    p_head = 0;
    p_tail = 0;
    p_utt = 0;  // can't be in the same utterance as r

    tmp_name = f.S("name", "");
    f = r.f;
    f.set("name", tmp_name);

    if (r.root() != 0)
    {
	EST_Item i = *r.root();
	EST_Item *to_root = append(&i);
	copy_node_tree_contents(r.root(),to_root);
    }
}

EST_Item *EST_Relation::append(EST_Item *si)
{

    EST_Item *nn;

    if (this == 0)
    {
      EST_warning("EST_Relation: no relation to append to");
      return 0;
    }
    else if (p_tail == 0)
    {
	nn = new EST_Item(this, si);
	p_head = nn;
    }
    else
	nn = p_tail->insert_after(si);
    p_tail = nn;

//    if (!si->f_present("id") && utt())
//	si->fset("id", utt()->next_id());

    return nn;
}

EST_Item *EST_Relation::append()
{
    return append(0);
}

EST_Item *EST_Relation::prepend()
{
    return prepend(0);
}

EST_Item *EST_Relation::prepend(EST_Item *si)
{
    EST_Item *nn;

    if (this == 0)
    {
      EST_warning("EST_Relation: no relation to prepend to");
	return 0;
    }
    else if (p_head == 0)
    {
	nn = new EST_Item(this,si);
	p_tail = nn;
    }
    else
	nn = p_head->insert_before(si);
    p_head = nn;

    return nn;
}

EST_Relation::~EST_Relation()
{
    clear();
}

int EST_Relation::length() const
{
    EST_Item *node;
    int i;

    if (this == 0)
	return 0;
    for (i=0,node=p_head; node; node=next(node))
	i++;
    return i;
}

void EST_Relation::evaluate_item_features()
{
    for (EST_Item *s = head(); s; s = next(s))
	s->evaluate_features();
}

void EST_Relation::clear()
{
    EST_Item *nn,*nnn;

    for (nn = p_head; nn != 0; nn = nnn)
    {
	nnn = next(nn);
	delete nn;
    }
    p_head = p_tail = 0;
}

void EST_Relation::remove_item(EST_Item *node)
{
    if (p_head == node)
	p_head = next(node);
    if (p_tail == node)
	p_tail = prev(node);
    delete node;
}

void EST_Relation::remove_item_feature(const EST_String &name)
{
    for (EST_Item *s = p_head; s; s = next_item(s))
	s->f_remove(name);
}

void copy_relation(const EST_Relation &from, EST_Relation &to)
{
    // clone the relation structure from into to, deleting any existing
    // nodes in to.

    to.clear();

    if (from.root() != 0)
    {
	EST_Item *to_root = to.append(from.root());
	copy_node_tree(from.root(),to_root);
    }
}

EST_write_status EST_Relation::save(ostream &outf,
				    const EST_String &type,
				    bool evaluate_ff) const
{
    if (type == "esps")
	return save_esps_label(&outf,*this,evaluate_ff);
    else if (type == "htk")
	return save_htk_label(&outf,*this);
    else
    {
      EST_warning("EST_Relation: unsupported type: \"%s\"", (const char *)type);
	return write_fail;
    }
}

EST_write_status EST_Relation::save(const EST_String &filename, 
				    const EST_String &type,
				    bool evaluate_ff) const
{
    if (type == "esps")
	return save_esps_label(filename,*this,evaluate_ff);
    else if (type == "htk")
	return save_htk_label(filename,*this);
    else
    {
      EST_warning("EST_Relation: unsupported type: \"%s\"", (const char *)type);
	return write_fail;
    }
}

EST_write_status EST_Relation::save(const EST_String &filename, 
				    bool evaluate_ff) const
{
    return save(filename,"esps",evaluate_ff);
}

EST_write_status EST_Relation::save(ostream &outf, 
				    EST_TKVL<void *,int> contents) const
{
    EST_TKVL<void *,int> nodenames;
    int node_count = 1;
    outf << "Relation " << name() << " ; ";
    f.save(outf);
    outf << endl;
    save_items(p_head,outf,contents,nodenames,node_count);
    outf << "End_of_Relation" << endl;
    return write_ok;
}

EST_write_status EST_Relation::save_items(EST_Item *node, 
					  ostream &outf,
					  EST_TKVL<void *,int> &cnames,
					  EST_TKVL<void *,int> &nodenames,
					  int &node_count) const
{
    if (node != 0)
    {
	int myname = node_count++;
	// Name it before dealing with the next nodes
	nodenames.add_item(node,myname);
	// This will need to be expanded if the we make Relations
	// have more complex structures
	save_items(node->next(),outf,cnames,nodenames,node_count);
	save_items(node->down(),outf,cnames,nodenames,node_count);
	outf << myname << " " <<
	   (node->contents() == 0 ? 0 : cnames.val(node->contents())) << " " <<
	   (node->up() == 0 ? 0 : nodenames.val(node->up())) << " " <<
	   (node->down() == 0 ? 0 : nodenames.val(node->down())) << " " <<
	   (node->next() == 0 ? 0 : nodenames.val(node->next())) << " " <<
	   (node->prev() == 0 ? 0 : nodenames.val(node->prev())) << endl;
    }
    return write_ok;
}

#if 0
EST_read_status EST_Relation::load(EST_TokenStream &ts,
				   const EST_THash<int,EST_Val> &contents)
{
    if (ts.get() != "Relation")
    {
	cerr << "load_relation: " << ts.pos_description() << 
	    " no new Relation" << endl;
	return misc_read_error;
    }
    p_name = ts.get().string();
    if (ts.get() != ";")
    {
	cerr << "load_relation: " << ts.pos_description() << 
	    " semicolon missing after Relation name \"" <<
		p_name << "\"" << endl;
	return misc_read_error;
    }
    if (f.load(ts) != format_ok)
	return misc_read_error;
    if (load_items(ts,contents) != format_ok)
	return misc_read_error;

    return format_ok;
}
#endif

EST_read_status EST_Relation::load(EST_TokenStream &ts,
				   const EST_TVector < EST_Item_Content * > &contents
				   )
{
    if (ts.get() != "Relation")
    {
	cerr << "load_relation: " << ts.pos_description() << 
	    " no new Relation" << endl;
	return misc_read_error;
    }
    p_name = ts.get().string();
    if (ts.get() != ";")
    {
	cerr << "load_relation: " << ts.pos_description() << 
	    " semicolon missing after Relation name \"" <<
		p_name << "\"" << endl;
	return misc_read_error;
    }
    if (f.load(ts) != format_ok)
	return misc_read_error;
    if (load_items(ts,contents) != format_ok)
	return misc_read_error;

    return format_ok;
}

void EST_Relation::node_tidy_up_val(int &k, EST_Val &v)
{
    // Called to delete the nodes in the hash table when a load
    // fails
    (void)k;
    EST_Item *node = item(v);
    node->u = 0;
    node->d = 0;
    node->n = 0;
    node->p = 0;
    delete node;
}

void EST_Relation::node_tidy_up(int &k, EST_Item *node)
{
    // Called to delete the nodes in the hash table when a load
    // fails
    (void)k;
    node->u = 0;
    node->d = 0;
    node->n = 0;
    node->p = 0;
    delete node;
}

#if 0
EST_read_status EST_Relation::load_items(EST_TokenStream &ts,
					 const EST_THash<int,EST_Val> &contents)
{
    // Load a set of nodes from a TokenStream, the file contains node
    // descriptions one per line as 5 ints, this nodes name, the
    // stream item it is to be related to, then the name of the 
    // nodes above, below, before and after it.
    EST_THash<int,EST_Val> nodenames(100);
    EST_read_status r = format_ok;
    EST_Item *node = 0;
    EST_Relation *rel=NULL;
//    int expect_links=0;

    while (ts.peek() != "End_of_Relation")
    {
	int name = atoi(ts.get().string());
	int siname;

	node = get_item_from_name(nodenames,name);
	if (!node)
	  EST_error("Unknown item %d", name);

	if (rel==NULL)
	  {
	    rel=node->relation();
//	    EST_String type = rel->f.S("type", "");
//	    expect_links = (type == "ladder");
	  }

	siname = atoi(ts.get().string());
	if (siname != 0) 
	{
	    int found;
	    EST_Val v = contents.val(siname,found);
	    if (!found)
	    {
		cerr << "load_nodes: " << ts.pos_description() << 
		    " node's item contents" << siname << " doesn't exist\n";
		r = misc_read_error;
		break;
	    }
	    else
		node->set_contents(icontent(v));
	}
	// up down next previous
	node->u = get_item_from_name(nodenames,atoi(ts.get().string()));
	node->d = get_item_from_name(nodenames,atoi(ts.get().string()));
	node->n = get_item_from_name(nodenames,atoi(ts.get().string()));
	node->p = get_item_from_name(nodenames,atoi(ts.get().string()));

	
	// Read ladder links
#if 0
	if (expect_links)
	  {
	    int numlinks = atoi(ts.get().string());
	    // node->link_feats.set("num_links",numlinks);
	    for (int i=0;i<numlinks;++i)
	      {
		EST_Item * item = get_item_from_name(nodenames,atoi(ts.get().string()));
		node->link_feats.set_val("link" + itoString(i),est_val(item));
	      }
	  }
#endif
    }
    
    ts.get(); // skip End_of_Relation

    if (r == format_ok)
    {
	if (node != 0) // at least one node
	  {
	    p_head = get_item_from_name(nodenames,1);
	    p_tail = p_head->last();
	    if (!p_head->verify())
	      {
		cerr << "load_nodes: " << ts.pos_description() <<
		  " nodes do not form consistent graph" << endl;
		r = misc_read_error;
	      }
	  }
    }

    if (r != format_ok)
    {
	// failed to read this relation so clear the created nodes
	// before returning, no idea what state the links are in so
	// explicitly unlink them before deleting them

	nodenames.map(node_tidy_up_val);
    }
    return r;
}    
#endif

EST_read_status EST_Relation::load_items(EST_TokenStream &ts,
					 const EST_TVector < EST_Item_Content * > &contents
					 )
{
    // Load a set of nodes from a TokenStream, the file contains node
    // descriptions one per line as 5 ints, this nodes name, the
    // stream item it is to be related to, then the name of the 
    // nodes above, below, before and after it.

    EST_TVector < EST_Item * > nodenames(100);
    //    EST_THash<int,EST_Val> nodenames(100);
    EST_read_status r = format_ok;
    EST_Item *node = 0;
    EST_Relation *rel=NULL;
//    int expect_links=0;

    while (ts.peek() != "End_of_Relation")
    {
	int name = atoi(ts.get().string());
	int siname;

	node = get_item_from_name(nodenames,name);
	if (!node)
	  EST_error("Unknown item %d", name);

	if (rel==NULL)
	  {
	    rel=node->relation();
//	    EST_String type = rel->f.S("type", "");
//	    expect_links = (type == "ladder");
	  }

	siname = atoi(ts.get().string());
	if (siname != 0) 
	{
	  EST_Item_Content *c = contents(siname);
	  if (c==NULL)
	    {
	      cerr << "load_nodes: " << ts.pos_description() << 
		" node's stream item " << siname << " doesn't exist\n";
	      r = misc_read_error;
	      break;
	    }
	  else
	    node->set_contents(c);
	}
	// up down next previous
	node->u = get_item_from_name(nodenames,atoi(ts.get().string()));
	node->d = get_item_from_name(nodenames,atoi(ts.get().string()));
	node->n = get_item_from_name(nodenames,atoi(ts.get().string()));
	node->p = get_item_from_name(nodenames,atoi(ts.get().string()));

#if 0
	// Read ladder links
	if (expect_links)
	  {
	    int numlinks = atoi(ts.get().string());
	    // node->link_feats.set("num_links",numlinks);
	    for (int i=0;i<numlinks;++i)
	      {
		EST_Item * item = get_item_from_name(nodenames,atoi(ts.get().string()));
		// node->link_feats.set_val("link" + itoString(i),est_val(item));
	      }
	  }
#endif
    }

    ts.get(); // skip End_of_Relation

    if (r == format_ok)
    {
	if (node != 0) // at least one node
	    p_head = get_item_from_name(nodenames,1);
	p_tail = p_head->last();
	if (!p_head->verify())
	{
	    cerr << "load_nodes: " << ts.pos_description() <<
		" nodes do not form consistent graph" << endl;
	    r = misc_read_error;
	}
    }

    if (r != format_ok)
    {
	// failed to read this relation so clear the created nodes
	// before returning, no idea what state the links are in so
	// explicitly unlink them before deleting them
      for(int ni=0; ni<nodenames.length(); ni++)
	{
	  EST_Item *node = nodenames(ni);
	  if (node != NULL)
	    node_tidy_up(ni, node);
	}
    }
    return r;
}    

EST_Item *EST_Relation::get_item_from_name(EST_THash<int,EST_Val> &nodenames,
					   int name)
{
    // Return node named by name or create a new one if it doesn't
    // already exist
    EST_Item *node;
    int found;

    if (name == 0)
      return 0;
    EST_Val v = nodenames.val(name,found);
    if (!found)
    {
	node = new EST_Item(this, 0);
	nodenames.add_item(name,est_val(node));
    }
    else
	node = item(v);
    return node;
}

EST_Item *EST_Relation::get_item_from_name(EST_TVector< EST_Item * > &nodenames,
					   int name)
{
    // Return node named by name or create a new one if it doesn't
    // already exist

    if (name == 0)
	return 0;

    if (name >= nodenames.length())
      {
	nodenames.resize(name*2, 1);
      }

    EST_Item *node = nodenames(name);
    if (node==NULL)
    {
	node = new EST_Item(this, 0);
	nodenames[name] = node;
    }

    return node;
}

EST_read_status EST_Relation::load(const EST_String &filename,
				   EST_TokenStream &ts,
				   const EST_String &type)
{
    EST_read_status r;

    f.set("filename",filename);

    if (type == "esps")
	r = load_esps_label(ts,*this);
    else if (type == "ogi")
	r = load_ogi_label(ts,*this);
    else if (type == "htk")
	r = load_sample_label(ts,*this,10000000);
    else if ((type == "ascii") || (type == "timit"))
	r = load_sample_label(ts,*this,1);
    else if (type == "words")
	r = load_words_label(ts,*this);
    else   // currently esps is the default
	r = load_esps_label(ts,*this);

    return r;
}

EST_read_status EST_Relation::load(const EST_String &filename,
				   const EST_String &type)
{
    // Load an isolated relation from a file, assuming Xlabel format
    EST_TokenStream ts;
    EST_read_status r;

    if (((filename == "-") ? ts.open(cin) : ts.open(filename)) != 0)
    {
	cerr << "load_relation: can't open relation input file " 
	    << filename << endl;
	return misc_read_error;
    }
    r = load(filename, ts, type);

    ts.close();

    return r;
}

int num_leaves(const EST_Item *h)
{
    int count = 0;
    EST_Item *n;

    for (n = h->first_leaf(); n != 0; n=n->next_leaf())
	count++;
    return count;
}

EST_Item *EST_Relation::first_leaf() const 
{ 
    return head()->first_leaf();
}

EST_Item *EST_Relation::last_leaf() const 
{ 
    return head()->last_leaf();
}

EST_Utterance *get_utt(EST_Item *s)
{
    // Occasionally you need to get the utterance from a stream_item
    // This finds any relations in s and follows them to the utterance
    // If there aren't any Relations the this streamitem isn't in an
    // utterances

    if (s == 0)
	return 0;
    if (s->relation())
	return s->relation()->utt();
    else
	return 0;  // can't find an utterance
}

EST_Relation &EST_Relation::operator=(const EST_Relation &s)
{
    copy(s);
    return *this;
}

ostream& operator << (ostream &s, const EST_Relation &a)
{
    s << a.f << endl;

    for (EST_Item *p = a.head(); p; p = next(p))
	s << *p << endl;

    return s;
}