-
Notifications
You must be signed in to change notification settings - Fork 1
/
libhfst.i
2357 lines (2035 loc) · 87.6 KB
/
libhfst.i
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2016 University of Helsinki
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
// See the file COPYING included with this distribution for more
// information.
// This is a swig interface file that is used to create python bindings for HFST.
// Everything will be visible under module 'libhfst', but will be wrapped under
// package 'hfst' and its subpackages 'hfst.exceptions' and 'hfst.rules' (see
// folder 'hfst' in the current directory).
%module libhfst
// Needed for type conversions between c++ and python.
%include "std_string.i"
%include "std_vector.i"
%include "std_pair.i"
%include "std_set.i"
%include "std_map.i"
%include "exception.i"
// %feature("autodoc", "3");
// We want warnings to be printed to standard error.
%init %{
hfst::set_warning_stream(&std::cerr);
%}
// Make swig aware of what hfst offers.
%{
#define HFSTIMPORT
#include "HfstDataTypes.h"
#include "HfstTransducer.h"
#include "HfstOutputStream.h"
#include "HfstInputStream.h"
#include "HfstExceptionDefs.h"
#include "HfstTokenizer.h"
#include "HfstFlagDiacritics.h"
#include "parsers/XreCompiler.h"
#include "parsers/LexcCompiler.h"
#include "parsers/XfstCompiler.h"
#include "implementations/HfstBasicTransducer.h"
#include "implementations/optimized-lookup/pmatch.h"
// Most of C++ extension code is located in separate files.
#include "hfst_regex_extensions.cc"
#include "hfst_extensions.cc"
#include "hfst_lexc_extensions.cc"
#include "hfst_xfst_extensions.cc"
#include "hfst_pmatch_extensions.cc"
#include "hfst_lookup_extensions.cc"
#include "hfst_rules_extensions.cc"
#include "hfst_prolog_extensions.cc"
%}
#ifdef _MSC_VER
%include <windows.h>
#endif
// Templates needed for conversion between c++ and python datatypes.
//
// Note that templating order matters; simple templates used as part of
// more complex templates must be defined first, e.g. StringPair must be
// defined before StringPairSet. Also templates that are not used as such
// but are used as part of other templates must be defined, e.g.
// HfstBasicTransitions which is needed for HfstBasicStates.
%include "typemaps.i"
namespace std {
%template(StringVector) vector<string>;
%template(StringPair) pair<string, string>;
%template(StringPairVector) vector<pair<string, string > >;
%template(FloatVector) vector<float>;
%template(StringSet) set<string>;
%template(StringPairSet) set<pair<string, string> >;
%template(HfstTransducerVector) vector<hfst::HfstTransducer>;
%template(HfstSymbolSubstitutions) map<string, string>;
%template(HfstSymbolPairSubstitutions) map<pair<string, string>, pair<string, string> >;
// needed for HfstBasicTransducer.states()
%template(BarBazFoo) vector<unsigned int>;
// HfstBasicTransitions is needed for templating HfstBasicStates:
%template(HfstBasicTransitions) vector<hfst::implementations::HfstBasicTransition>;
%template(HfstBasicStates) vector<vector<hfst::implementations::HfstBasicTransition> >;
%template(HfstOneLevelPath) pair<float, vector<string> >;
%template(HfstOneLevelPaths) set<pair<float, vector<string> > >;
%template(HfstTwoLevelPath) pair<float, vector<pair<string, string > > >;
%template(HfstTwoLevelPaths) set<pair<float, vector<pair<string, string > > > >;
%template(HfstTransducerPair) pair<hfst::HfstTransducer, hfst::HfstTransducer>;
%template(HfstTransducerPairVector) vector<pair<hfst::HfstTransducer, hfst::HfstTransducer> >;
}
%include "docstrings.i"
// ****************************************************** //
// ********** WHAT IS MADE AVAILABLE ON PYTHON ********** //
// ****************************************************** //
// *** HfstException and its subclasses (will be wrapped under module hfst.exceptions). *** //
class HfstException
{
public:
HfstException();
HfstException(const std::string&, const std::string&, size_t);
~HfstException();
std::string what() const;
};
class HfstTransducerTypeMismatchException : public HfstException { public: HfstTransducerTypeMismatchException(const std::string&, const std::string&, size_t); ~HfstTransducerTypeMismatchException(); std::string what() const; };
class ImplementationTypeNotAvailableException : public HfstException { public: ImplementationTypeNotAvailableException(const std::string&, const std::string&, size_t, hfst::ImplementationType type); ~ImplementationTypeNotAvailableException(); std::string what() const; hfst::ImplementationType get_type() const; };
class FunctionNotImplementedException : public HfstException { public: FunctionNotImplementedException(const std::string&, const std::string&, size_t); ~FunctionNotImplementedException(); std::string what() const; };
class StreamNotReadableException : public HfstException { public: StreamNotReadableException(const std::string&, const std::string&, size_t); ~StreamNotReadableException(); std::string what() const; };
class StreamCannotBeWrittenException : public HfstException { public: StreamCannotBeWrittenException(const std::string&, const std::string&, size_t); ~StreamCannotBeWrittenException(); std::string what() const; };
class StreamIsClosedException : public HfstException { public: StreamIsClosedException(const std::string&, const std::string&, size_t); ~StreamIsClosedException(); std::string what() const; };
class EndOfStreamException : public HfstException { public: EndOfStreamException(const std::string&, const std::string&, size_t); ~EndOfStreamException(); std::string what() const; };
class TransducerIsCyclicException : public HfstException { public: TransducerIsCyclicException(const std::string&, const std::string&, size_t); ~TransducerIsCyclicException(); std::string what() const; };
class NotTransducerStreamException : public HfstException { public: NotTransducerStreamException(const std::string&, const std::string&, size_t); ~NotTransducerStreamException(); std::string what() const; };
class NotValidAttFormatException : public HfstException { public: NotValidAttFormatException(const std::string&, const std::string&, size_t); ~NotValidAttFormatException(); std::string what() const; };
class NotValidPrologFormatException : public HfstException { public: NotValidPrologFormatException(const std::string&, const std::string&, size_t); ~NotValidPrologFormatException(); std::string what() const; };
class NotValidLexcFormatException : public HfstException { public: NotValidLexcFormatException(const std::string&, const std::string&, size_t); ~NotValidLexcFormatException(); std::string what() const; };
class StateIsNotFinalException : public HfstException { public: StateIsNotFinalException(const std::string&, const std::string&, size_t); ~StateIsNotFinalException(); std::string what() const; };
class ContextTransducersAreNotAutomataException : public HfstException { public: ContextTransducersAreNotAutomataException(const std::string&, const std::string&, size_t); ~ContextTransducersAreNotAutomataException(); std::string what() const; };
class TransducersAreNotAutomataException : public HfstException { public: TransducersAreNotAutomataException(const std::string&, const std::string&, size_t); ~TransducersAreNotAutomataException(); std::string what() const; };
class StateIndexOutOfBoundsException : public HfstException { public: StateIndexOutOfBoundsException(const std::string&, const std::string&, size_t); ~StateIndexOutOfBoundsException(); std::string what() const; };
class TransducerHeaderException : public HfstException { public: TransducerHeaderException(const std::string&, const std::string&, size_t); ~TransducerHeaderException(); std::string what() const; };
class MissingOpenFstInputSymbolTableException : public HfstException { public: MissingOpenFstInputSymbolTableException(const std::string&, const std::string&, size_t); ~MissingOpenFstInputSymbolTableException(); std::string what() const; };
class TransducerTypeMismatchException : public HfstException { public: TransducerTypeMismatchException(const std::string&, const std::string&, size_t); ~TransducerTypeMismatchException(); std::string what() const; };
class EmptySetOfContextsException : public HfstException { public: EmptySetOfContextsException(const std::string&, const std::string&, size_t); ~EmptySetOfContextsException(); std::string what() const; };
class SpecifiedTypeRequiredException : public HfstException { public: SpecifiedTypeRequiredException(const std::string&, const std::string&, size_t); ~SpecifiedTypeRequiredException(); std::string what() const; };
class HfstFatalException : public HfstException { public: HfstFatalException(const std::string&, const std::string&, size_t); ~HfstFatalException(); std::string what() const; };
class TransducerHasWrongTypeException : public HfstException { public: TransducerHasWrongTypeException(const std::string&, const std::string&, size_t); ~TransducerHasWrongTypeException(); std::string what() const; };
class IncorrectUtf8CodingException : public HfstException { public: IncorrectUtf8CodingException(const std::string&, const std::string&, size_t); ~IncorrectUtf8CodingException(); std::string what() const; };
class EmptyStringException : public HfstException { public: EmptyStringException(const std::string&, const std::string&, size_t); ~EmptyStringException(); std::string what() const; };
class SymbolNotFoundException : public HfstException { public: SymbolNotFoundException(const std::string&, const std::string&, size_t); ~SymbolNotFoundException(); std::string what() const; };
class MetadataException : public HfstException { public: MetadataException(const std::string&, const std::string&, size_t); ~MetadataException(); std::string what() const; };
class FlagDiacriticsAreNotIdentitiesException : public HfstException { public: FlagDiacriticsAreNotIdentitiesException(const std::string&, const std::string&, size_t); ~FlagDiacriticsAreNotIdentitiesException(); std::string what() const; };
namespace hfst
{
// Needed for conversion between c++ and python datatypes.
typedef std::vector<std::string> StringVector;
typedef std::pair<std::string, std::string> StringPair;
typedef std::vector<std::pair<std::string, std::string> > StringPairVector;
typedef std::vector<float> FloatVector;
typedef std::set<std::string> StringSet;
typedef std::set<std::pair<std::string, std::string> > StringPairSet;
typedef std::pair<float, std::vector<std::string> > HfstOneLevelPath;
typedef std::set<std::pair<float, std::vector<std::string> > > HfstOneLevelPaths;
typedef std::pair<float, std::vector<std::pair<std::string, std::string > > > HfstTwoLevelPath;
typedef std::set<std::pair<float, std::vector<std::pair<std::string, std::string> > > > HfstTwoLevelPaths;
typedef std::map<std::string, std::string> HfstSymbolSubstitutions;
typedef std::map<std::pair<std::string, std::string>, std::pair<std::string, std::string> > HfstSymbolPairSubstitutions;
typedef std::vector<hfst::HfstTransducer> HfstTransducerVector;
typedef std::pair<hfst::HfstTransducer, hfst::HfstTransducer> HfstTransducerPair;
typedef std::vector<std::pair<hfst::HfstTransducer, hfst::HfstTransducer> > HfstTransducerPairVector;
// *** Some enumerations *** //
enum ImplementationType
{ SFST_TYPE, TROPICAL_OPENFST_TYPE, LOG_OPENFST_TYPE, FOMA_TYPE,
XFSM_TYPE, HFST_OL_TYPE, HFST_OLW_TYPE, HFST2_TYPE,
UNSPECIFIED_TYPE, ERROR_TYPE };
// enum PushType { TO_INITIAL_STATE, TO_FINAL_STATE };
// *** Some other functions *** //
bool is_diacritic(const std::string & symbol);
hfst::HfstTransducerVector compile_pmatch_expression(const std::string & pmatch);
// internal functions
%pythoncode %{
def _is_string(s):
if isinstance(s, str):
return True
else:
return False
def _is_string_pair(sp):
if not isinstance(sp, tuple):
return False
if len(sp) != 2:
return False
if not _is_string(sp[0]):
return False
if not _is_string(sp[1]):
return False
return True
def _is_string_vector(sv):
if not isinstance(sv, tuple):
return False
for s in sv:
if not _is_string(s):
return False
return True
def _is_string_pair_vector(spv):
if not isinstance(spv, tuple):
return False
for sp in spv:
if not _is_string_pair(sp):
return False
return True
def _two_level_paths_to_dict(tlps):
retval = {}
for tlp in tlps:
input = ""
output = ""
for sp in tlp[1]:
input += sp[0]
output += sp[1]
if input in retval:
retval[input].append((output, tlp[0]))
else:
retval[input] = [(output, tlp[0])]
return retval
def _one_level_paths_to_tuple(olps):
retval = []
for olp in olps:
path = ""
for s in olp[1]:
path += s
retval.append((path, olp[0]))
return tuple(retval)
%}
// *** HfstTransducer *** //
// NOTE: all functions returning an HfstTransducer& are commented out and extended
// by replacing them with equivalent functions that return void. This is done in
// order to avoid use of references that are not handled well by swig/python.
// Some constructors and the destructor are also redefined.
class HfstTransducer
{
public:
void set_name(const std::string &name);
std::string get_name() const;
hfst::ImplementationType get_type() const;
void set_property(const std::string& property, const std::string& value);
std::string get_property(const std::string& property) const;
const std::map<std::string,std::string>& get_properties() const;
bool compare(const HfstTransducer&, bool harmonize=true) const throw(TransducerTypeMismatchException);
unsigned int number_of_states() const;
unsigned int number_of_arcs() const;
StringSet get_alphabet() const;
bool is_cyclic() const;
bool is_automaton() const;
bool is_infinitely_ambiguous() const;
bool is_lookup_infinitely_ambiguous(const std::string &) const;
bool has_flag_diacritics() const;
void insert_to_alphabet(const std::string &);
void remove_from_alphabet(const std::string &);
static bool is_implementation_type_available(hfst::ImplementationType type);
int longest_path_size(bool obey_flags=true) const;
%extend {
// First versions of all functions returning an HfstTransducer& that return void instead:
void concatenate(const HfstTransducer& tr, bool harmonize=true) throw(TransducerTypeMismatchException) { self->concatenate(tr, harmonize); }
void disjunct(const HfstTransducer& tr, bool harmonize=true) throw(TransducerTypeMismatchException) { self->disjunct(tr, harmonize); }
void subtract(const HfstTransducer& tr, bool harmonize=true) throw(TransducerTypeMismatchException) { self->subtract(tr, harmonize); }
void intersect(const HfstTransducer& tr, bool harmonize=true) throw(TransducerTypeMismatchException) { self->intersect(tr, harmonize); }
void compose(const HfstTransducer& tr, bool harmonize=true) throw(TransducerTypeMismatchException) { self->compose(tr, harmonize); }
void compose_intersect(const HfstTransducerVector &v, bool invert=false, bool harmonize=true) { self->compose_intersect(v, invert, harmonize); }
void priority_union(const HfstTransducer &another) { self->priority_union(another); }
void lenient_composition(const HfstTransducer &another, bool harmonize=true) { self->lenient_composition(another, harmonize); }
void cross_product(const HfstTransducer &another, bool harmonize=true) throw(TransducersAreNotAutomataException) { self->cross_product(another, harmonize); }
void shuffle(const HfstTransducer &another, bool harmonize=true) { self->shuffle(another, harmonize); }
void remove_epsilons() { self->remove_epsilons(); }
void determinize() { self->determinize(); }
void minimize() { self->minimize(); }
void prune() { self->prune(); }
void eliminate_flags() { self->eliminate_flags(); }
void eliminate_flag(const std::string& f) throw(HfstException) { self->eliminate_flag(f); }
void n_best(unsigned int n) { self->n_best(n); }
void convert(ImplementationType impl) { self->convert(impl); }
void repeat_star() { self->repeat_star(); }
void repeat_plus() { self->repeat_plus(); }
void repeat_n(unsigned int n) { self->repeat_n(n); }
void repeat_n_to_k(unsigned int n, unsigned int k) { self->repeat_n_to_k(n, k); }
void repeat_n_minus(unsigned int n) { self->repeat_n_minus(n); }
void repeat_n_plus(unsigned int n) { self->repeat_n_plus(n); }
void invert() { self->invert(); }
void reverse() { self->reverse(); }
void input_project() { self->input_project(); }
void output_project() { self->output_project(); }
void optionalize() { self->optionalize(); }
void insert_freely(const StringPair &symbol_pair, bool harmonize=true) { self->insert_freely(symbol_pair, harmonize); }
void insert_freely(const HfstTransducer &tr, bool harmonize=true) { self->insert_freely(tr, harmonize); }
void _substitute_symbol(const std::string &old_symbol, const std::string &new_symbol, bool input_side=true, bool output_side=true) { self->substitute_symbol(old_symbol, new_symbol, input_side, output_side); }
void _substitute_symbol_pair(const StringPair &old_symbol_pair, const StringPair &new_symbol_pair) { self->substitute_symbol_pair(old_symbol_pair, new_symbol_pair); }
void _substitute_symbol_pair_with_set(const StringPair &old_symbol_pair, const hfst::StringPairSet &new_symbol_pair_set) { self->substitute_symbol_pair_with_set(old_symbol_pair, new_symbol_pair_set); }
void _substitute_symbol_pair_with_transducer(const StringPair &symbol_pair, HfstTransducer &transducer, bool harmonize=true) { self->substitute_symbol_pair_with_transducer(symbol_pair, transducer, harmonize); }
void _substitute_symbols(const hfst::HfstSymbolSubstitutions &substitutions) { self->substitute_symbols(substitutions); } // alias for the previous function which is shadowed
void _substitute_symbol_pairs(const hfst::HfstSymbolPairSubstitutions &substitutions) { self->substitute_symbol_pairs(substitutions); } // alias for the previous function which is shadowed
void set_final_weights(float weight, bool increment=false) { self->set_final_weights(weight, increment); };
void push_weights_to_start() { self->push_weights(hfst::TO_INITIAL_STATE); };
void push_weights_to_end() { self->push_weights(hfst::TO_FINAL_STATE); };
// And some aliases:
// 'union' is a reserved word in python, so it cannot be used as an alias for function 'disjunct'
void minus(const HfstTransducer& t, bool harmonize=true) { $self->subtract(t, harmonize); }
void conjunct(const HfstTransducer& t, bool harmonize=true) { $self->intersect(t, harmonize); }
// Then the actual extensions:
void lookup_optimize() { self->convert(hfst::HFST_OLW_TYPE); }
void remove_optimization() { self->convert(hfst::get_default_fst_type()); }
HfstTransducer() { return hfst::empty_transducer(); }
HfstTransducer(const hfst::HfstTransducer & t) { return hfst::copy_hfst_transducer(t); }
HfstTransducer(const hfst::implementations::HfstBasicTransducer & t) { return hfst::copy_hfst_transducer_from_basic_transducer(t); }
HfstTransducer(const hfst::implementations::HfstBasicTransducer & t, hfst::ImplementationType impl) { return hfst::copy_hfst_transducer_from_basic_transducer(t, impl); }
~HfstTransducer()
{
if ($self->get_type() == hfst::UNSPECIFIED_TYPE || $self->get_type() == hfst::ERROR_TYPE)
{
return;
}
delete $self;
}
// For python's 'print'
char *__str__() {
std::ostringstream oss;
hfst::implementations::HfstBasicTransducer fsm(*$self);
fsm.write_in_att_format(oss,true);
return strdup(oss.str().c_str());
}
void write(hfst::HfstOutputStream & os) { (void) os.redirect(*$self); }
hfst::HfstTwoLevelPaths _extract_shortest_paths()
{
hfst::HfstTwoLevelPaths results;
$self->extract_shortest_paths(results);
return results;
}
hfst::HfstTwoLevelPaths _extract_longest_paths(bool obey_flags)
{
hfst::HfstTwoLevelPaths results;
$self->extract_longest_paths(results, obey_flags);
return results;
}
hfst::HfstTwoLevelPaths _extract_paths(int max_num=-1, int cycles=-1) const throw(TransducerIsCyclicException)
{
hfst::HfstTwoLevelPaths results;
$self->extract_paths(results, max_num, cycles);
return results;
}
hfst::HfstTwoLevelPaths _extract_paths_fd(int max_num=-1, int cycles=-1, bool filter_fd=true) const throw(TransducerIsCyclicException)
{
hfst::HfstTwoLevelPaths results;
$self->extract_paths_fd(results, max_num, cycles, filter_fd);
return results;
}
hfst::HfstTwoLevelPaths _extract_random_paths(int max_num) const
{
hfst::HfstTwoLevelPaths results;
$self->extract_random_paths(results, max_num);
return results;
}
hfst::HfstTwoLevelPaths _extract_random_paths_fd(int max_num, bool filter_fd) const
{
hfst::HfstTwoLevelPaths results;
$self->extract_random_paths_fd(results, max_num, filter_fd);
return results;
}
HfstOneLevelPaths _lookup_vector(const StringVector& s, int limit = -1, double time_cutoff = 0.0) const throw(FunctionNotImplementedException)
{
return hfst::lookup_vector($self, false /*fd*/, s, limit, time_cutoff);
}
HfstOneLevelPaths _lookup_fd_vector(const StringVector& s, int limit = -1, double time_cutoff = 0.0) const throw(FunctionNotImplementedException)
{
return hfst::lookup_vector($self, true /*fd*/, s, limit, time_cutoff);
}
HfstOneLevelPaths _lookup_fd_string(const std::string& s, int limit = -1, double time_cutoff = 0.0) const throw(FunctionNotImplementedException)
{
return hfst::lookup_string($self, true /*fd*/, s, limit, time_cutoff);
}
HfstOneLevelPaths _lookup_string(const std::string & s, int limit = -1, double time_cutoff = 0.0) const throw(FunctionNotImplementedException)
{
return hfst::lookup_string($self, false /*fd*/, s, limit, time_cutoff);
}
%pythoncode %{
def copy(self):
"""
Return a deep copy of the transducer.
"""
return HfstTransducer(self)
def write_to_file(self, filename_):
"""
Write the transducer in binary format to file *filename_*.
"""
ostr = HfstOutputStream(filename=filename_, type=self.get_type(), hfst_format=True)
ostr.write(self)
ostr.close()
def read_from_file(filename_):
"""
Read a binary transducer from file *filename_*.
"""
istr = HfstInputStream(filename_)
tr = istr.read()
istr.close()
return tr
def write_prolog(self, f, write_weights=True):
"""
Write the transducer in prolog format with name *name* to file *f*,
*write_weights* defined whether weights are written.
Parameters
----------
* `f` :
A python file where the transducer is written.
* `write_weights` :
Whether weights are written.
"""
fsm = HfstBasicTransducer(self)
fsm.name = self.get_name()
prologstr = fsm.get_prolog_string(write_weights)
f.write(prologstr)
def write_xfst(self, f, write_weights=True):
"""
Write the transducer in xfst format to file *f*, *write_weights* defined whether
weights are written.
Parameters
----------
* `f` :
A python file where transducer is written.
* `write_weights` :
Whether weights are written.
"""
fsm = HfstBasicTransducer(self)
fsm.name = self.get_name()
xfststr = fsm.get_xfst_string(write_weights)
f.write(xfst)
def write_att(self, f, write_weights=True):
"""
Write the transducer in AT&T format to file *f*, *write_weights* defined whether
weights are written.
Parameters
----------
* `f` :
A python file where transducer is written.
* `write_weights` :
Whether weights are written.
"""
fsm = HfstBasicTransducer(self)
fsm.name = self.get_name()
attstr = fsm.get_att_string(write_weights)
f.write(attstr)
def lookup(self, input, **kvargs):
"""
Lookup string *input*.
Parameters
----------
* `input` :
The input. A string or a pre-tokenized tuple of symbols (i.e. a tuple of strings).
* `kvargs` :
Possible parameters and their default values are: obey_flags=True,
max_number=-1, time_cutoff=0.0, output='tuple'
* `obey_flags` :
Whether flag diacritics are obeyed. Always True for HFST_OL(W)_TYPE transducers.
* `max_number` :
Maximum number of results returned, defaults to -1, i.e. infinity.
* `time_cutoff` :
How long the function can search for results before returning, expressed in
seconds. Defaults to 0.0, i.e. infinitely. Always 0.0 for transducers that are
not of HFST_OL(W)_TYPE.
* `output` :
Possible values are 'tuple', 'text' and 'raw', 'tuple' being the default.
Note: This function has an efficient implementation only for optimized lookup format
(hfst.types.HFST_OL_TYPE or hfst.types.HFST_OLW_TYPE). Other formats perform the
lookup via composition. Consider converting the transducer to optimized lookup format
or to a HfstBasicTransducer. Conversion to HFST_OL(W)_TYPE might take a while but the
lookup is fast. Conversion to HfstBasicTransducer is quick but lookup is slower.
"""
obey_flags=True
max_number=-1
time_cutoff=0.0
output='tuple' # 'tuple' (default), 'text', 'raw'
for k,v in kvargs.items():
if k == 'obey_flags':
if v == 'True':
pass
elif v == 'False':
obey_flags=False
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'True' and 'False'.")
elif k == 'output':
if v == 'text':
output='text'
elif v == 'raw':
output='raw'
elif v == 'tuple':
output='tuple'
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'tuple' (default), 'text', 'raw'.")
elif k == 'max_number' :
max_number=v
elif k == 'time_cutoff' :
time_cutoff=v
else:
print('Warning: ignoring unknown argument %s.' % (k))
retval=0
if isinstance(input, tuple):
if obey_flags:
retval=self._lookup_fd_vector(input, max_number, time_cutoff)
else:
retval=self._lookup_vector(input, max_number, time_cutoff)
elif isinstance(input, str):
if obey_flags:
retval=self._lookup_fd_string(input, max_number, time_cutoff)
else:
retval=self._lookup_string(input, max_number, time_cutoff)
else:
try:
if obey_flags:
retval=self._lookup_fd_string(str(input), max_number, time_cutoff)
else:
retval=self._lookup_string(str(input), max_number, time_cutoff)
except:
raise RuntimeError('Input argument must be string or tuple.')
if output == 'text':
return one_level_paths_to_string(retval)
elif output == 'tuple':
return _one_level_paths_to_tuple(retval)
else:
return retval
def extract_longest_paths(self, **kvargs):
"""
Extract longest paths of the transducer.
Parameters
----------
* `kvargs` :
Possible parameters and their default values are: obey_flags=True,
output='dict'
* `obey_flags` :
Whether flag diacritics are obeyed. The default is True.
* `output` :
Possible values are 'dict', 'text' and 'raw', 'dict' being the default.
"""
obey_flags=True
output='dict' # 'dict' (default), 'text', 'raw'
for k,v in kvargs.items():
if k == 'obey_flags':
if v == 'True':
pass
elif v == 'False':
obey_flags=False
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'True' and 'False'.")
elif k == 'output':
if v == 'text':
output == 'text'
elif v == 'raw':
output='raw'
elif v == 'dict':
output='dict'
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'dict' (default), 'text', 'raw'.")
else:
print('Warning: ignoring unknown argument %s.' % (k))
retval = self._extract_longest_paths(obey_flags)
if output == 'text':
return two_level_paths_to_string(retval)
elif output == 'dict':
return _two_level_paths_to_dict(retval)
else:
return retval
def extract_shortest_paths(self, **kvargs):
"""
Extract shortest paths of the transducer.
Parameters
----------
* `kvargs` :
Possible parameters and their default values are: obey_flags=True.
* `output` :
Possible values are 'dict', 'text' and 'raw', 'dict' being the default.
"""
output='dict' # 'dict' (default), 'text', 'raw'
for k,v in kvargs.items():
if k == 'output':
if v == 'text':
output == 'text'
elif v == 'raw':
output='raw'
elif v == 'dict':
output='dict'
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'dict' (default), 'text', 'raw'.")
else:
print('Warning: ignoring unknown argument %s.' % (k))
retval = self._extract_shortest_paths()
if output == 'text':
return two_level_paths_to_string(retval)
elif output == 'dict':
return _two_level_paths_to_dict(retval)
else:
return retval
def extract_paths(self, **kvargs):
"""
Extract paths that are recognized by the transducer.
Parameters
----------
* `kvargs` :
Arguments recognized are filter_flags, max_cycles, max_number, obey_flags,
output, random.
* `filter_flags` :
Whether flags diacritics are filtered out from the result (default True).
* `max_cycles` :
Indicates how many times a cycle will be followed, with negative numbers
indicating unlimited (default -1 i.e. unlimited).
* `max_number` :
The total number of resulting strings is capped at this value, with 0 or
negative indicating unlimited (default -1 i.e. unlimited).
* `obey_flags` :
Whether flag diacritics are validated (default True).
* `output` :
Output format. Values recognized: 'text' (as a string, separated by
newlines), 'raw' (a dictionary that maps each input string into a list of
tuples of an output string and a weight), 'dict' (a dictionary that maps
each input string into a tuple of tuples of an output string and a weight,
the default).
* `random` :
Whether result strings are fetched randomly (default False).
Returns
-------
The extracted strings. *output* controls how they are represented.
pre: The transducer must be acyclic, if both *max_number* and *max_cycles* have
unlimited values. Else a hfst.exceptions.TransducerIsCyclicException will be
thrown.
An example:
>>> tr = hfst.regex('a:b+ (a:c+)')
>>> print(tr)
0 1 a b 0.000000
1 1 a b 0.000000
1 2 a c 0.000000
1 0.000000
2 2 a c 0.000000
2 0.000000
>>> print(tr.extract_paths(max_cycles=1, output='text'))
a:b 0
aa:bb 0
aaa:bbc 0
aaaa:bbcc 0
aa:bc 0
aaa:bcc 0
>>> print(tr.extract_paths(max_number=4, output='text'))
a:b 0
aa:bc 0
aaa:bcc 0
aaaa:bccc 0
>>> print(tr.extract_paths(max_cycles=1, max_number=4, output='text'))
a:b 0
aa:bb 0
aa:bc 0
aaa:bcc 0
Exceptions
----------
* `TransducerIsCyclicException` :
See also: hfst.HfstTransducer.n_best
"""
obey_flags=True
filter_flags=True
max_cycles=-1
max_number=-1
random=False
output='dict' # 'dict' (default), 'text', 'raw'
for k,v in kvargs.items():
if k == 'obey_flags' :
if v == 'True':
pass
elif v == 'False':
obey_flags=False
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'True' and 'False'.")
elif k == 'filter_flags' :
if v == 'True':
pass
elif v == 'False':
filter_flags=False
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'True' and 'False'.")
elif k == 'max_cycles' :
max_cycles=v
elif k == 'max_number' :
max_number=v
elif k == 'random' :
if v == 'False':
pass
elif v == 'True':
random=True
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'True' and 'False'.")
elif k == 'output':
if v == 'text':
output = 'text'
elif v == 'raw':
output='raw'
elif v == 'dict':
output='dict'
else:
print('Warning: ignoring argument %s as it has value %s.' % (k, v))
print("Possible values are 'dict' (default), 'text', 'raw'.")
else:
print('Warning: ignoring unknown argument %s.' % (k))
retval=0
if obey_flags :
if random :
retval=self._extract_random_paths_fd(max_number, filter_flags)
else :
retval=self._extract_paths_fd(max_number, max_cycles)
else :
if random :
retval=self._extract_random_paths(max_number)
else :
retval=self._extract_paths(max_number, max_cycles)
if output == 'text':
return two_level_paths_to_string(retval)
elif output == 'dict':
return _two_level_paths_to_dict(retval)
else:
return retval
def substitute(self, s, S=None, **kvargs):
"""
Substitute symbols or transitions in the transducer.
Parameters
----------
* `s` :
The symbol or transition to be substituted. Can also be a dictionary of
substitutions, if S == None.
* `S` :
The symbol, transition, a tuple of transitions or a transducer
(hfst.HfstTransducer) that substitutes *s*.
* `kvargs` :
Arguments recognized are 'input' and 'output', their values can be False or
True, True being the default. These arguments are valid only if *s* and *S*
are strings, else they are ignored.
* `input` :
Whether substitution is performed on input side, defaults to True. Valid
only if *s* and *S* are strings.
* `output` :
Whether substitution is performed on output side, defaults to True. Valid
only if *s* and \\ S are strings.
For more information, see hfst.HfstBasicTransducer.substitute. The function
works similarly, with the exception of argument *S*, which must be
hfst.HfstTransducer instead of hfst.HfstBasicTransducer.
See also: hfst.HfstBasicTransducer.substitute
"""
if S == None:
if not isinstance(s, dict):
raise RuntimeError('Sole input argument must be a dictionary.')
subst_type=""
for k, v in s.items():
if _is_string(k):
if subst_type == "":
subst_type="string"
elif subst_type == "string pair":
raise RuntimeError('')
if not _is_string(v):
raise RuntimeError('')
elif _is_string_pair(k):
if subst_type == "":
subst_type="string pair"
elif subst_type == "string":
raise RuntimeError('')
if not _is_string_pair(v):
raise RuntimeError('')
else:
raise RuntimeError('')
if subst_type == "string":
return self._substitute_symbols(s)
else:
return self._substitute_symbol_pairs(s)
if _is_string(s):
if _is_string(S):
input=True
output=True
for k,v in kvargs.items():
if k == 'input':
if v == False:
input=False
elif k == 'output':
if v == False:
output=False
else:
raise RuntimeError('Free argument not recognized.')
return self._substitute_symbol(s, S, input, output)
else:
raise RuntimeError('...')
elif _is_string_pair(s):
if _is_string_pair(S):
return self._substitute_symbol_pair(s, S)
elif _is_string_pair_vector(S):
return self._substitute_symbol_pair_with_set(s, S)
elif isinstance(S, HfstTransducer):
return self._substitute_symbol_pair_with_transducer(s, S, True)
else:
raise RuntimeError('...')
else:
raise RuntimeError('...')
%}
};
}; // class HfstTransducer
// *** HfstOutputStream *** //
hfst::HfstOutputStream * create_hfst_output_stream(const std::string & filename, hfst::ImplementationType type, bool hfst_format);
class HfstOutputStream
{
public:
~HfstOutputStream(void);
HfstOutputStream &flush();
void close(void);
%extend {
void write(hfst::HfstTransducer transducer) throw(StreamIsClosedException) { $self->redirect(transducer); }
HfstOutputStream() { return new hfst::HfstOutputStream(hfst::get_default_fst_type()); }
%pythoncode %{
def __init__(self, **kvargs):
"""
Open a stream for writing binary transducers. Note: hfst.HfstTransducer.write_to_file
is probably the easiest way to write a single binary transducer to a file.
Parameters
----------
* `kvargs` :
Arguments recognized are filename, hfst_format, type.
* `filename` :
The name of the file where transducers are written. If the file exists, it
is overwritten. If *filename* is not given, transducers are written to
standard output.
* `hfst_format` :
Whether transducers are written in hfst format (default is True) or as such
in their backend format.
* `type` :
The type of the transducers that will be written to the stream. Default is
hfst.get_default_fst_type().
Examples:
# a stream for writing default type transducers in hfst format to standard output
ostr = hfst.HfstOutputStream()
transducer = hfst.regex('foo:bar::0.5')
ostr.write(transducer)
ostr.flush()
# a stream for writing native sfst type transducers to a file
ostr = hfst.HfstOutputStream(filename='transducer.sfst', hfst_format=False, type=hfst.types.SFST_TYPE)
transducer1 = hfst.regex('foo:bar')
transducer1.convert(hfst.types.SFST_TYPE) # if not set as the default type
transducer2 = hfst.regex('bar:baz')
transducer2.convert(hfst.types.SFST_TYPE) # if not set as the default type
ostr.write(transducer1)
ostr.write(transducer2)
ostr.flush()
ostr.close()
"""
filename = ""
hfst_format = True
type = _libhfst.get_default_fst_type()
for k,v in kvargs.items():
if k == 'filename':
filename = v
if k == 'hfst_format':
hfst_format = v
if k == 'type':
type = v
if filename == "":
self.this = _libhfst.create_hfst_output_stream("", type, hfst_format)
else:
self.this = _libhfst.create_hfst_output_stream(filename, type, hfst_format)
%}
}
}; // class HfstOutputStream
// *** HfstInputStream *** //
class HfstInputStream
{
public:
HfstInputStream(void) throw(StreamNotReadableException, NotTransducerStreamException, EndOfStreamException, TransducerHeaderException);
HfstInputStream(const std::string &filename) throw(StreamNotReadableException, NotTransducerStreamException, EndOfStreamException, TransducerHeaderException);
~HfstInputStream(void);
void close(void);
bool is_eof(void);
bool is_bad(void);
bool is_good(void);
ImplementationType get_type(void) const throw(TransducerTypeMismatchException);
%extend {
hfst::HfstTransducer * read() throw (EndOfStreamException) { return new hfst::HfstTransducer(*($self)); }
%pythoncode %{
def __iter__(self):
"""
Return *self*. Needed for 'for ... in' statement.
"""
return self
def next(self):
"""
Read next transducer from stream and return it. Needed for 'for ... in' statement.
"""
if self.is_eof():
raise StopIteration
else:
return self.read();
def __next__(self):
"""
Read next transducer from stream and return it. Needed for 'for ... in' statement.
"""
return self.next()
%}
}