repo_id
stringlengths
18
103
file_path
stringlengths
30
136
content
stringlengths
2
3.36M
__index_level_0__
int64
0
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/bin/fstencode.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/flags.h> DEFINE_bool(encode_labels, false, "Encode output labels"); DEFINE_bool(encode_weights, false, "Encode weights"); DEFINE_bool(encode_reuse, false, "Re-use existing codex"); DEFINE_bool(decode, false, "Decode labels and/or weights"); int fstencode_main(int argc, char **argv); int main(int argc, char **argv) { return fstencode_main(argc, argv); }
0
coqui_public_repos/STT/native_client/kenlm/util
coqui_public_repos/STT/native_client/kenlm/util/double-conversion/utils.h
// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DOUBLE_CONVERSION_UTILS_H_ #define DOUBLE_CONVERSION_UTILS_H_ // Use DOUBLE_CONVERSION_NON_PREFIXED_MACROS to get unprefixed macros as was // the case in double-conversion releases prior to 3.1.6 #include <cstdlib> #include <cstring> #include <cassert> #ifndef DOUBLE_CONVERSION_ASSERT #define DOUBLE_CONVERSION_ASSERT(condition) \ assert(condition) #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(ASSERT) #define ASSERT DOUBLE_CONVERSION_ASSERT #endif #ifndef DOUBLE_CONVERSION_UNIMPLEMENTED #define DOUBLE_CONVERSION_UNIMPLEMENTED() (abort()) #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(UNIMPLEMENTED) #define UNIMPLEMENTED DOUBLE_CONVERSION_UNIMPLEMENTED #endif #ifndef DOUBLE_CONVERSION_NO_RETURN #ifdef _MSC_VER #define DOUBLE_CONVERSION_NO_RETURN __declspec(noreturn) #else #define DOUBLE_CONVERSION_NO_RETURN __attribute__((noreturn)) #endif #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(NO_RETURN) #define NO_RETURN DOUBLE_CONVERSION_NO_RETURN #endif #ifndef DOUBLE_CONVERSION_UNREACHABLE #ifdef _MSC_VER void DOUBLE_CONVERSION_NO_RETURN abort_noreturn(); inline void abort_noreturn() { abort(); } #define DOUBLE_CONVERSION_UNREACHABLE() (abort_noreturn()) #else #define DOUBLE_CONVERSION_UNREACHABLE() (abort()) #endif #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(UNREACHABLE) #define UNREACHABLE DOUBLE_CONVERSION_UNREACHABLE #endif // Not all compilers support __has_attribute and combining a check for both // ifdef and __has_attribute on the same preprocessor line isn't portable. #ifdef __has_attribute # define DOUBLE_CONVERSION_HAS_ATTRIBUTE(x) __has_attribute(x) #else # define DOUBLE_CONVERSION_HAS_ATTRIBUTE(x) 0 #endif #ifndef DOUBLE_CONVERSION_UNUSED #if DOUBLE_CONVERSION_HAS_ATTRIBUTE(unused) #define DOUBLE_CONVERSION_UNUSED __attribute__((unused)) #else #define DOUBLE_CONVERSION_UNUSED #endif #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(UNUSED) #define UNUSED DOUBLE_CONVERSION_UNUSED #endif #if DOUBLE_CONVERSION_HAS_ATTRIBUTE(uninitialized) #define DOUBLE_CONVERSION_STACK_UNINITIALIZED __attribute__((uninitialized)) #else #define DOUBLE_CONVERSION_STACK_UNINITIALIZED #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(STACK_UNINITIALIZED) #define STACK_UNINITIALIZED DOUBLE_CONVERSION_STACK_UNINITIALIZED #endif // Double operations detection based on target architecture. // Linux uses a 80bit wide floating point stack on x86. This induces double // rounding, which in turn leads to wrong results. // An easy way to test if the floating-point operations are correct is to // evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then // the result is equal to 89255e-22. // The best way to test this, is to create a division-function and to compare // the output of the division with the expected result. (Inlining must be // disabled.) // On Linux,x86 89255e-22 != Div_double(89255.0/1e22) // // For example: /* // -- in div.c double Div_double(double x, double y) { return x / y; } // -- in main.c double Div_double(double x, double y); // Forward declaration. int main(int argc, char** argv) { return Div_double(89255.0, 1e22) == 89255e-22; } */ // Run as follows ./main || echo "correct" // // If it prints "correct" then the architecture should be here, in the "correct" section. #if defined(_M_X64) || defined(__x86_64__) || \ defined(__ARMEL__) || defined(__avr32__) || defined(_M_ARM) || defined(_M_ARM64) || \ defined(__hppa__) || defined(__ia64__) || \ defined(__mips__) || \ defined(__loongarch__) || \ defined(__nios2__) || defined(__ghs) || \ defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \ defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \ defined(__sparc__) || defined(__sparc) || defined(__s390__) || \ defined(__SH4__) || defined(__alpha__) || \ defined(_MIPS_ARCH_MIPS32R2) || defined(__ARMEB__) ||\ defined(__AARCH64EL__) || defined(__aarch64__) || defined(__AARCH64EB__) || \ defined(__riscv) || defined(__e2k__) || \ defined(__or1k__) || defined(__arc__) || defined(__ARC64__) || \ defined(__microblaze__) || defined(__XTENSA__) || \ defined(__EMSCRIPTEN__) || defined(__wasm32__) #define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 #elif defined(__mc68000__) || \ defined(__pnacl__) || defined(__native_client__) #undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS #elif defined(_M_IX86) || defined(__i386__) || defined(__i386) #if defined(_WIN32) // Windows uses a 64bit wide floating point stack. #define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 #else #undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS #endif // _WIN32 #else #error Target architecture was not detected as supported by Double-Conversion. #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(CORRECT_DOUBLE_OPERATIONS) #define CORRECT_DOUBLE_OPERATIONS DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS #endif #if defined(_WIN32) && !defined(__MINGW32__) typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; // NOLINT typedef unsigned short uint16_t; // NOLINT typedef int int32_t; typedef unsigned int uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; // intptr_t and friends are defined in crtdefs.h through stdio.h. #else #include <stdint.h> #endif typedef uint16_t uc16; // The following macro works on both 32 and 64-bit platforms. // Usage: instead of writing 0x1234567890123456 // write DOUBLE_CONVERSION_UINT64_2PART_C(0x12345678,90123456); #define DOUBLE_CONVERSION_UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u)) #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(UINT64_2PART_C) #define UINT64_2PART_C DOUBLE_CONVERSION_UINT64_2PART_C #endif // The expression DOUBLE_CONVERSION_ARRAY_SIZE(a) is a compile-time constant of type // size_t which represents the number of elements of the given // array. You should only use DOUBLE_CONVERSION_ARRAY_SIZE on statically allocated // arrays. #ifndef DOUBLE_CONVERSION_ARRAY_SIZE #define DOUBLE_CONVERSION_ARRAY_SIZE(a) \ ((sizeof(a) / sizeof(*(a))) / \ static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(ARRAY_SIZE) #define ARRAY_SIZE DOUBLE_CONVERSION_ARRAY_SIZE #endif // A macro to disallow the evil copy constructor and operator= functions // This should be used in the private: declarations for a class #ifndef DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN #define DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(DC_DISALLOW_COPY_AND_ASSIGN) #define DC_DISALLOW_COPY_AND_ASSIGN DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN #endif // A macro to disallow all the implicit constructors, namely the // default constructor, copy constructor and operator= functions. // // This should be used in the private: declarations for a class // that wants to prevent anyone from instantiating it. This is // especially useful for classes containing only static methods. #ifndef DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS #define DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ TypeName(); \ DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(TypeName) #endif #if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(DC_DISALLOW_IMPLICIT_CONSTRUCTORS) #define DC_DISALLOW_IMPLICIT_CONSTRUCTORS DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS #endif namespace kenlm_double_conversion { inline int StrLength(const char* string) { size_t length = strlen(string); DOUBLE_CONVERSION_ASSERT(length == static_cast<size_t>(static_cast<int>(length))); return static_cast<int>(length); } // This is a simplified version of V8's Vector class. template <typename T> class Vector { public: Vector() : start_(NULL), length_(0) {} Vector(T* data, int len) : start_(data), length_(len) { DOUBLE_CONVERSION_ASSERT(len == 0 || (len > 0 && data != NULL)); } // Returns a vector using the same backing storage as this one, // spanning from and including 'from', to but not including 'to'. Vector<T> SubVector(int from, int to) { DOUBLE_CONVERSION_ASSERT(to <= length_); DOUBLE_CONVERSION_ASSERT(from < to); DOUBLE_CONVERSION_ASSERT(0 <= from); return Vector<T>(start() + from, to - from); } // Returns the length of the vector. int length() const { return length_; } // Returns whether or not the vector is empty. bool is_empty() const { return length_ == 0; } // Returns the pointer to the start of the data in the vector. T* start() const { return start_; } // Access individual vector elements - checks bounds in debug mode. T& operator[](int index) const { DOUBLE_CONVERSION_ASSERT(0 <= index && index < length_); return start_[index]; } T& first() { return start_[0]; } T& last() { return start_[length_ - 1]; } void pop_back() { DOUBLE_CONVERSION_ASSERT(!is_empty()); --length_; } private: T* start_; int length_; }; // Helper class for building result strings in a character buffer. The // purpose of the class is to use safe operations that checks the // buffer bounds on all operations in debug mode. class StringBuilder { public: StringBuilder(char* buffer, int buffer_size) : buffer_(buffer, buffer_size), position_(0) { } ~StringBuilder() { if (!is_finalized()) Finalize(); } int size() const { return buffer_.length(); } // Get the current position in the builder. int position() const { DOUBLE_CONVERSION_ASSERT(!is_finalized()); return position_; } // Reset the position. void Reset() { position_ = 0; } // Add a single character to the builder. It is not allowed to add // 0-characters; use the Finalize() method to terminate the string // instead. void AddCharacter(char c) { DOUBLE_CONVERSION_ASSERT(c != '\0'); DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ < buffer_.length()); buffer_[position_++] = c; } // Add an entire string to the builder. Uses strlen() internally to // compute the length of the input string. void AddString(const char* s) { AddSubstring(s, StrLength(s)); } // Add the first 'n' characters of the given string 's' to the // builder. The input string must have enough characters. void AddSubstring(const char* s, int n) { DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ + n < buffer_.length()); DOUBLE_CONVERSION_ASSERT(static_cast<size_t>(n) <= strlen(s)); memmove(&buffer_[position_], s, n); position_ += n; } // Add character padding to the builder. If count is non-positive, // nothing is added to the builder. void AddPadding(char c, int count) { for (int i = 0; i < count; i++) { AddCharacter(c); } } // Finalize the string by 0-terminating it and returning the buffer. char* Finalize() { DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ < buffer_.length()); buffer_[position_] = '\0'; // Make sure nobody managed to add a 0-character to the // buffer while building the string. DOUBLE_CONVERSION_ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_)); position_ = -1; DOUBLE_CONVERSION_ASSERT(is_finalized()); return buffer_.start(); } private: Vector<char> buffer_; int position_; bool is_finalized() const { return position_ < 0; } DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder); }; // The type-based aliasing rule allows the compiler to assume that pointers of // different types (for some definition of different) never alias each other. // Thus the following code does not work: // // float f = foo(); // int fbits = *(int*)(&f); // // The compiler 'knows' that the int pointer can't refer to f since the types // don't match, so the compiler may cache f in a register, leaving random data // in fbits. Using C++ style casts makes no difference, however a pointer to // char data is assumed to alias any other pointer. This is the 'memcpy // exception'. // // Bit_cast uses the memcpy exception to move the bits from a variable of one // type of a variable of another type. Of course the end result is likely to // be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005) // will completely optimize BitCast away. // // There is an additional use for BitCast. // Recent gccs will warn when they see casts that may result in breakage due to // the type-based aliasing rule. If you have checked that there is no breakage // you can use BitCast to cast one pointer type to another. This confuses gcc // enough that it can no longer see that you have cast one pointer type to // another thus avoiding the warning. template <class Dest, class Source> Dest BitCast(const Source& source) { // Compile time assertion: sizeof(Dest) == sizeof(Source) // A compile error here means your Dest and Source have different sizes. #if __cplusplus >= 201103L static_assert(sizeof(Dest) == sizeof(Source), "source and destination size mismatch"); #else DOUBLE_CONVERSION_UNUSED typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1]; #endif Dest dest; memmove(&dest, &source, sizeof(dest)); return dest; } template <class Dest, class Source> Dest BitCast(Source* source) { return BitCast<Dest>(reinterpret_cast<uintptr_t>(source)); } } // namespace kenlm_double_conversion #endif // DOUBLE_CONVERSION_UTILS_H_
0
coqui_public_repos/inference-engine/third_party
coqui_public_repos/inference-engine/third_party/kenlm/README.coqui
KenLM source downloaded from https://github.com/kpu/kenlm on 2020/01/15 commit b9f35777d112ce2fc10bd3986302517a16dc3883 This corresponds to https://github.com/kpu/kenlm/commit/b9f35777d112ce2fc10bd3986302517a16dc3883 The following procedure was run to remove unneeded files: cd kenlm rm -rf windows include lm/filter lm/builder util/stream util/getopt.* python This was done in order to ensure uniqueness of double_conversion: git grep 'double_conversion' | cut -d':' -f1 | sort | uniq | xargs sed -ri 's/double_conversion/kenlm_double_conversion/g' Cherry-pick fix for MSVC: curl -vsSL https://github.com/kpu/kenlm/commit/d70e28403f07e88b276c6bd9f162d2a428530f2e.patch | git am -p1 --directory=native_client/kenlm
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/randgen.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Classes and functions to generate random paths through an FST. #ifndef FST_RANDGEN_H_ #define FST_RANDGEN_H_ #include <math.h> #include <stddef.h> #include <limits> #include <map> #include <memory> #include <random> #include <utility> #include <vector> #include <fst/log.h> #include <fst/accumulator.h> #include <fst/cache.h> #include <fst/dfs-visit.h> #include <fst/float-weight.h> #include <fst/fst-decl.h> #include <fst/fst.h> #include <fst/mutable-fst.h> #include <fst/properties.h> #include <fst/util.h> #include <fst/weight.h> namespace fst { // The RandGenFst class is roughly similar to ArcMapFst in that it takes two // template parameters denoting the input and output arc types. However, it also // takes an additional template parameter which specifies a sampler object which // samples (with replacement) arcs from an FST state. The sampler in turn takes // a template parameter for a selector object which actually chooses the arc. // // Arc selector functors are used to select a random transition given an FST // state s, returning a number N such that 0 <= N <= NumArcs(s). If N is // NumArcs(s), then the final weight is selected; otherwise the N-th arc is // selected. It is assumed these are not applied to any state which is neither // final nor has any arcs leaving it. // Randomly selects a transition using the uniform distribution. This class is // not thread-safe. template <class Arc> class UniformArcSelector { public: using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; // Constructs a selector with a non-deterministic seed. UniformArcSelector() : rand_(std::random_device()()) {} // Constructs a selector with a given seed. explicit UniformArcSelector(uint64_t seed) : rand_(seed) {} size_t operator()(const Fst<Arc> &fst, StateId s) const { const auto n = fst.NumArcs(s) + (fst.Final(s) != Weight::Zero()); return static_cast<size_t>( std::uniform_int_distribution<>(0, n - 1)(rand_)); } private: mutable std::mt19937_64 rand_; }; // Randomly selects a transition w.r.t. the weights treated as negative log // probabilities after normalizing for the total weight leaving the state. Zero // transitions are disregarded. It assumed that Arc::Weight::Value() accesses // the floating point representation of the weight. This class is not // thread-safe. template <class Arc> class LogProbArcSelector { public: using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; // Constructs a selector with a non-deterministic seed. LogProbArcSelector() : rand_(std::random_device()()) {} // Constructs a selector with a given seed. explicit LogProbArcSelector(uint64_t seed) : rand_(seed) {} size_t operator()(const Fst<Arc> &fst, StateId s) const { // Finds total weight leaving state. auto sum = Log64Weight::Zero(); ArcIterator<Fst<Arc>> aiter(fst, s); for (; !aiter.Done(); aiter.Next()) { const auto &arc = aiter.Value(); sum = Plus(sum, to_log_weight_(arc.weight)); } sum = Plus(sum, to_log_weight_(fst.Final(s))); const double threshold = std::uniform_real_distribution<>(0, exp(-sum.Value()))(rand_); auto p = Log64Weight::Zero(); size_t n = 0; for (aiter.Reset(); !aiter.Done(); aiter.Next(), ++n) { p = Plus(p, to_log_weight_(aiter.Value().weight)); if (exp(-p.Value()) > threshold) return n; } return n; } private: mutable std::mt19937_64 rand_; WeightConvert<Weight, Log64Weight> to_log_weight_; }; // Useful alias when using StdArc. using StdArcSelector = LogProbArcSelector<StdArc>; // Same as LogProbArcSelector but use CacheLogAccumulator to cache the weight // accumulation computations. This class is not thread-safe. template <class Arc> class FastLogProbArcSelector : public LogProbArcSelector<Arc> { public: using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using LogProbArcSelector<Arc>::operator(); // Constructs a selector with a non-deterministic seed. FastLogProbArcSelector() : seed_(std::random_device()()), rand_(seed_) {} // Constructs a selector with a given seed. explicit FastLogProbArcSelector(uint64_t seed) : seed_(seed), rand_(seed_) {} size_t operator()(const Fst<Arc> &fst, StateId s, CacheLogAccumulator<Arc> *accumulator) const { accumulator->SetState(s); ArcIterator<Fst<Arc>> aiter(fst, s); // Finds total weight leaving state. const double sum = to_log_weight_(accumulator->Sum(fst.Final(s), &aiter, 0, fst.NumArcs(s))) .Value(); const double r = -log(std::uniform_real_distribution<>(0, 1)(rand_)); Weight w = from_log_weight_(r + sum); aiter.Reset(); return accumulator->LowerBound(w, &aiter); } uint64_t Seed() const { return seed_; } private: const uint64_t seed_; mutable std::mt19937_64 rand_; WeightConvert<Weight, Log64Weight> to_log_weight_; WeightConvert<Log64Weight, Weight> from_log_weight_; }; // Random path state info maintained by RandGenFst and passed to samplers. template <typename Arc> struct RandState { using StateId = typename Arc::StateId; StateId state_id; // Current input FST state. size_t nsamples; // Number of samples to be sampled at this state. size_t length; // Length of path to this random state. size_t select; // Previous sample arc selection. const RandState<Arc> *parent; // Previous random state on this path. explicit RandState(StateId state_id, size_t nsamples = 0, size_t length = 0, size_t select = 0, const RandState<Arc> *parent = nullptr) : state_id(state_id), nsamples(nsamples), length(length), select(select), parent(parent) {} RandState() : RandState(kNoStateId) {} }; // This class, given an arc selector, samples, with replacement, multiple random // transitions from an FST's state. This is a generic version with a // straightforward use of the arc selector. Specializations may be defined for // arc selectors for greater efficiency or special behavior. template <class Arc, class Selector> class ArcSampler { public: using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; // The max_length argument may be interpreted (or ignored) by a selector as // it chooses. This generic version interprets this literally. ArcSampler(const Fst<Arc> &fst, const Selector &selector, int32_t max_length = std::numeric_limits<int32_t>::max()) : fst_(fst), selector_(selector), max_length_(max_length) {} // Allow updating FST argument; pass only if changed. ArcSampler(const ArcSampler<Arc, Selector> &sampler, const Fst<Arc> *fst = nullptr) : fst_(fst ? *fst : sampler.fst_), selector_(sampler.selector_), max_length_(sampler.max_length_) { Reset(); } // Samples a fixed number of samples from the given state. The length argument // specifies the length of the path to the state. Returns true if the samples // were collected. No samples may be collected if either there are no // transitions leaving the state and the state is non-final, or if the path // length has been exceeded. Iterator members are provided to read the samples // in the order in which they were collected. bool Sample(const RandState<Arc> &rstate) { sample_map_.clear(); if ((fst_.NumArcs(rstate.state_id) == 0 && fst_.Final(rstate.state_id) == Weight::Zero()) || rstate.length == max_length_) { Reset(); return false; } for (size_t i = 0; i < rstate.nsamples; ++i) { ++sample_map_[selector_(fst_, rstate.state_id)]; } Reset(); return true; } // More samples? bool Done() const { return sample_iter_ == sample_map_.end(); } // Gets the next sample. void Next() { ++sample_iter_; } std::pair<size_t, size_t> Value() const { return *sample_iter_; } void Reset() { sample_iter_ = sample_map_.begin(); } bool Error() const { return false; } private: const Fst<Arc> &fst_; const Selector &selector_; const int32_t max_length_; // Stores (N, K) as described for Value(). std::map<size_t, size_t> sample_map_; std::map<size_t, size_t>::const_iterator sample_iter_; ArcSampler<Arc, Selector> &operator=(const ArcSampler &) = delete; }; // Samples one sample of num_to_sample dimensions from a multinomial // distribution parameterized by a vector of probabilities. The result // container should be pre-initialized (e.g., an empty map or a zeroed vector // sized the same as the vector of probabilities. // probs.size()). template <class Result, class RNG> void OneMultinomialSample(const std::vector<double> &probs, size_t num_to_sample, Result *result, RNG *rng) { // Left-over probability mass. double norm = 0; for (double p : probs) norm += p; // Left-over number of samples needed. for (size_t i = 0; i < probs.size(); ++i) { size_t num_sampled = 0; if (probs[i] > 0) { std::binomial_distribution<> d(num_to_sample, probs[i] / norm); num_sampled = d(*rng); } if (num_sampled != 0) (*result)[i] = num_sampled; norm -= probs[i]; num_to_sample -= num_sampled; } } // Specialization for FastLogProbArcSelector. template <class Arc> class ArcSampler<Arc, FastLogProbArcSelector<Arc>> { public: using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using Accumulator = CacheLogAccumulator<Arc>; using Selector = FastLogProbArcSelector<Arc>; ArcSampler(const Fst<Arc> &fst, const Selector &selector, int32_t max_length = std::numeric_limits<int32_t>::max()) : fst_(fst), selector_(selector), max_length_(max_length), accumulator_(new Accumulator()) { accumulator_->Init(fst); rng_.seed(selector_.Seed()); } ArcSampler(const ArcSampler<Arc, Selector> &sampler, const Fst<Arc> *fst = nullptr) : fst_(fst ? *fst : sampler.fst_), selector_(sampler.selector_), max_length_(sampler.max_length_) { if (fst) { accumulator_.reset(new Accumulator()); accumulator_->Init(*fst); } else { // Shallow copy. accumulator_.reset(new Accumulator(*sampler.accumulator_)); } } bool Sample(const RandState<Arc> &rstate) { sample_map_.clear(); if ((fst_.NumArcs(rstate.state_id) == 0 && fst_.Final(rstate.state_id) == Weight::Zero()) || rstate.length == max_length_) { Reset(); return false; } if (fst_.NumArcs(rstate.state_id) + 1 < rstate.nsamples) { MultinomialSample(rstate); Reset(); return true; } for (size_t i = 0; i < rstate.nsamples; ++i) { ++sample_map_[selector_(fst_, rstate.state_id, accumulator_.get())]; } Reset(); return true; } bool Done() const { return sample_iter_ == sample_map_.end(); } void Next() { ++sample_iter_; } std::pair<size_t, size_t> Value() const { return *sample_iter_; } void Reset() { sample_iter_ = sample_map_.begin(); } bool Error() const { return accumulator_->Error(); } private: using RNG = std::mt19937; // Sample according to the multinomial distribution of rstate.nsamples draws // from p_. void MultinomialSample(const RandState<Arc> &rstate) { p_.clear(); for (ArcIterator<Fst<Arc>> aiter(fst_, rstate.state_id); !aiter.Done(); aiter.Next()) { p_.push_back(exp(-to_log_weight_(aiter.Value().weight).Value())); } if (fst_.Final(rstate.state_id) != Weight::Zero()) { p_.push_back(exp(-to_log_weight_(fst_.Final(rstate.state_id)).Value())); } if (rstate.nsamples < std::numeric_limits<RNG::result_type>::max()) { OneMultinomialSample(p_, rstate.nsamples, &sample_map_, &rng_); } else { for (size_t i = 0; i < p_.size(); ++i) { sample_map_[i] = ceil(p_[i] * rstate.nsamples); } } } const Fst<Arc> &fst_; const Selector &selector_; const int32_t max_length_; // Stores (N, K) for Value(). std::map<size_t, size_t> sample_map_; std::map<size_t, size_t>::const_iterator sample_iter_; std::unique_ptr<Accumulator> accumulator_; RNG rng_; // Random number generator. std::vector<double> p_; // Multinomial parameters. WeightConvert<Weight, Log64Weight> to_log_weight_; }; // Options for random path generation with RandGenFst. The template argument is // a sampler, typically the class ArcSampler. Ownership of the sampler is taken // by RandGenFst. template <class Sampler> struct RandGenFstOptions : public CacheOptions { Sampler *sampler; // How to sample transitions at a state. int32_t npath; // Number of paths to generate. bool weighted; // Is the output tree weighted by path count, or // is it just an unweighted DAG? bool remove_total_weight; // Remove total weight when output is weighted. RandGenFstOptions(const CacheOptions &opts, Sampler *sampler, int32_t npath = 1, bool weighted = true, bool remove_total_weight = false) : CacheOptions(opts), sampler(sampler), npath(npath), weighted(weighted), remove_total_weight(remove_total_weight) {} }; namespace internal { // Implementation of RandGenFst. template <class FromArc, class ToArc, class Sampler> class RandGenFstImpl : public CacheImpl<ToArc> { public: using FstImpl<ToArc>::SetType; using FstImpl<ToArc>::SetProperties; using FstImpl<ToArc>::SetInputSymbols; using FstImpl<ToArc>::SetOutputSymbols; using CacheBaseImpl<CacheState<ToArc>>::PushArc; using CacheBaseImpl<CacheState<ToArc>>::HasArcs; using CacheBaseImpl<CacheState<ToArc>>::HasFinal; using CacheBaseImpl<CacheState<ToArc>>::HasStart; using CacheBaseImpl<CacheState<ToArc>>::SetArcs; using CacheBaseImpl<CacheState<ToArc>>::SetFinal; using CacheBaseImpl<CacheState<ToArc>>::SetStart; using Label = typename FromArc::Label; using StateId = typename FromArc::StateId; using FromWeight = typename FromArc::Weight; using ToWeight = typename ToArc::Weight; RandGenFstImpl(const Fst<FromArc> &fst, const RandGenFstOptions<Sampler> &opts) : CacheImpl<ToArc>(opts), fst_(fst.Copy()), sampler_(opts.sampler), npath_(opts.npath), weighted_(opts.weighted), remove_total_weight_(opts.remove_total_weight), superfinal_(kNoLabel) { SetType("randgen"); SetProperties( RandGenProperties(fst.Properties(kFstProperties, false), weighted_), kCopyProperties); SetInputSymbols(fst.InputSymbols()); SetOutputSymbols(fst.OutputSymbols()); } RandGenFstImpl(const RandGenFstImpl &impl) : CacheImpl<ToArc>(impl), fst_(impl.fst_->Copy(true)), sampler_(new Sampler(*impl.sampler_, fst_.get())), npath_(impl.npath_), weighted_(impl.weighted_), superfinal_(kNoLabel) { SetType("randgen"); SetProperties(impl.Properties(), kCopyProperties); SetInputSymbols(impl.InputSymbols()); SetOutputSymbols(impl.OutputSymbols()); } StateId Start() { if (!HasStart()) { const auto s = fst_->Start(); if (s == kNoStateId) return kNoStateId; SetStart(state_table_.size()); state_table_.emplace_back( new RandState<FromArc>(s, npath_, 0, 0, nullptr)); } return CacheImpl<ToArc>::Start(); } ToWeight Final(StateId s) { if (!HasFinal(s)) Expand(s); return CacheImpl<ToArc>::Final(s); } size_t NumArcs(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<ToArc>::NumArcs(s); } size_t NumInputEpsilons(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<ToArc>::NumInputEpsilons(s); } size_t NumOutputEpsilons(StateId s) { if (!HasArcs(s)) Expand(s); return CacheImpl<ToArc>::NumOutputEpsilons(s); } uint64_t Properties() const override { return Properties(kFstProperties); } // Sets error if found, and returns other FST impl properties. uint64_t Properties(uint64_t mask) const override { if ((mask & kError) && (fst_->Properties(kError, false) || sampler_->Error())) { SetProperties(kError, kError); } return FstImpl<ToArc>::Properties(mask); } void InitArcIterator(StateId s, ArcIteratorData<ToArc> *data) { if (!HasArcs(s)) Expand(s); CacheImpl<ToArc>::InitArcIterator(s, data); } // Computes the outgoing transitions from a state, creating new destination // states as needed. void Expand(StateId s) { if (s == superfinal_) { SetFinal(s, ToWeight::One()); SetArcs(s); return; } SetFinal(s, ToWeight::Zero()); const auto &rstate = *state_table_[s]; sampler_->Sample(rstate); ArcIterator<Fst<FromArc>> aiter(*fst_, rstate.state_id); const auto narcs = fst_->NumArcs(rstate.state_id); for (; !sampler_->Done(); sampler_->Next()) { const auto &sample_pair = sampler_->Value(); const auto pos = sample_pair.first; const auto count = sample_pair.second; double prob = static_cast<double>(count) / rstate.nsamples; if (pos < narcs) { // Regular transition. aiter.Seek(sample_pair.first); const auto &aarc = aiter.Value(); const auto weight = weighted_ ? to_weight_(Log64Weight(-log(prob))) : ToWeight::One(); const ToArc barc(aarc.ilabel, aarc.olabel, weight, state_table_.size()); PushArc(s, barc); auto *nrstate = new RandState<FromArc>(aarc.nextstate, count, rstate.length + 1, pos, &rstate); state_table_.emplace_back(nrstate); } else { // Super-final transition. if (weighted_) { const auto weight = remove_total_weight_ ? to_weight_(Log64Weight(-log(prob))) : to_weight_(Log64Weight(-log(prob * npath_))); SetFinal(s, weight); } else { if (superfinal_ == kNoLabel) { superfinal_ = state_table_.size(); state_table_.emplace_back( new RandState<FromArc>(kNoStateId, 0, 0, 0, nullptr)); } for (size_t n = 0; n < count; ++n) { const ToArc barc(0, 0, ToWeight::One(), superfinal_); PushArc(s, barc); } } } } SetArcs(s); } private: const std::unique_ptr<Fst<FromArc>> fst_; std::unique_ptr<Sampler> sampler_; const int32_t npath_; std::vector<std::unique_ptr<RandState<FromArc>>> state_table_; const bool weighted_; bool remove_total_weight_; StateId superfinal_; WeightConvert<Log64Weight, ToWeight> to_weight_; }; } // namespace internal // FST class to randomly generate paths through an FST, with details controlled // by RandGenOptionsFst. Output format is a tree weighted by the path count. template <class FromArc, class ToArc, class Sampler> class RandGenFst : public ImplToFst<internal::RandGenFstImpl<FromArc, ToArc, Sampler>> { public: using Label = typename FromArc::Label; using StateId = typename FromArc::StateId; using Weight = typename FromArc::Weight; using Store = DefaultCacheStore<FromArc>; using State = typename Store::State; using Impl = internal::RandGenFstImpl<FromArc, ToArc, Sampler>; friend class ArcIterator<RandGenFst<FromArc, ToArc, Sampler>>; friend class StateIterator<RandGenFst<FromArc, ToArc, Sampler>>; RandGenFst(const Fst<FromArc> &fst, const RandGenFstOptions<Sampler> &opts) : ImplToFst<Impl>(std::make_shared<Impl>(fst, opts)) {} // See Fst<>::Copy() for doc. RandGenFst(const RandGenFst<FromArc, ToArc, Sampler> &fst, bool safe = false) : ImplToFst<Impl>(fst, safe) {} // Get a copy of this RandGenFst. See Fst<>::Copy() for further doc. RandGenFst<FromArc, ToArc, Sampler> *Copy(bool safe = false) const override { return new RandGenFst<FromArc, ToArc, Sampler>(*this, safe); } inline void InitStateIterator(StateIteratorData<ToArc> *data) const override; void InitArcIterator(StateId s, ArcIteratorData<ToArc> *data) const override { GetMutableImpl()->InitArcIterator(s, data); } private: using ImplToFst<Impl>::GetImpl; using ImplToFst<Impl>::GetMutableImpl; RandGenFst &operator=(const RandGenFst &) = delete; }; // Specialization for RandGenFst. template <class FromArc, class ToArc, class Sampler> class StateIterator<RandGenFst<FromArc, ToArc, Sampler>> : public CacheStateIterator<RandGenFst<FromArc, ToArc, Sampler>> { public: explicit StateIterator(const RandGenFst<FromArc, ToArc, Sampler> &fst) : CacheStateIterator<RandGenFst<FromArc, ToArc, Sampler>>( fst, fst.GetMutableImpl()) {} }; // Specialization for RandGenFst. template <class FromArc, class ToArc, class Sampler> class ArcIterator<RandGenFst<FromArc, ToArc, Sampler>> : public CacheArcIterator<RandGenFst<FromArc, ToArc, Sampler>> { public: using StateId = typename FromArc::StateId; ArcIterator(const RandGenFst<FromArc, ToArc, Sampler> &fst, StateId s) : CacheArcIterator<RandGenFst<FromArc, ToArc, Sampler>>( fst.GetMutableImpl(), s) { if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s); } }; template <class FromArc, class ToArc, class Sampler> inline void RandGenFst<FromArc, ToArc, Sampler>::InitStateIterator( StateIteratorData<ToArc> *data) const { data->base = new StateIterator<RandGenFst<FromArc, ToArc, Sampler>>(*this); } // Options for random path generation. template <class Selector> struct RandGenOptions { const Selector &selector; // How an arc is selected at a state. int32_t max_length; // Maximum path length. int32_t npath; // Number of paths to generate. bool weighted; // Is the output tree weighted by path count, or // is it just an unweighted DAG? bool remove_total_weight; // Remove total weight when output is weighted? explicit RandGenOptions(const Selector &selector, int32_t max_length = std::numeric_limits<int32_t>::max(), int32_t npath = 1, bool weighted = false, bool remove_total_weight = false) : selector(selector), max_length(max_length), npath(npath), weighted(weighted), remove_total_weight(remove_total_weight) {} }; namespace internal { template <class FromArc, class ToArc> class RandGenVisitor { public: using StateId = typename FromArc::StateId; using Weight = typename FromArc::Weight; explicit RandGenVisitor(MutableFst<ToArc> *ofst) : ofst_(ofst) {} void InitVisit(const Fst<FromArc> &ifst) { ifst_ = &ifst; ofst_->DeleteStates(); ofst_->SetInputSymbols(ifst.InputSymbols()); ofst_->SetOutputSymbols(ifst.OutputSymbols()); if (ifst.Properties(kError, false)) ofst_->SetProperties(kError, kError); path_.clear(); } constexpr bool InitState(StateId, StateId) const { return true; } bool TreeArc(StateId, const ToArc &arc) { if (ifst_->Final(arc.nextstate) == Weight::Zero()) { path_.push_back(arc); } else { OutputPath(); } return true; } bool BackArc(StateId, const FromArc &) { FSTERROR() << "RandGenVisitor: cyclic input"; ofst_->SetProperties(kError, kError); return false; } bool ForwardOrCrossArc(StateId, const FromArc &) { OutputPath(); return true; } void FinishState(StateId s, StateId p, const FromArc *) { if (p != kNoStateId && ifst_->Final(s) == Weight::Zero()) path_.pop_back(); } void FinishVisit() {} private: void OutputPath() { if (ofst_->Start() == kNoStateId) { const auto start = ofst_->AddState(); ofst_->SetStart(start); } auto src = ofst_->Start(); for (size_t i = 0; i < path_.size(); ++i) { const auto dest = ofst_->AddState(); const ToArc arc(path_[i].ilabel, path_[i].olabel, Weight::One(), dest); ofst_->AddArc(src, arc); src = dest; } ofst_->SetFinal(src, Weight::One()); } const Fst<FromArc> *ifst_; MutableFst<ToArc> *ofst_; std::vector<ToArc> path_; RandGenVisitor(const RandGenVisitor &) = delete; RandGenVisitor &operator=(const RandGenVisitor &) = delete; }; } // namespace internal // Randomly generate paths through an FST; details controlled by // RandGenOptions. template <class FromArc, class ToArc, class Selector> void RandGen(const Fst<FromArc> &ifst, MutableFst<ToArc> *ofst, const RandGenOptions<Selector> &opts) { using State = typename ToArc::StateId; using Weight = typename ToArc::Weight; using Sampler = ArcSampler<FromArc, Selector>; auto *sampler = new Sampler(ifst, opts.selector, opts.max_length); RandGenFstOptions<Sampler> fopts(CacheOptions(true, 0), sampler, opts.npath, opts.weighted, opts.remove_total_weight); RandGenFst<FromArc, ToArc, Sampler> rfst(ifst, fopts); if (opts.weighted) { *ofst = rfst; } else { internal::RandGenVisitor<FromArc, ToArc> rand_visitor(ofst); DfsVisit(rfst, &rand_visitor); } } // Randomly generate a path through an FST with the uniform distribution // over the transitions. template <class FromArc, class ToArc> void RandGen(const Fst<FromArc> &ifst, MutableFst<ToArc> *ofst) { const UniformArcSelector<FromArc> uniform_selector; RandGenOptions<UniformArcSelector<ToArc>> opts(uniform_selector); RandGen(ifst, ofst, opts); } } // namespace fst #endif // FST_RANDGEN_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/mutable-fst.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Expanded FST augmented with mutators; interface class definition and // mutable arc iterator interface. #ifndef FST_MUTABLE_FST_H_ #define FST_MUTABLE_FST_H_ #include <stddef.h> #include <sys/types.h> #include <istream> #include <string> #include <utility> #include <vector> #include <fst/log.h> #include <fstream> #include <fst/expanded-fst.h> namespace fst { template <class Arc> struct MutableArcIteratorData; // Abstract interface for an expanded FST which also supports mutation // operations. To modify arcs, use MutableArcIterator. template <class A> class MutableFst : public ExpandedFst<A> { public: using Arc = A; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; virtual MutableFst<Arc> &operator=(const Fst<Arc> &fst) = 0; MutableFst<Arc> &operator=(const MutableFst<Arc> &fst) { return operator=(static_cast<const Fst<Arc> &>(fst)); } // Sets the initial state. virtual void SetStart(StateId) = 0; // Sets a state's final weight. virtual void SetFinal(StateId, Weight) = 0; // Sets property bits w.r.t. mask. virtual void SetProperties(uint64_t props, uint64_t mask) = 0; // Adds a state and returns its ID. virtual StateId AddState() = 0; // Adds an arc to state. virtual void AddArc(StateId, const Arc &arc) = 0; // Deletes some states, preserving original StateId ordering. virtual void DeleteStates(const std::vector<StateId> &) = 0; // Delete all states. virtual void DeleteStates() = 0; // Delete some arcs at a given state. virtual void DeleteArcs(StateId, size_t n) = 0; // Delete all arcs at a given state. virtual void DeleteArcs(StateId) = 0; // Optional, best effort only. virtual void ReserveStates(StateId n) {} // Optional, best effort only. virtual void ReserveArcs(StateId s, size_t n) {} // Returns input label symbol table or nullptr if not specified. const SymbolTable *InputSymbols() const override = 0; // Returns output label symbol table or nullptr if not specified. const SymbolTable *OutputSymbols() const override = 0; // Returns input label symbol table or nullptr if not specified. virtual SymbolTable *MutableInputSymbols() = 0; // Returns output label symbol table or nullptr if not specified. virtual SymbolTable *MutableOutputSymbols() = 0; // Sets input label symbol table; pass nullptr to delete table. virtual void SetInputSymbols(const SymbolTable *isyms) = 0; // Sets output label symbol table; pass nullptr to delete table. virtual void SetOutputSymbols(const SymbolTable *osyms) = 0; // Gets a copy of this MutableFst. See Fst<>::Copy() for further doc. MutableFst<A> *Copy(bool safe = false) const override = 0; // Reads a MutableFst from an input stream, returning nullptr on error. static MutableFst<Arc> *Read(std::istream &strm, const FstReadOptions &opts) { FstReadOptions ropts(opts); FstHeader hdr; if (ropts.header) { hdr = *opts.header; } else { if (!hdr.Read(strm, opts.source)) return nullptr; ropts.header = &hdr; } if (!(hdr.Properties() & kMutable)) { LOG(ERROR) << "MutableFst::Read: Not a MutableFst: " << ropts.source; return nullptr; } const auto &fst_type = hdr.FstType(); const auto reader = FstRegister<Arc>::GetRegister()->GetReader(fst_type); if (!reader) { LOG(ERROR) << "MutableFst::Read: Unknown FST type \"" << fst_type << "\" (arc type = \"" << A::Type() << "\"): " << ropts.source; return nullptr; } auto *fst = reader(strm, ropts); if (!fst) return nullptr; return static_cast<MutableFst<Arc> *>(fst); } // Reads a MutableFst from a file; returns nullptr on error. An empty // filename results in reading from standard input. If convert is true, // convert to a mutable FST subclass (given by convert_type) in the case // that the input FST is non-mutable. static MutableFst<Arc> *Read(const string &filename, bool convert = false, const string &convert_type = "vector") { if (convert == false) { if (!filename.empty()) { std::ifstream strm(filename, std::ios_base::in | std::ios_base::binary); if (!strm) { LOG(ERROR) << "MutableFst::Read: Can't open file: " << filename; return nullptr; } return Read(strm, FstReadOptions(filename)); } else { return Read(std::cin, FstReadOptions("standard input")); } } else { // Converts to 'convert_type' if not mutable. std::unique_ptr<Fst<Arc>> ifst(Fst<Arc>::Read(filename)); if (!ifst) return nullptr; if (ifst->Properties(kMutable, false)) { return static_cast<MutableFst<Arc> *>(ifst.release()); } else { std::unique_ptr<Fst<Arc>> ofst(Convert(*ifst, convert_type)); ifst.reset(); if (!ofst) return nullptr; if (!ofst->Properties(kMutable, false)) { LOG(ERROR) << "MutableFst: Bad convert type: " << convert_type; } return static_cast<MutableFst<Arc> *>(ofst.release()); } } } // For generic mutuble arc iterator construction; not normally called // directly by users. virtual void InitMutableArcIterator(StateId s, MutableArcIteratorData<Arc> *data) = 0; }; // Mutable arc iterator interface, templated on the Arc definition. This is // used by mutable arc iterator specializations that are returned by the // InitMutableArcIterator MutableFst method. template <class Arc> class MutableArcIteratorBase : public ArcIteratorBase<Arc> { public: // Sets current arc. virtual void SetValue(const Arc &) = 0; }; template <class Arc> struct MutableArcIteratorData { MutableArcIteratorBase<Arc> *base; // Specific iterator. }; // Generic mutable arc iterator, templated on the FST definition; a wrapper // around a pointer to a more specific one. // // Here is a typical use: // // for (MutableArcIterator<StdFst> aiter(&fst, s); // !aiter.Done(); // aiter.Next()) { // StdArc arc = aiter.Value(); // arc.ilabel = 7; // aiter.SetValue(arc); // ... // } // // This version requires function calls. template <class FST> class MutableArcIterator { public: using Arc = typename FST::Arc; using StateId = typename Arc::StateId; MutableArcIterator(FST *fst, StateId s) { fst->InitMutableArcIterator(s, &data_); } ~MutableArcIterator() { delete data_.base; } bool Done() const { return data_.base->Done(); } const Arc &Value() const { return data_.base->Value(); } void Next() { data_.base->Next(); } size_t Position() const { return data_.base->Position(); } void Reset() { data_.base->Reset(); } void Seek(size_t a) { data_.base->Seek(a); } void SetValue(const Arc &arc) { data_.base->SetValue(arc); } uint32_t Flags() const { return data_.base->Flags(); } void SetFlags(uint32_t flags, uint32_t mask) { return data_.base->SetFlags(flags, mask); } private: MutableArcIteratorData<Arc> data_; MutableArcIterator(const MutableArcIterator &) = delete; MutableArcIterator &operator=(const MutableArcIterator &) = delete; }; namespace internal { // MutableFst<A> case: abstract methods. template <class Arc> inline typename Arc::Weight Final(const MutableFst<Arc> &fst, typename Arc::StateId s) { return fst.Final(s); } template <class Arc> inline std::ptrdiff_t NumArcs(const MutableFst<Arc> &fst, typename Arc::StateId s) { return fst.NumArcs(s); } template <class Arc> inline std::ptrdiff_t NumInputEpsilons(const MutableFst<Arc> &fst, typename Arc::StateId s) { return fst.NumInputEpsilons(s); } template <class Arc> inline std::ptrdiff_t NumOutputEpsilons(const MutableFst<Arc> &fst, typename Arc::StateId s) { return fst.NumOutputEpsilons(s); } } // namespace internal // A useful alias when using StdArc. using StdMutableFst = MutableFst<StdArc>; // This is a helper class template useful for attaching a MutableFst interface // to its implementation, handling reference counting and COW semantics. template <class Impl, class FST = MutableFst<typename Impl::Arc>> class ImplToMutableFst : public ImplToExpandedFst<Impl, FST> { public: using Arc = typename Impl::Arc; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using ImplToExpandedFst<Impl, FST>::operator=; void SetStart(StateId s) override { MutateCheck(); GetMutableImpl()->SetStart(s); } void SetFinal(StateId s, Weight weight) override { MutateCheck(); GetMutableImpl()->SetFinal(s, std::move(weight)); } void SetProperties(uint64_t props, uint64_t mask) override { // Can skip mutate check if extrinsic properties don't change, // since it is then safe to update all (shallow) copies const auto exprops = kExtrinsicProperties & mask; if (GetImpl()->Properties(exprops) != (props & exprops)) MutateCheck(); GetMutableImpl()->SetProperties(props, mask); } StateId AddState() override { MutateCheck(); return GetMutableImpl()->AddState(); } void AddArc(StateId s, const Arc &arc) override { MutateCheck(); GetMutableImpl()->AddArc(s, arc); } void DeleteStates(const std::vector<StateId> &dstates) override { MutateCheck(); GetMutableImpl()->DeleteStates(dstates); } void DeleteStates() override { if (!Unique()) { const auto *isymbols = GetImpl()->InputSymbols(); const auto *osymbols = GetImpl()->OutputSymbols(); SetImpl(std::make_shared<Impl>()); GetMutableImpl()->SetInputSymbols(isymbols); GetMutableImpl()->SetOutputSymbols(osymbols); } else { GetMutableImpl()->DeleteStates(); } } void DeleteArcs(StateId s, size_t n) override { MutateCheck(); GetMutableImpl()->DeleteArcs(s, n); } void DeleteArcs(StateId s) override { MutateCheck(); GetMutableImpl()->DeleteArcs(s); } void ReserveStates(StateId s) override { MutateCheck(); GetMutableImpl()->ReserveStates(s); } void ReserveArcs(StateId s, size_t n) override { MutateCheck(); GetMutableImpl()->ReserveArcs(s, n); } const SymbolTable *InputSymbols() const override { return GetImpl()->InputSymbols(); } const SymbolTable *OutputSymbols() const override { return GetImpl()->OutputSymbols(); } SymbolTable *MutableInputSymbols() override { MutateCheck(); return GetMutableImpl()->InputSymbols(); } SymbolTable *MutableOutputSymbols() override { MutateCheck(); return GetMutableImpl()->OutputSymbols(); } void SetInputSymbols(const SymbolTable *isyms) override { MutateCheck(); GetMutableImpl()->SetInputSymbols(isyms); } void SetOutputSymbols(const SymbolTable *osyms) override { MutateCheck(); GetMutableImpl()->SetOutputSymbols(osyms); } protected: using ImplToExpandedFst<Impl, FST>::GetImpl; using ImplToExpandedFst<Impl, FST>::GetMutableImpl; using ImplToExpandedFst<Impl, FST>::Unique; using ImplToExpandedFst<Impl, FST>::SetImpl; using ImplToExpandedFst<Impl, FST>::InputSymbols; explicit ImplToMutableFst(std::shared_ptr<Impl> impl) : ImplToExpandedFst<Impl, FST>(impl) {} ImplToMutableFst(const ImplToMutableFst<Impl, FST> &fst, bool safe) : ImplToExpandedFst<Impl, FST>(fst, safe) {} void MutateCheck() { if (!Unique()) SetImpl(std::make_shared<Impl>(*this)); } }; } // namespace fst #endif // FST_MUTABLE_FST_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/script/compose.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_COMPOSE_H_ #define FST_SCRIPT_COMPOSE_H_ #include <tuple> #include <fst/compose.h> #include <fst/script/fst-class.h> namespace fst { namespace script { using ComposeArgs = std::tuple<const FstClass &, const FstClass &, MutableFstClass *, const ComposeOptions &>; template <class Arc> void Compose(ComposeArgs *args) { const Fst<Arc> &ifst1 = *(std::get<0>(*args).GetFst<Arc>()); const Fst<Arc> &ifst2 = *(std::get<1>(*args).GetFst<Arc>()); MutableFst<Arc> *ofst = std::get<2>(*args)->GetMutableFst<Arc>(); const auto &opts = std::get<3>(*args); Compose(ifst1, ifst2, ofst, opts); } void Compose(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, const ComposeOptions &opts = ComposeOptions()); } // namespace script } // namespace fst #endif // FST_SCRIPT_COMPOSE_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/arcfilter.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Function objects to restrict which arcs are traversed in an FST. #ifndef FST_ARCFILTER_H_ #define FST_ARCFILTER_H_ #include <fst/fst.h> #include <fst/util.h> namespace fst { // True for all arcs. template <class Arc> class AnyArcFilter { public: bool operator()(const Arc &arc) const { return true; } }; // True for (input/output) epsilon arcs. template <class Arc> class EpsilonArcFilter { public: bool operator()(const Arc &arc) const { return arc.ilabel == 0 && arc.olabel == 0; } }; // True for input epsilon arcs. template <class Arc> class InputEpsilonArcFilter { public: bool operator()(const Arc &arc) const { return arc.ilabel == 0; } }; // True for output epsilon arcs. template <class Arc> class OutputEpsilonArcFilter { public: bool operator()(const Arc &arc) const { return arc.olabel == 0; } }; // True if specified label matches (doesn't match) when keep_match is // true (false). template <class Arc> class LabelArcFilter { public: using Label = typename Arc::Label; explicit LabelArcFilter(Label label, bool match_input = true, bool keep_match = true) : label_(label), match_input_(match_input), keep_match_(keep_match) {} bool operator()(const Arc &arc) const { const bool match = (match_input_ ? arc.ilabel : arc.olabel) == label_; return keep_match_ ? match : !match; } private: const Label label_; const bool match_input_; const bool keep_match_; }; // True if specified labels match (don't match) when keep_match is true (false). template <class Arc> class MultiLabelArcFilter { public: using Label = typename Arc::Label; explicit MultiLabelArcFilter(bool match_input = true, bool keep_match = true) : match_input_(match_input), keep_match_(keep_match) {} bool operator()(const Arc &arc) const { const Label label = match_input_ ? arc.ilabel : arc.olabel; const bool match = labels_.Find(label) != labels_.End(); return keep_match_ ? match : !match; } void AddLabel(Label label) { labels_.Insert(label); } private: CompactSet<Label, kNoLabel> labels_; const bool match_input_; const bool keep_match_; }; } // namespace fst #endif // FST_ARCFILTER_H_
0
coqui_public_repos/TTS/TTS/vc
coqui_public_repos/TTS/TTS/vc/models/__init__.py
import importlib import re from typing import Dict, List, Union def to_camel(text): text = text.capitalize() return re.sub(r"(?!^)_([a-zA-Z])", lambda m: m.group(1).upper(), text) def setup_model(config: "Coqpit", samples: Union[List[List], List[Dict]] = None) -> "BaseVC": print(" > Using model: {}".format(config.model)) # fetch the right model implementation. if "model" in config and config["model"].lower() == "freevc": MyModel = importlib.import_module("TTS.vc.models.freevc").FreeVC model = MyModel.init_from_config(config, samples) return model
0
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core/framework/op_node_proto_helper.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #ifndef SHARED_PROVIDER #include "core/common/status.h" #include "core/graph/graph_viewer.h" #include "gsl/gsl" #endif #ifdef __has_attribute #define ORT_HAVE_ATTRIBUTE(x) __has_attribute(x) #else #define ORT_HAVE_ATTRIBUTE(x) 0 #endif #if ORT_HAVE_ATTRIBUTE(nodiscard) #define MUST_USE_RESULT [[nodiscard]] #elif defined(__clang__) && ORT_HAVE_ATTRIBUTE(warn_unused_result) #define MUST_USE_RESULT __attribute__((warn_unused_result)) #else #define MUST_USE_RESULT #endif class IMLOpKernel; namespace onnxruntime { /** A set of wrappers with common signatures for use with both OpKernelInfo (as its base class) and InferenceContext. Used by ABI kernels for both shape / type inference and kernel construction */ template <class Impl_t> class OpNodeProtoHelper { public: explicit OpNodeProtoHelper(const Impl_t* impl) : impl_(impl) {} /** Get a single attribute Call this function for a required attribute or when a default value for an optional attribute is specified in the op schema */ template <typename T> MUST_USE_RESULT Status GetAttr(const std::string& name, T* value) const; /** Get a single attribute Call this function only when a default value for an optional attribute isn't specified in the op schema */ template <typename T> T GetAttrOrDefault(const std::string& name, const T& default_value) const { T tmp; return GetAttr<T>(name, &tmp).IsOK() ? tmp : default_value; } /** Get a single attribute Call this function only when a default value for an optional attribute isn't specified in the op schema */ template <typename T> void GetAttrOrDefault(const std::string& name, T* value, const T& default_value) const { if (!GetAttr<T>(name, value).IsOK()) *value = default_value; } /** Get repeated attributes Call this function only when a default value for an optional attribute isn't specified in the op schema */ template <typename T> MUST_USE_RESULT std::vector<T> GetAttrsOrDefault(const std::string& name, const std::vector<T>& default_value = std::vector<T>{}) const { std::vector<T> tmp; return GetAttrs<T>(name, tmp).IsOK() ? tmp : default_value; } /** Get repeated attributes */ template <typename T> MUST_USE_RESULT Status GetAttrs(const std::string& name, std::vector<T>& values) const; template <typename T> MUST_USE_RESULT Status GetAttrs(const std::string& name, gsl::span<T> values) const; /// <summary> /// Return a gsl::span that points to an array of primitive types held by AttributeProto /// This function allows to avoid copying big attributes locally into a kernel and operate on /// AttributeProto data directly. /// /// Does not apply to strings, Tensors and Sparse Tensors that require special treatment. /// </summary> /// <typeparam name="T">Primitive type contained in the array</typeparam> /// <param name="name">Attribute name</param> /// <param name="values">Attribute data in a span, out parameter</param> /// <returns>Status</returns> template <typename T> MUST_USE_RESULT Status GetAttrsAsSpan(const std::string& name, gsl::span<const T>& values) const; MUST_USE_RESULT Status GetAttrsStringRefs(const std::string& name, std::vector<std::reference_wrapper<const std::string>>& refs) const; uint32_t GetPrimitiveAttrElementCount(ONNX_NAMESPACE::AttributeProto_AttributeType type, const std::string& name) const noexcept; bool HasPrimitiveAttribute(ONNX_NAMESPACE::AttributeProto_AttributeType type, const std::string& name) const noexcept; uint32_t GetInputCount() const { return gsl::narrow_cast<uint32_t>(impl_->getNumInputs()); } uint32_t GetOutputCount() const { return gsl::narrow_cast<uint32_t>(impl_->getNumOutputs()); } const ONNX_NAMESPACE::TypeProto* GetInputType(size_t index) const { return impl_->getInputType(index); } const ONNX_NAMESPACE::TypeProto* GetOutputType(size_t index) const { // Work around lack of a const method from the onnx InferenceContext interface return const_cast<Impl_t*>(impl_)->getOutputType(index); } // Try to query an attribute, returning nullptr if it doesn't exist const ONNX_NAMESPACE::AttributeProto* TryGetAttribute(const std::string& name) const { return impl_->getAttribute(name); } const ONNX_NAMESPACE::AttributeProto* GetAttribute(const std::string& name) const { const ONNX_NAMESPACE::AttributeProto* attr = TryGetAttribute(name); ORT_ENFORCE(attr != nullptr); return attr; } private: OpNodeProtoHelper() = delete; const Impl_t* impl_ = nullptr; }; // The methods on the following class are called by OpNodeProtoHelper, implementing // the same signatures as InferenceContext other than const-ness. class ProtoHelperNodeContext { public: explicit ProtoHelperNodeContext(const onnxruntime::Node& node) : node_(node) {} ProtoHelperNodeContext() = delete; const ONNX_NAMESPACE::AttributeProto* getAttribute(const std::string& name) const; size_t getNumInputs() const; const ONNX_NAMESPACE::TypeProto* getInputType(size_t index) const; size_t getNumOutputs() const; const ONNX_NAMESPACE::TypeProto* getOutputType(size_t index) const; private: const onnxruntime::Node& node_; }; } // namespace onnxruntime
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions/compact/compact64_unweighted_acceptor-fst.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/fst.h> #include <fst/compact-fst.h> namespace fst { static FstRegisterer< CompactUnweightedAcceptorFst<StdArc, uint64>> CompactUnweightedAcceptorFst_StdArc_uint64_registerer; static FstRegisterer< CompactUnweightedAcceptorFst<LogArc, uint64>> CompactUnweightedAcceptorFst_LogArc_uint64_registerer; } // namespace fst
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/bin/fstrelabel-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Relabels input or output space of an FST. #include <cstring> #include <memory> #include <string> #include <vector> #include <fst/flags.h> #include <fst/util.h> #include <fst/script/relabel.h> #include <fst/script/weight-class.h> DECLARE_string(isymbols); DECLARE_string(osymbols); DECLARE_string(relabel_isymbols); DECLARE_string(relabel_osymbols); DECLARE_string(relabel_ipairs); DECLARE_string(relabel_opairs); DECLARE_string(unknown_isymbol); DECLARE_string(unknown_osymbol); DECLARE_bool(allow_negative_labels); int fstrelabel_main(int argc, char **argv) { namespace s = fst::script; using fst::script::MutableFstClass; using fst::SymbolTable; using fst::SymbolTableTextOptions; string usage = "Relabels the input and/or the output labels of the FST.\n\n" " Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; usage += "\n Using SymbolTables flags:\n"; usage += " --relabel_isymbols isyms.map\n"; usage += " --relabel_osymbols osyms.map\n"; usage += "\n Using numeric labels flags:\n"; usage += " --relabel_ipairs ipairs.txt\n"; usage += " --relabel_opairs opairs.txt\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } const string in_name = (argc > 1 && (strcmp(argv[1], "-") != 0)) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<MutableFstClass> fst(MutableFstClass::Read(in_name, true)); if (!fst) return 1; // Relabel with symbol tables. const SymbolTableTextOptions opts(FLAGS_allow_negative_labels); if (!FLAGS_relabel_isymbols.empty() || !FLAGS_relabel_osymbols.empty()) { bool attach_new_isymbols = (fst->InputSymbols() != nullptr); std::unique_ptr<const SymbolTable> old_isymbols( FLAGS_isymbols.empty() ? nullptr : SymbolTable::ReadText(FLAGS_isymbols, opts)); const std::unique_ptr<const SymbolTable> relabel_isymbols( FLAGS_relabel_isymbols.empty() ? nullptr : SymbolTable::ReadText(FLAGS_relabel_isymbols, opts)); bool attach_new_osymbols = (fst->OutputSymbols() != nullptr); std::unique_ptr<const SymbolTable> old_osymbols( FLAGS_osymbols.empty() ? nullptr : SymbolTable::ReadText(FLAGS_osymbols, opts)); const std::unique_ptr<const SymbolTable> relabel_osymbols( FLAGS_relabel_osymbols.empty() ? nullptr : SymbolTable::ReadText(FLAGS_relabel_osymbols, opts)); s::Relabel(fst.get(), old_isymbols ? old_isymbols.get() : fst->InputSymbols(), relabel_isymbols.get(), FLAGS_unknown_isymbol, attach_new_isymbols, old_osymbols ? old_osymbols.get() : fst->OutputSymbols(), relabel_osymbols.get(), FLAGS_unknown_osymbol, attach_new_osymbols); } else { // Reads in relabeling pairs. std::vector<s::LabelPair> ipairs; std::vector<s::LabelPair> opairs; if (!FLAGS_relabel_ipairs.empty()) { if (!fst::ReadLabelPairs(FLAGS_relabel_ipairs, &ipairs, FLAGS_allow_negative_labels)) return 1; } if (!FLAGS_relabel_opairs.empty()) { if (!fst::ReadLabelPairs(FLAGS_relabel_opairs, &opairs, FLAGS_allow_negative_labels)) return 1; } s::Relabel(fst.get(), ipairs, opairs); } return !fst->Write(out_name); }
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/bin/fstconcat-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Concatenates two FSTs. #include <cstring> #include <memory> #include <string> #include <fst/flags.h> #include <fst/log.h> #include <fst/script/concat.h> int fstconcat_main(int argc, char **argv) { namespace s = fst::script; using fst::script::FstClass; using fst::script::MutableFstClass; string usage = "Concatenates two FSTs.\n\n Usage: "; usage += argv[0]; usage += " in1.fst in2.fst [out.fst]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc < 3 || argc > 4) { ShowUsage(); return 1; } const string in1_name = strcmp(argv[1], "-") == 0 ? "" : argv[1]; const string in2_name = strcmp(argv[2], "-") == 0 ? "" : argv[2]; const string out_name = argc > 3 ? argv[3] : ""; if (in1_name.empty() && in2_name.empty()) { LOG(ERROR) << argv[0] << ": Can't take both inputs from standard input"; return 1; } std::unique_ptr<MutableFstClass> fst1(MutableFstClass::Read(in1_name, true)); if (!fst1) return 1; std::unique_ptr<FstClass> fst2(FstClass::Read(in2_name)); if (!fst2) return 1; s::Concat(fst1.get(), *fst2); return !fst1->Write(out_name); }
0
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external/rapidjson/ostreamwrapper.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_ #define CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_ #include "stream.h" #include <iosfwd> #ifdef __clang__ CEREAL_RAPIDJSON_DIAG_PUSH CEREAL_RAPIDJSON_DIAG_OFF(padded) #endif CEREAL_RAPIDJSON_NAMESPACE_BEGIN //! Wrapper of \c std::basic_ostream into RapidJSON's Stream concept. /*! The classes can be wrapped including but not limited to: - \c std::ostringstream - \c std::stringstream - \c std::wpstringstream - \c std::wstringstream - \c std::ifstream - \c std::fstream - \c std::wofstream - \c std::wfstream \tparam StreamType Class derived from \c std::basic_ostream. */ template <typename StreamType> class BasicOStreamWrapper { public: typedef typename StreamType::char_type Ch; BasicOStreamWrapper(StreamType& stream) : stream_(stream) {} void Put(Ch c) { stream_.put(c); } void Flush() { stream_.flush(); } // Not implemented char Peek() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } char Take() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } size_t Tell() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } char* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } size_t PutEnd(char*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } private: BasicOStreamWrapper(const BasicOStreamWrapper&); BasicOStreamWrapper& operator=(const BasicOStreamWrapper&); StreamType& stream_; }; typedef BasicOStreamWrapper<std::ostream> OStreamWrapper; typedef BasicOStreamWrapper<std::wostream> WOStreamWrapper; #ifdef __clang__ CEREAL_RAPIDJSON_DIAG_POP #endif CEREAL_RAPIDJSON_NAMESPACE_END #endif // CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/script/compose.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_COMPOSE_H_ #define FST_SCRIPT_COMPOSE_H_ #include <tuple> #include <fst/compose.h> #include <fst/script/fst-class.h> namespace fst { namespace script { using ComposeArgs = std::tuple<const FstClass &, const FstClass &, MutableFstClass *, const ComposeOptions &>; template <class Arc> void Compose(ComposeArgs *args) { const Fst<Arc> &ifst1 = *(std::get<0>(*args).GetFst<Arc>()); const Fst<Arc> &ifst2 = *(std::get<1>(*args).GetFst<Arc>()); MutableFst<Arc> *ofst = std::get<2>(*args)->GetMutableFst<Arc>(); const auto &opts = std::get<3>(*args); Compose(ifst1, ifst2, ofst, opts); } void Compose(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, const ComposeOptions &opts = ComposeOptions()); } // namespace script } // namespace fst #endif // FST_SCRIPT_COMPOSE_H_
0
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external/rapidjson
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external/rapidjson/internal/itoa.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef CEREAL_RAPIDJSON_ITOA_ #define CEREAL_RAPIDJSON_ITOA_ #include "../rapidjson.h" CEREAL_RAPIDJSON_NAMESPACE_BEGIN namespace internal { inline const char* GetDigitsLut() { static const char cDigitsLut[200] = { '0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9', '1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9', '2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9', '3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9', '4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9', '5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9', '6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9', '7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9', '8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9', '9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9' }; return cDigitsLut; } inline char* u32toa(uint32_t value, char* buffer) { CEREAL_RAPIDJSON_ASSERT(buffer != 0); const char* cDigitsLut = GetDigitsLut(); if (value < 10000) { const uint32_t d1 = (value / 100) << 1; const uint32_t d2 = (value % 100) << 1; if (value >= 1000) *buffer++ = cDigitsLut[d1]; if (value >= 100) *buffer++ = cDigitsLut[d1 + 1]; if (value >= 10) *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; } else if (value < 100000000) { // value = bbbbcccc const uint32_t b = value / 10000; const uint32_t c = value % 10000; const uint32_t d1 = (b / 100) << 1; const uint32_t d2 = (b % 100) << 1; const uint32_t d3 = (c / 100) << 1; const uint32_t d4 = (c % 100) << 1; if (value >= 10000000) *buffer++ = cDigitsLut[d1]; if (value >= 1000000) *buffer++ = cDigitsLut[d1 + 1]; if (value >= 100000) *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; *buffer++ = cDigitsLut[d3]; *buffer++ = cDigitsLut[d3 + 1]; *buffer++ = cDigitsLut[d4]; *buffer++ = cDigitsLut[d4 + 1]; } else { // value = aabbbbcccc in decimal const uint32_t a = value / 100000000; // 1 to 42 value %= 100000000; if (a >= 10) { const unsigned i = a << 1; *buffer++ = cDigitsLut[i]; *buffer++ = cDigitsLut[i + 1]; } else *buffer++ = static_cast<char>('0' + static_cast<char>(a)); const uint32_t b = value / 10000; // 0 to 9999 const uint32_t c = value % 10000; // 0 to 9999 const uint32_t d1 = (b / 100) << 1; const uint32_t d2 = (b % 100) << 1; const uint32_t d3 = (c / 100) << 1; const uint32_t d4 = (c % 100) << 1; *buffer++ = cDigitsLut[d1]; *buffer++ = cDigitsLut[d1 + 1]; *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; *buffer++ = cDigitsLut[d3]; *buffer++ = cDigitsLut[d3 + 1]; *buffer++ = cDigitsLut[d4]; *buffer++ = cDigitsLut[d4 + 1]; } return buffer; } inline char* i32toa(int32_t value, char* buffer) { CEREAL_RAPIDJSON_ASSERT(buffer != 0); uint32_t u = static_cast<uint32_t>(value); if (value < 0) { *buffer++ = '-'; u = ~u + 1; } return u32toa(u, buffer); } inline char* u64toa(uint64_t value, char* buffer) { CEREAL_RAPIDJSON_ASSERT(buffer != 0); const char* cDigitsLut = GetDigitsLut(); const uint64_t kTen8 = 100000000; const uint64_t kTen9 = kTen8 * 10; const uint64_t kTen10 = kTen8 * 100; const uint64_t kTen11 = kTen8 * 1000; const uint64_t kTen12 = kTen8 * 10000; const uint64_t kTen13 = kTen8 * 100000; const uint64_t kTen14 = kTen8 * 1000000; const uint64_t kTen15 = kTen8 * 10000000; const uint64_t kTen16 = kTen8 * kTen8; if (value < kTen8) { uint32_t v = static_cast<uint32_t>(value); if (v < 10000) { const uint32_t d1 = (v / 100) << 1; const uint32_t d2 = (v % 100) << 1; if (v >= 1000) *buffer++ = cDigitsLut[d1]; if (v >= 100) *buffer++ = cDigitsLut[d1 + 1]; if (v >= 10) *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; } else { // value = bbbbcccc const uint32_t b = v / 10000; const uint32_t c = v % 10000; const uint32_t d1 = (b / 100) << 1; const uint32_t d2 = (b % 100) << 1; const uint32_t d3 = (c / 100) << 1; const uint32_t d4 = (c % 100) << 1; if (value >= 10000000) *buffer++ = cDigitsLut[d1]; if (value >= 1000000) *buffer++ = cDigitsLut[d1 + 1]; if (value >= 100000) *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; *buffer++ = cDigitsLut[d3]; *buffer++ = cDigitsLut[d3 + 1]; *buffer++ = cDigitsLut[d4]; *buffer++ = cDigitsLut[d4 + 1]; } } else if (value < kTen16) { const uint32_t v0 = static_cast<uint32_t>(value / kTen8); const uint32_t v1 = static_cast<uint32_t>(value % kTen8); const uint32_t b0 = v0 / 10000; const uint32_t c0 = v0 % 10000; const uint32_t d1 = (b0 / 100) << 1; const uint32_t d2 = (b0 % 100) << 1; const uint32_t d3 = (c0 / 100) << 1; const uint32_t d4 = (c0 % 100) << 1; const uint32_t b1 = v1 / 10000; const uint32_t c1 = v1 % 10000; const uint32_t d5 = (b1 / 100) << 1; const uint32_t d6 = (b1 % 100) << 1; const uint32_t d7 = (c1 / 100) << 1; const uint32_t d8 = (c1 % 100) << 1; if (value >= kTen15) *buffer++ = cDigitsLut[d1]; if (value >= kTen14) *buffer++ = cDigitsLut[d1 + 1]; if (value >= kTen13) *buffer++ = cDigitsLut[d2]; if (value >= kTen12) *buffer++ = cDigitsLut[d2 + 1]; if (value >= kTen11) *buffer++ = cDigitsLut[d3]; if (value >= kTen10) *buffer++ = cDigitsLut[d3 + 1]; if (value >= kTen9) *buffer++ = cDigitsLut[d4]; *buffer++ = cDigitsLut[d4 + 1]; *buffer++ = cDigitsLut[d5]; *buffer++ = cDigitsLut[d5 + 1]; *buffer++ = cDigitsLut[d6]; *buffer++ = cDigitsLut[d6 + 1]; *buffer++ = cDigitsLut[d7]; *buffer++ = cDigitsLut[d7 + 1]; *buffer++ = cDigitsLut[d8]; *buffer++ = cDigitsLut[d8 + 1]; } else { const uint32_t a = static_cast<uint32_t>(value / kTen16); // 1 to 1844 value %= kTen16; if (a < 10) *buffer++ = static_cast<char>('0' + static_cast<char>(a)); else if (a < 100) { const uint32_t i = a << 1; *buffer++ = cDigitsLut[i]; *buffer++ = cDigitsLut[i + 1]; } else if (a < 1000) { *buffer++ = static_cast<char>('0' + static_cast<char>(a / 100)); const uint32_t i = (a % 100) << 1; *buffer++ = cDigitsLut[i]; *buffer++ = cDigitsLut[i + 1]; } else { const uint32_t i = (a / 100) << 1; const uint32_t j = (a % 100) << 1; *buffer++ = cDigitsLut[i]; *buffer++ = cDigitsLut[i + 1]; *buffer++ = cDigitsLut[j]; *buffer++ = cDigitsLut[j + 1]; } const uint32_t v0 = static_cast<uint32_t>(value / kTen8); const uint32_t v1 = static_cast<uint32_t>(value % kTen8); const uint32_t b0 = v0 / 10000; const uint32_t c0 = v0 % 10000; const uint32_t d1 = (b0 / 100) << 1; const uint32_t d2 = (b0 % 100) << 1; const uint32_t d3 = (c0 / 100) << 1; const uint32_t d4 = (c0 % 100) << 1; const uint32_t b1 = v1 / 10000; const uint32_t c1 = v1 % 10000; const uint32_t d5 = (b1 / 100) << 1; const uint32_t d6 = (b1 % 100) << 1; const uint32_t d7 = (c1 / 100) << 1; const uint32_t d8 = (c1 % 100) << 1; *buffer++ = cDigitsLut[d1]; *buffer++ = cDigitsLut[d1 + 1]; *buffer++ = cDigitsLut[d2]; *buffer++ = cDigitsLut[d2 + 1]; *buffer++ = cDigitsLut[d3]; *buffer++ = cDigitsLut[d3 + 1]; *buffer++ = cDigitsLut[d4]; *buffer++ = cDigitsLut[d4 + 1]; *buffer++ = cDigitsLut[d5]; *buffer++ = cDigitsLut[d5 + 1]; *buffer++ = cDigitsLut[d6]; *buffer++ = cDigitsLut[d6 + 1]; *buffer++ = cDigitsLut[d7]; *buffer++ = cDigitsLut[d7 + 1]; *buffer++ = cDigitsLut[d8]; *buffer++ = cDigitsLut[d8 + 1]; } return buffer; } inline char* i64toa(int64_t value, char* buffer) { CEREAL_RAPIDJSON_ASSERT(buffer != 0); uint64_t u = static_cast<uint64_t>(value); if (value < 0) { *buffer++ = '-'; u = ~u + 1; } return u64toa(u, buffer); } } // namespace internal CEREAL_RAPIDJSON_NAMESPACE_END #endif // CEREAL_RAPIDJSON_ITOA_
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/rpi3-build.sh
#!/bin/bash set -xe source $(dirname "$0")/tc-tests-utils.sh source $(dirname "$0")/tf_tc-vars.sh BAZEL_TARGETS=" //native_client:libstt.so //native_client:generate_scorer_package " BAZEL_BUILD_FLAGS="${BAZEL_ARM_FLAGS} ${BAZEL_EXTRA_FLAGS}" BAZEL_ENV_FLAGS="TF_NEED_CUDA=0" SYSTEM_TARGET=rpi3 SYSTEM_RASPBIAN=/tmp/multistrap-raspbian-buster maybe_install_xldd do_bazel_build do_deepspeech_binary_build export SUPPORTED_PYTHON_VERSIONS="3.7.6:ucs2" do_deepspeech_python_build do_deepspeech_nodejs_build
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/script/concat.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_CONCAT_H_ #define FST_SCRIPT_CONCAT_H_ #include <utility> #include <fst/concat.h> #include <fst/script/fst-class.h> namespace fst { namespace script { using ConcatArgs1 = std::pair<MutableFstClass *, const FstClass &>; template <class Arc> void Concat(ConcatArgs1 *args) { MutableFst<Arc> *ofst = std::get<0>(*args)->GetMutableFst<Arc>(); const Fst<Arc> &ifst = *(std::get<1>(*args).GetFst<Arc>()); Concat(ofst, ifst); } using ConcatArgs2 = std::pair<const FstClass &, MutableFstClass *>; template <class Arc> void Concat(ConcatArgs2 *args) { const Fst<Arc> &ifst = *(std::get<0>(*args).GetFst<Arc>()); MutableFst<Arc> *ofst = std::get<1>(*args)->GetMutableFst<Arc>(); Concat(ifst, ofst); } void Concat(MutableFstClass *ofst, const FstClass &ifst); void Concat(const FstClass &ifst, MutableFstClass *ofst); } // namespace script } // namespace fst #endif // FST_SCRIPT_CONCAT_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/lookahead-filter.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Composition filters to support lookahead matchers, useful for improving // composition efficiency with certain inputs. #ifndef FST_LOOKAHEAD_FILTER_H_ #define FST_LOOKAHEAD_FILTER_H_ #include <vector> #include <fst/log.h> #include <fst/filter-state.h> #include <fst/fst.h> #include <fst/lookahead-matcher.h> namespace fst { // Identifies and verifies the capabilities of the matcher to be used for // lookahead with the composition filters below. This version is passed two // matchers. template <class Matcher1, class Matcher2> MatchType LookAheadMatchType(const Matcher1 &m1, const Matcher2 &m2) { const auto type1 = m1.Type(false); const auto type2 = m2.Type(false); if (type1 == MATCH_OUTPUT && m1.Flags() & kOutputLookAheadMatcher) { return MATCH_OUTPUT; } else if (type2 == MATCH_INPUT && m2.Flags() & kInputLookAheadMatcher) { return MATCH_INPUT; } else if (m1.Flags() & kOutputLookAheadMatcher && m1.Type(true) == MATCH_OUTPUT) { return MATCH_OUTPUT; } else if (m2.Flags() & kInputLookAheadMatcher && m2.Type(true) == MATCH_INPUT) { return MATCH_INPUT; } else { return MATCH_NONE; } } // Identifies and verifies the capabilities of the matcher to be used for // lookahead with the composition filters below. This version uses the FST's // default matchers. template <class Arc> MatchType LookAheadMatchType(const Fst<Arc> &fst1, const Fst<Arc> &fst2) { LookAheadMatcher<Fst<Arc>> matcher1(fst1, MATCH_OUTPUT); LookAheadMatcher<Fst<Arc>> matcher2(fst2, MATCH_INPUT); return LookAheadMatchType(matcher1, matcher2); } // LookAheadSelector is a helper class for selecting among possibly distinct // FST and matcher types without using a common base class. This lets us avoid // virtual function calls. It stores and returns the appropriate FSTs and // matcher for lookahead. It is templated on the matcher types. General case // has no methods. template <class Matcher1, class Matcher2, MatchType MT> class LookAheadSelector {}; // Stores and returns the appropriate FST and matcher for lookahead. Specialized // for two matchers of same type with the (match) type argument determining // which is used for lookahead. template <class Matcher, MatchType MT> class LookAheadSelector<Matcher, Matcher, MT> { public: using FST = typename Matcher::FST; LookAheadSelector(Matcher *lmatcher1, Matcher *lmatcher2, MatchType type) : lmatcher1_(lmatcher1->Copy()), lmatcher2_(lmatcher2->Copy()), type_(type) {} LookAheadSelector(const LookAheadSelector<Matcher, Matcher, MT> &selector) : lmatcher1_(selector.lmatcher1_->Copy()), lmatcher2_(selector.lmatcher2_->Copy()), type_(selector.type_) {} const FST &GetFst() const { return type_ == MATCH_OUTPUT ? lmatcher2_->GetFst() : lmatcher1_->GetFst(); } Matcher *GetMatcher() const { return type_ == MATCH_OUTPUT ? lmatcher1_.get() : lmatcher2_.get(); } private: std::unique_ptr<Matcher> lmatcher1_; std::unique_ptr<Matcher> lmatcher2_; MatchType type_; }; // Stores and returns the appropriate FST and matcher for lookahead. // Specialized for lookahead on input labels. template <class Matcher1, class Matcher2> class LookAheadSelector<Matcher1, Matcher2, MATCH_INPUT> { public: using FST1 = typename Matcher1::FST; LookAheadSelector(Matcher1 *lmatcher1, Matcher2 *lmatcher2, MatchType) : fst_(lmatcher1->GetFst().Copy()), lmatcher_(lmatcher2->Copy()) {} LookAheadSelector( const LookAheadSelector<Matcher1, Matcher2, MATCH_INPUT> &selector) : fst_(selector.fst_->Copy()), lmatcher_(selector.lmatcher_->Copy()) {} const FST1 &GetFst() const { return *fst_; } Matcher2 *GetMatcher() const { return lmatcher_.get(); } private: std::unique_ptr<const FST1> fst_; std::unique_ptr<Matcher2> lmatcher_; }; // Stores and returns the appropriate FST and matcher for lookahead. // Specialized for lookahead on output labels. template <class Matcher1, class Matcher2> class LookAheadSelector<Matcher1, Matcher2, MATCH_OUTPUT> { public: using FST2 = typename Matcher2::FST; LookAheadSelector(Matcher1 *lmatcher1, Matcher2 *lmatcher2, MatchType) : fst_(lmatcher2->GetFst().Copy()), lmatcher_(lmatcher1->Copy()) {} LookAheadSelector( const LookAheadSelector<Matcher1, Matcher2, MATCH_OUTPUT> &selector) : fst_(selector.fst_->Copy()), lmatcher_(selector.lmatcher_->Copy()) {} const FST2 &GetFst() const { return *fst_; } Matcher1 *GetMatcher() const { return lmatcher_.get(); } private: std::unique_ptr<const FST2> fst_; std::unique_ptr<Matcher1> lmatcher_; }; // This filter uses a lookahead matcher in FilterArc(arc1, arc2) to examine the // future of the composition state (arc1.nextstate, arc2.nextstate), blocking // moving forward when its determined to be // non-coaccessible. It is templated on an underlying filter, typically the // epsilon filter. Which matcher is the lookahead matcher is determined by the // template argument MT unless it is MATCH_BOTH. In that case, both matcher // arguments must be lookahead matchers of the same type and one will be // selected by LookAheadMatchType() based on their capability. template <class Filter, class M1 = LookAheadMatcher<typename Filter::FST1>, class M2 = M1, MatchType MT = MATCH_BOTH> class LookAheadComposeFilter { public: using Arc = typename Filter::Arc; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using FST1 = typename Filter::FST1; using FST2 = typename Filter::FST2; using Matcher1 = typename Filter::Matcher1; using Matcher2 = typename Filter::Matcher2; using FilterState = typename Filter::FilterState; LookAheadComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1, M2 *matcher2) : filter_(fst1, fst2, matcher1, matcher2), lookahead_type_(MT == MATCH_BOTH ? LookAheadMatchType(*filter_.GetMatcher1(), *filter_.GetMatcher2()) : MT), selector_(filter_.GetMatcher1(), filter_.GetMatcher2(), lookahead_type_), flags_(lookahead_type_ == MATCH_OUTPUT ? filter_.GetMatcher1()->Flags() : filter_.GetMatcher2()->Flags()) { if (lookahead_type_ == MATCH_NONE) { FSTERROR() << "LookAheadComposeFilter: 1st argument cannot " << "match/look-ahead on output labels and 2nd argument " << "cannot match/look-ahead on input labels"; } selector_.GetMatcher()->InitLookAheadFst(selector_.GetFst()); } LookAheadComposeFilter( const LookAheadComposeFilter<Filter, M1, M2, MT> &filter, bool safe = false) : filter_(filter.filter_, safe), lookahead_type_(filter.lookahead_type_), selector_(filter_.GetMatcher1(), filter_.GetMatcher2(), lookahead_type_), flags_(filter.flags_) { selector_.GetMatcher()->InitLookAheadFst(selector_.GetFst(), true); } FilterState Start() const { return filter_.Start(); } void SetState(StateId s1, StateId s2, const FilterState &fs) { filter_.SetState(s1, s2, fs); } FilterState FilterArc(Arc *arc1, Arc *arc2) const { lookahead_arc_ = false; const FilterState &fs = filter_.FilterArc(arc1, arc2); if (fs == FilterState::NoState()) return FilterState::NoState(); return LookAheadOutput() ? LookAheadFilterArc(arc1, arc2, fs) : LookAheadFilterArc(arc2, arc1, fs); } void FilterFinal(Weight *weight1, Weight *weight2) const { filter_.FilterFinal(weight1, weight2); } // Returns matchers; ownership stays with filter. Matcher1 *GetMatcher1() { return filter_.GetMatcher1(); } Matcher2 *GetMatcher2() { return filter_.GetMatcher2(); } const LookAheadSelector<Matcher1, Matcher2, MT> &Selector() const { return selector_; } uint64 Properties(uint64 inprops) const { auto outprops = filter_.Properties(inprops); if (lookahead_type_ == MATCH_NONE) outprops |= kError; return outprops; } uint32 LookAheadFlags() const { return flags_; } bool LookAheadArc() const { return lookahead_arc_; } bool LookAheadOutput() const { if (MT == MATCH_OUTPUT) { return true; } else if (MT == MATCH_INPUT) { return false; } else if (lookahead_type_ == MATCH_OUTPUT) { return true; } else { return false; } } private: FilterState LookAheadFilterArc(Arc *arca, Arc *arcb, const FilterState &fs) const { auto &labela = LookAheadOutput() ? arca->olabel : arca->ilabel; if (labela != 0 && !(flags_ & kLookAheadNonEpsilons)) return fs; if (labela == 0 && !(flags_ & kLookAheadEpsilons)) return fs; lookahead_arc_ = true; selector_.GetMatcher()->SetState(arca->nextstate); return selector_.GetMatcher()->LookAheadFst(selector_.GetFst(), arcb->nextstate) ? fs : FilterState::NoState(); } Filter filter_; // Underlying filter. MatchType lookahead_type_; // Lookahead match type. LookAheadSelector<Matcher1, Matcher2, MT> selector_; uint32 flags_; // Lookahead flags. mutable bool lookahead_arc_; // Look-ahead performed at last FilterArc()? LookAheadComposeFilter &operator=(const LookAheadComposeFilter &) = delete; }; // This filter adds weight-pushing to a lookahead composition filter using the // LookAheadWeight() method of matcher argument. It is templated on an // underlying lookahead filter, typically the basic lookahead filter. // Weight-pushing in composition brings weights forward as much as possible // based on the lookahead information. template <class Filter, class M1 = LookAheadMatcher<typename Filter::FST1>, class M2 = M1, MatchType MT = MATCH_BOTH> class PushWeightsComposeFilter { public: using Arc = typename Filter::Arc; using StateId = typename Filter::StateId; using Weight = typename Filter::Weight; using FST1 = typename Filter::FST1; using FST2 = typename Filter::FST2; using Matcher1 = typename Filter::Matcher1; using Matcher2 = typename Filter::Matcher2; using FilterState1 = typename Filter::FilterState; using FilterState2 = WeightFilterState<Weight>; using FilterState = PairFilterState<FilterState1, FilterState2>; PushWeightsComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1, M2 *matcher2) : filter_(fst1, fst2, matcher1, matcher2), fs_(FilterState::NoState()) {} PushWeightsComposeFilter( const PushWeightsComposeFilter<Filter, M1, M2, MT> &filter, bool safe = false) : filter_(filter.filter_, safe), fs_(FilterState::NoState()) {} FilterState Start() const { return FilterState(filter_.Start(), FilterState2(Weight::One())); } void SetState(StateId s1, StateId s2, const FilterState &fs) { fs_ = fs; filter_.SetState(s1, s2, fs.GetState1()); } FilterState FilterArc(Arc *arc1, Arc *arc2) const { const auto &fs1 = filter_.FilterArc(arc1, arc2); if (fs1 == FilterState1::NoState()) return FilterState::NoState(); if (!(LookAheadFlags() & kLookAheadWeight)) { return FilterState(fs1, FilterState2(Weight::One())); } const auto &lweight = filter_.LookAheadArc() ? Selector().GetMatcher()->LookAheadWeight() : Weight::One(); const auto &fs2 = fs_.GetState2(); const auto &fweight = fs2.GetWeight(); // Disallows Zero() weight futures. if (lweight == Weight::Zero()) return FilterState::NoState(); arc2->weight = Divide(Times(arc2->weight, lweight), fweight); return FilterState(fs1, FilterState2(lweight.Quantize())); } void FilterFinal(Weight *weight1, Weight *weight2) const { filter_.FilterFinal(weight1, weight2); if (!(LookAheadFlags() & kLookAheadWeight) || *weight1 == Weight::Zero()) { return; } const auto &fs2 = fs_.GetState2(); const auto &fweight = fs2.GetWeight(); *weight1 = Divide(*weight1, fweight); } // Returns matchers; ownership states with filter. Matcher1 *GetMatcher1() { return filter_.GetMatcher1(); } Matcher2 *GetMatcher2() { return filter_.GetMatcher2(); } const LookAheadSelector<Matcher1, Matcher2, MT> &Selector() const { return filter_.Selector(); } uint32 LookAheadFlags() const { return filter_.LookAheadFlags(); } bool LookAheadArc() const { return filter_.LookAheadArc(); } bool LookAheadOutput() const { return filter_.LookAheadOutput(); } uint64 Properties(uint64 props) const { return filter_.Properties(props) & kWeightInvariantProperties; } private: Filter filter_; // Underlying filter. FilterState fs_; // Current filter state. PushWeightsComposeFilter &operator=(const PushWeightsComposeFilter &) = delete; }; // This filter adds label-pushing to a lookahead composition filter using the // LookAheadPrefix() method of the matcher argument. It is templated on an // underlying filter, typically the basic lookahead or weight-pushing lookahead // filter. Label-pushing in composition matches labels as early as possible // based on the lookahead information. template <class Filter, class M1 = LookAheadMatcher<typename Filter::FST1>, class M2 = M1, MatchType MT = MATCH_BOTH> class PushLabelsComposeFilter { public: using Arc = typename Filter::Arc; using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using FST1 = typename Filter::FST1; using FST2 = typename Filter::FST2; using Matcher1 = MultiEpsMatcher<typename Filter::Matcher1>; using Matcher2 = MultiEpsMatcher<typename Filter::Matcher2>; using FilterState1 = typename Filter::FilterState; using FilterState2 = IntegerFilterState<Label>; using FilterState = PairFilterState<FilterState1, FilterState2>; PushLabelsComposeFilter(const FST1 &fst1, const FST2 &fst2, M1 *matcher1, M2 *matcher2) : filter_(fst1, fst2, matcher1, matcher2), fs_(FilterState::NoState()), fst1_(filter_.GetMatcher1()->GetFst()), fst2_(filter_.GetMatcher2()->GetFst()), matcher1_(fst1_, MATCH_OUTPUT, filter_.LookAheadOutput() ? kMultiEpsList : kMultiEpsLoop, filter_.GetMatcher1(), false), matcher2_(fst2_, MATCH_INPUT, filter_.LookAheadOutput() ? kMultiEpsLoop : kMultiEpsList, filter_.GetMatcher2(), false) {} PushLabelsComposeFilter( const PushLabelsComposeFilter<Filter, M1, M2, MT> &filter, bool safe = false) : filter_(filter.filter_, safe), fs_(FilterState::NoState()), fst1_(filter_.GetMatcher1()->GetFst()), fst2_(filter_.GetMatcher2()->GetFst()), matcher1_(fst1_, MATCH_OUTPUT, filter_.LookAheadOutput() ? kMultiEpsList : kMultiEpsLoop, filter_.GetMatcher1(), false), matcher2_(fst2_, MATCH_INPUT, filter_.LookAheadOutput() ? kMultiEpsLoop : kMultiEpsList, filter_.GetMatcher2(), false) {} FilterState Start() const { return FilterState(filter_.Start(), FilterState2(kNoLabel)); } void SetState(StateId s1, StateId s2, const FilterState &fs) { fs_ = fs; filter_.SetState(s1, s2, fs.GetState1()); if (!(LookAheadFlags() & kLookAheadPrefix)) return; narcsa_ = LookAheadOutput() ? internal::NumArcs(fst1_, s1) : internal::NumArcs(fst2_, s2); const auto &fs2 = fs_.GetState2(); const auto &flabel = fs2.GetState(); GetMatcher1()->ClearMultiEpsLabels(); GetMatcher2()->ClearMultiEpsLabels(); if (flabel != kNoLabel) { // Have a lookahead label? GetMatcher1()->AddMultiEpsLabel(flabel); // Yes, make it a multi-epsilon GetMatcher2()->AddMultiEpsLabel(flabel); // label so that it matches the } // implicit epsilon arc to be } // modified below when pushing. FilterState FilterArc(Arc *arc1, Arc *arc2) const { if (!(LookAheadFlags() & kLookAheadPrefix)) { return FilterState(filter_.FilterArc(arc1, arc2), FilterState2(kNoLabel)); } const auto &fs2 = fs_.GetState2(); const auto &flabel = fs2.GetState(); if (flabel != kNoLabel) { // Have a lookahead label? return LookAheadOutput() ? PushedLabelFilterArc(arc1, arc2, flabel) : PushedLabelFilterArc(arc2, arc1, flabel); } const auto &fs1 = filter_.FilterArc(arc1, arc2); if (fs1 == FilterState1::NoState()) return FilterState::NoState(); if (!filter_.LookAheadArc()) return FilterState(fs1, FilterState2(kNoLabel)); return LookAheadOutput() ? PushLabelFilterArc(arc1, arc2, fs1) : PushLabelFilterArc(arc2, arc1, fs1); } void FilterFinal(Weight *weight1, Weight *weight2) const { filter_.FilterFinal(weight1, weight2); if (!(LookAheadFlags() & kLookAheadPrefix) || *weight1 == Weight::Zero()) { return; } const auto &fs2 = fs_.GetState2(); const auto &flabel = fs2.GetState(); if (flabel != kNoLabel) *weight1 = Weight::Zero(); } // Returns matchers; ownership states with filter. Matcher1 *GetMatcher1() { return &matcher1_; } Matcher2 *GetMatcher2() { return &matcher2_; } uint64 Properties(uint64 iprops) const { const auto oprops = filter_.Properties(iprops); if (LookAheadOutput()) { return oprops & kOLabelInvariantProperties; } else { return oprops & kILabelInvariantProperties; } } private: const LookAheadSelector<typename Filter::Matcher1, typename Filter::Matcher2, MT> &Selector() const { return filter_.Selector(); } // Consumes an already pushed label. FilterState PushedLabelFilterArc(Arc *arca, Arc *arcb, Label flabel) const { auto &labela = LookAheadOutput() ? arca->olabel : arca->ilabel; const auto &labelb = LookAheadOutput() ? arcb->ilabel : arcb->olabel; if (labelb != kNoLabel) { return FilterState::NoState(); // Blocks non-(multi-)epsilon label } else if (labela == flabel) { labela = 0; // Converts match to multi-epsilon to epsilon. return Start(); } else if (labela == 0) { if (narcsa_ == 1) return fs_; // Takes epsilon, keeping state with label. Selector().GetMatcher()->SetState(arca->nextstate); if (Selector().GetMatcher()->LookAheadLabel(flabel)) { return fs_; // Takes epsilon, keeping state with label. } else { return FilterState::NoState(); // Blocks non-coaccessible path. } } else { return FilterState::NoState(); // Blocks mismatch to multi-epsilon label. } } // Pushes a label forward when possible. FilterState PushLabelFilterArc(Arc *arca, Arc *arcb, const FilterState1 &fs1) const { auto &labela = LookAheadOutput() ? arca->olabel : arca->ilabel; const auto &labelb = LookAheadOutput() ? arcb->olabel : arcb->ilabel; if (labelb != 0) { // No place to push. return FilterState(fs1, FilterState2(kNoLabel)); } if (labela != 0 && // Wrong lookahead prefix type? LookAheadFlags() & kLookAheadNonEpsilonPrefix) { return FilterState(fs1, FilterState2(kNoLabel)); } Arc larc(kNoLabel, kNoLabel, Weight::Zero(), kNoStateId); if (Selector().GetMatcher()->LookAheadPrefix(&larc)) { // Have prefix arc? labela = LookAheadOutput() ? larc.ilabel : larc.olabel; arcb->ilabel = larc.ilabel; // Goes forward on that arc, arcb->olabel = larc.olabel; // thus pushing the label. arcb->weight = Times(arcb->weight, larc.weight); arcb->nextstate = larc.nextstate; return FilterState(fs1, FilterState2(labela)); } else { return FilterState(fs1, FilterState2(kNoLabel)); } } uint32 LookAheadFlags() const { return filter_.LookAheadFlags(); } bool LookAheadArc() const { return filter_.LookAheadArc(); } bool LookAheadOutput() const { return filter_.LookAheadOutput(); } Filter filter_; // Underlying filter. FilterState fs_; // Current filter state. const FST1 &fst1_; const FST2 &fst2_; Matcher1 matcher1_; // Multi-epsilon matcher for fst1_. Matcher2 matcher2_; // Multi-epsilon matcher for fst2_. ssize_t narcsa_; // Number of arcs leaving look-ahead match FST. PushLabelsComposeFilter &operator=(const PushLabelsComposeFilter &) = delete; }; // Convenience class for setting up composition with a default lookahead matcher // and filter. template <class Arc, MatchType type> class DefaultLookAhead { public: using M = Matcher<Fst<Arc>>; using ComposeFilter = SequenceComposeFilter<M>; using FstMatcher = M; }; // Specializes for MATCH_INPUT to allow lookahead. template <class Arc> class DefaultLookAhead<Arc, MATCH_INPUT> { public: using M = LookAheadMatcher<Fst<Arc>>; using SF = SequenceComposeFilter<M>; using ComposeFilter = LookAheadComposeFilter<SF, M>; using FstMatcher = M; }; // Specializes for MATCH_OUTPUT to allow lookahead. template <class Arc> class DefaultLookAhead<Arc, MATCH_OUTPUT> { public: using M = LookAheadMatcher<Fst<Arc>>; using SF = AltSequenceComposeFilter<M>; using ComposeFilter = LookAheadComposeFilter<SF, M>; using FstMatcher = M; }; // Specializes for StdArc to allow weight and label pushing. template <> class DefaultLookAhead<StdArc, MATCH_INPUT> { public: using M = LookAheadMatcher<Fst<StdArc>>; using SF = SequenceComposeFilter<M>; using LF = LookAheadComposeFilter<SF, M>; using WF = PushWeightsComposeFilter<LF, M>; using ComposeFilter = PushLabelsComposeFilter<WF, M>; using FstMatcher = M; }; // Specializes for StdArc to allow weight and label pushing. template <> class DefaultLookAhead<StdArc, MATCH_OUTPUT> { public: using M = LookAheadMatcher<Fst<StdArc>>; using SF = AltSequenceComposeFilter<M>; using LF = LookAheadComposeFilter<SF, M>; using WF = PushWeightsComposeFilter<LF, M>; using ComposeFilter = PushLabelsComposeFilter<WF, M>; using FstMatcher = M; }; // Specializes for LogArc to allow weight and label pushing. template <> class DefaultLookAhead<LogArc, MATCH_INPUT> { public: using M = LookAheadMatcher<Fst<LogArc>>; using SF = SequenceComposeFilter<M>; using LF = LookAheadComposeFilter<SF, M>; using WF = PushWeightsComposeFilter<LF, M>; using ComposeFilter = PushLabelsComposeFilter<WF, M>; using FstMatcher = M; }; // Specializes for LogArc to allow weight and label pushing. template <> class DefaultLookAhead<LogArc, MATCH_OUTPUT> { public: using M = LookAheadMatcher<Fst<LogArc>>; using SF = AltSequenceComposeFilter<M>; using LF = LookAheadComposeFilter<SF, M>; using WF = PushWeightsComposeFilter<LF, M>; using ComposeFilter = PushLabelsComposeFilter<WF, M>; using FstMatcher = M; }; } // namespace fst #endif // FST_LOOKAHEAD_FILTER_H_
0
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core/framework/alloc_kind.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <iosfwd> namespace onnxruntime { // The ml-Values fall into the following categories with respect to their // memory management: // - inference inputs: owned (allocated and freed) by caller, and is by // default read-only by the runtime. // - inference outputs: allocated by runtime, ownership transferred to // caller. TODO: Make sure this semantics is clear in InferenceSession API. // - weights (constant tensors): can be allocated once (statically), and // reused by all inference calls within an InferenceSession. // - tensor values: The lifetimes of these tensor-values are statically // determined, which is used for memory reuse/sharing optimizations. The // runtime allocates/frees these values at the right time (as determined // by the static allocation plan). Note that this is simplified since we // do not try to optimize for "slice" like ops, where we may be able to // conditionally reuse memory/data in some cases but not others. // Generalizing this is future work. enum class AllocKind { kNotSet = -1, kAllocate = 0, kReuse = 1, kPreExisting = 2, kAllocateStatically = 3, kAllocateOutput = 4, kShare = 5, kAllocatedExternally = 6 }; std::ostream& operator<<(std::ostream& out, AllocKind alloc_kind); } // namespace onnxruntime
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions/lookahead/Makefile.am
AM_CPPFLAGS = -I$(srcdir)/../../include $(ICU_CPPFLAGS) libfstdir = @libfstdir@ libfst_LTLIBRARIES = arc_lookahead-fst.la \ ilabel_lookahead-fst.la olabel_lookahead-fst.la lib_LTLIBRARIES = libfstlookahead.la libfstlookahead_la_SOURCES = arc_lookahead-fst.cc ilabel_lookahead-fst.cc \ olabel_lookahead-fst.cc libfstlookahead_la_LDFLAGS = -version-info 10:0:0 libfstlookahead_la_LIBADD = ../../lib/libfst.la -lm $(DL_LIBS) arc_lookahead_fst_la_SOURCES = arc_lookahead-fst.cc arc_lookahead_fst_la_LDFLAGS = -module ilabel_lookahead_fst_la_SOURCES = ilabel_lookahead-fst.cc ilabel_lookahead_fst_la_LDFLAGS = -module olabel_lookahead_fst_la_SOURCES = olabel_lookahead-fst.cc olabel_lookahead_fst_la_LDFLAGS = -module
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/script/reverse.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_REVERSE_H_ #define FST_SCRIPT_REVERSE_H_ #include <tuple> #include <fst/reverse.h> #include <fst/script/fst-class.h> namespace fst { namespace script { using ReverseArgs = std::tuple<const FstClass &, MutableFstClass *, bool>; template <class Arc> void Reverse(ReverseArgs *args) { const Fst<Arc> &ifst = *(std::get<0>(*args).GetFst<Arc>()); MutableFst<Arc> *ofst = std::get<1>(*args)->GetMutableFst<Arc>(); Reverse(ifst, ofst, std::get<2>(*args)); } void Reverse(const FstClass &ifst, MutableFstClass *ofst, bool require_superinitial = true); } // namespace script } // namespace fst #endif // FST_SCRIPT_REVERSE_H_
0
coqui_public_repos/STT-models/mongolian/itml
coqui_public_repos/STT-models/mongolian/itml/v0.1.0/MODEL_CARD.md
# Model card for Mongolian STT Jump to section: - [Model details](#model-details) - [Intended use](#intended-use) - [Performance Factors](#performance-factors) - [Metrics](#metrics) - [Training data](#training-data) - [Evaluation data](#evaluation-data) - [Ethical considerations](#ethical-considerations) - [Caveats and recommendations](#caveats-and-recommendations) ## Model details - Person or organization developing model: Originally trained by [Francis Tyers](https://scholar.google.fr/citations?user=o5HSM6cAAAAJ) and the [Inclusive Technology for Marginalised Languages](https://itml.cl.indiana.edu/) group. - Model language: Mongolian / Монгол хэл / `mn` - Model date: April 9, 2021 - Model type: `Speech-to-Text` - Model version: `v0.1.0` - Compatible with 🐸 STT version: `v0.9.3` - License: AGPL - Citation details: `@techreport{mongolian-stt, author = {Tyers,Francis}, title = {Mongolian STT 0.1}, institution = {Coqui}, address = {\url{https://github.com/coqui-ai/STT-models}} year = {2021}, month = {April}, number = {STT-CV6.1-MN-0.1} }` - Where to send questions or comments about the model: You can leave an issue on [`STT-model` issues](https://github.com/coqui-ai/STT-models/issues), open a new discussion on [`STT-model` discussions](https://github.com/coqui-ai/STT-models/discussions), or chat with us on [Gitter](https://gitter.im/coqui-ai/). ## Intended use Speech-to-Text for the [Mongolian Language](https://en.wikipedia.org/wiki/Mongolian_language) on 16kHz, mono-channel audio. ## Performance Factors Factors relevant to Speech-to-Text performance include but are not limited to speaker demographics, recording quality, and background noise. Read more about STT performance factors [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). ## Metrics STT models are usually evaluated in terms of their transcription accuracy, deployment Real-Time Factor, and model size on disk. #### Transcription Accuracy The following Word Error Rates and Character Error Rates are reported on [omnilingo](https://tepozcatl.omnilingo.cc/mn/). |Test Corpus|WER|CER| |-----------|---|---| |Common Voice|96.7\%|45.5\%| #### Real-Time Factor Real-Time Factor (RTF) is defined as `processing-time / length-of-audio`. The exact real-time factor of an STT model will depend on the hardware setup, so you may experience a different RTF. Recorded average RTF on laptop CPU: `` #### Model Size `model.pbmm`: 181M `model.tflite`: 46M ### Approaches to uncertainty and variability Confidence scores and multiple paths from the decoding beam can be used to measure model uncertainty and provide multiple, variable transcripts for any processed audio. ## Training data This model was trained on Common Voice 6.1 train. ## Evaluation data The Model was evaluated on Common Voice 6.1 test. ## Ethical considerations Deploying a Speech-to-Text model into any production setting has ethical implications. You should consider these implications before use. ### Demographic Bias You should assume every machine learning model has demographic bias unless proven otherwise. For STT models, it is often the case that transcription accuracy is better for men than it is for women. If you are using this model in production, you should acknowledge this as a potential issue. ### Surveillance Speech-to-Text may be mis-used to invade the privacy of others by recording and mining information from private conversations. This kind of individual privacy is protected by law in may countries. You should not assume consent to record and analyze private speech. ## Caveats and recommendations Machine learning models (like this STT model) perform best on data that is similar to the data on which they were trained. Read about what to expect from an STT model with regard to your data [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). In most applications, it is recommended that you [train your own language model](https://stt.readthedocs.io/en/latest/LANGUAGE_MODEL.html) to improve transcription accuracy on your speech data.
0
coqui_public_repos/STT/native_client/wasm
coqui_public_repos/STT/native_client/wasm/test/stt-wasm.test.js
import STT from 'stt-wasm'; describe('STT WASM', () => { it('Checks stt-wasm was imported', () => { expect(STT).toBeDefined(); }) it.skip('Instantiates correctly the module', async () => { let ready = false; let instance = await STT({ 'locateFile': (filename) => { if (filename == 'stt_wasm.worker.js') { return `${__dirname}/mock.worker.js`; } return `${__dirname}/node_modules/stt-wasm/dist/${filename}` } }); expect(ready).toBeTrue(); expect(instance).toBeDefined(); }) })
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/product-weight.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Product weight set and associated semiring operation definitions. #ifndef FST_PRODUCT_WEIGHT_H_ #define FST_PRODUCT_WEIGHT_H_ #include <string> #include <utility> #include <fst/pair-weight.h> #include <fst/weight.h> namespace fst { // Product semiring: W1 * W2. template <class W1, class W2> class ProductWeight : public PairWeight<W1, W2> { public: using ReverseWeight = ProductWeight<typename W1::ReverseWeight, typename W2::ReverseWeight>; ProductWeight() {} explicit ProductWeight(const PairWeight<W1, W2> &weight) : PairWeight<W1, W2>(weight) {} ProductWeight(W1 w1, W2 w2) : PairWeight<W1, W2>(std::move(w1), std::move(w2)) {} static const ProductWeight &Zero() { static const ProductWeight zero(PairWeight<W1, W2>::Zero()); return zero; } static const ProductWeight &One() { static const ProductWeight one(PairWeight<W1, W2>::One()); return one; } static const ProductWeight &NoWeight() { static const ProductWeight no_weight(PairWeight<W1, W2>::NoWeight()); return no_weight; } static const string &Type() { static const string *const type = new string(W1::Type() + "_X_" + W2::Type()); return *type; } static constexpr uint64 Properties() { return W1::Properties() & W2::Properties() & (kLeftSemiring | kRightSemiring | kCommutative | kIdempotent); } ProductWeight Quantize(float delta = kDelta) const { return ProductWeight(PairWeight<W1, W2>::Quantize(delta)); } ReverseWeight Reverse() const { return ReverseWeight(PairWeight<W1, W2>::Reverse()); } }; template <class W1, class W2> inline ProductWeight<W1, W2> Plus(const ProductWeight<W1, W2> &w1, const ProductWeight<W1, W2> &w2) { return ProductWeight<W1, W2>(Plus(w1.Value1(), w2.Value1()), Plus(w1.Value2(), w2.Value2())); } template <class W1, class W2> inline ProductWeight<W1, W2> Times(const ProductWeight<W1, W2> &w1, const ProductWeight<W1, W2> &w2) { return ProductWeight<W1, W2>(Times(w1.Value1(), w2.Value1()), Times(w1.Value2(), w2.Value2())); } template <class W1, class W2> inline ProductWeight<W1, W2> Divide(const ProductWeight<W1, W2> &w1, const ProductWeight<W1, W2> &w2, DivideType typ = DIVIDE_ANY) { return ProductWeight<W1, W2>(Divide(w1.Value1(), w2.Value1(), typ), Divide(w1.Value2(), w2.Value2(), typ)); } // This function object generates weights by calling the underlying generators // for the template weight types, like all other pair weight types. This is // intended primarily for testing. template <class W1, class W2> class WeightGenerate<ProductWeight<W1, W2>> : public WeightGenerate<PairWeight<W1, W2>> { public: using Weight = ProductWeight<W1, W2>; using Generate = WeightGenerate<PairWeight<W1, W2>>; explicit WeightGenerate(bool allow_zero = true) : Generate(allow_zero) {} Weight operator()() const { return Weight(Generate::operator()()); } }; } // namespace fst #endif // FST_PRODUCT_WEIGHT_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions/special/CMakeLists.txt
file(GLOB HEADER_FILES ../../include/fst/extensions/special/*.h) message(STATUS "${HEADER_FILES}") if(HAVE_BIN) add_executable(fstspecial-bin ../../bin/fstconvert.cc ../../bin/fstconvert-main.cc phi-fst.cc rho-fst.cc sigma-fst.cc ) set_target_properties(fstspecial-bin PROPERTIES FOLDER special/bin OUTPUT_NAME fstspecial ) target_link_libraries(fstspecial-bin fstscript fst ${CMAKE_DL_LIBS} ) endif(HAVE_BIN) add_library(fstspecial phi-fst.cc rho-fst.cc sigma-fst.cc ${HEADER_FILES} ) set_target_properties(fstspecial PROPERTIES SOVERSION "${SOVERSION}" FOLDER special ) target_link_libraries(fstspecial fst ) install(TARGETS fstspecial fstspecial-bin LIBRARY DESTINATION lib RUNTIME DESTINATION bin ARCHIVE DESTINATION lib ) function (add_module _name) add_library(${ARGV}) if (TARGET ${_name}) target_link_libraries(${_name} fst) set_target_properties(${_name} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS true FOLDER special/modules ) endif() install(TARGETS ${_name} LIBRARY DESTINATION lib/fst) endfunction() add_module(phi-fst MODULE phi-fst.cc) add_module(rho-fst MODULE rho-fst.cc) add_module(sigma-fst MODULE sigma-fst.cc)
0
coqui_public_repos/TTS/recipes/thorsten_DE
coqui_public_repos/TTS/recipes/thorsten_DE/vits_tts/train_vits.py
import os from trainer import Trainer, TrainerArgs from TTS.tts.configs.shared_configs import BaseDatasetConfig from TTS.tts.configs.vits_config import VitsConfig from TTS.tts.datasets import load_tts_samples from TTS.tts.models.vits import Vits, VitsAudioConfig from TTS.tts.utils.text.tokenizer import TTSTokenizer from TTS.utils.audio import AudioProcessor from TTS.utils.downloaders import download_thorsten_de output_path = os.path.dirname(os.path.abspath(__file__)) dataset_config = BaseDatasetConfig( formatter="thorsten", meta_file_train="metadata.csv", path=os.path.join(output_path, "../thorsten-de/") ) # download dataset if not already present if not os.path.exists(dataset_config.path): print("Downloading dataset") download_thorsten_de(os.path.split(os.path.abspath(dataset_config.path))[0]) audio_config = VitsAudioConfig( sample_rate=22050, win_length=1024, hop_length=256, num_mels=80, mel_fmin=0, mel_fmax=None, ) config = VitsConfig( audio=audio_config, run_name="vits_thorsten-de", batch_size=32, eval_batch_size=16, batch_group_size=5, num_loader_workers=0, num_eval_loader_workers=4, run_eval=True, test_delay_epochs=-1, epochs=1000, text_cleaner="phoneme_cleaners", use_phonemes=True, phoneme_language="de", phoneme_cache_path=os.path.join(output_path, "phoneme_cache"), compute_input_seq_cache=True, print_step=25, print_eval=True, mixed_precision=True, test_sentences=[ "Es hat mich viel Zeit gekostet ein Stimme zu entwickeln, jetzt wo ich sie habe werde ich nicht mehr schweigen.", "Sei eine Stimme, kein Echo.", "Es tut mir Leid David. Das kann ich leider nicht machen.", "Dieser Kuchen ist großartig. Er ist so lecker und feucht.", "Vor dem 22. November 1963.", ], output_path=output_path, datasets=[dataset_config], ) # INITIALIZE THE AUDIO PROCESSOR # Audio processor is used for feature extraction and audio I/O. # It mainly serves to the dataloader and the training loggers. ap = AudioProcessor.init_from_config(config) # INITIALIZE THE TOKENIZER # Tokenizer is used to convert text to sequences of token IDs. # config is updated with the default characters if not defined in the config. tokenizer, config = TTSTokenizer.init_from_config(config) # LOAD DATA SAMPLES # Each sample is a list of ```[text, audio_file_path, speaker_name]``` # You can define your custom sample loader returning the list of samples. # Or define your custom formatter and pass it to the `load_tts_samples`. # Check `TTS.tts.datasets.load_tts_samples` for more details. train_samples, eval_samples = load_tts_samples( dataset_config, eval_split=True, eval_split_max_size=config.eval_split_max_size, eval_split_size=config.eval_split_size, ) # init model model = Vits(config, ap, tokenizer, speaker_manager=None) # init the trainer and 🚀 trainer = Trainer( TrainerArgs(), config, output_path, model=model, train_samples=train_samples, eval_samples=eval_samples, ) trainer.fit()
0
coqui_public_repos/STT
coqui_public_repos/STT/doc/MIXED_PRECISION.rst
.. _automatic-mixed-precision: Automatic Mixed Precision ========================= Training with `automatic mixed precision <https://medium.com/tensorflow/automatic-mixed-precision-in-tensorflow-for-faster-ai-training-on-nvidia-gpus-6033234b2540>`_ is available when training STT on an GPU. Mixed precision training makes use of both ``FP32`` and ``FP16`` precisions where appropriate. ``FP16`` operations can leverage the Tensor cores on NVIDIA GPUs (Volta, Turing or newer architectures) for improved throughput. Mixed precision training often allows larger batch sizes. Automatic mixed precision training can be enabled by including the flag ``--automatic_mixed_precision true`` at training time: .. code-block:: bash $ python -m coqui_stt_training.train \ --train_files train.csv \ --dev_files dev.csv \ --test_files test.csv \ --automatic_mixed_precision true On a Volta generation V100 GPU, automatic mixed precision can speed up 🐸STT training and evaluation by approximately 30% to 40%.
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/flashlight/flashlight/lib
coqui_public_repos/STT/native_client/ctcdecode/third_party/flashlight/flashlight/lib/common/String.h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <algorithm> #include <cerrno> #include <chrono> #include <cstring> #include <stdexcept> #include <string> #include <type_traits> #include <unordered_map> #include <vector> namespace fl { namespace lib { // ============================ Types and Templates ============================ template <typename It> using DecayDereference = typename std::decay<decltype(*std::declval<It>())>::type; template <typename S, typename T> using EnableIfSame = typename std::enable_if<std::is_same<S, T>::value>::type; // ================================== Functions // ================================== std::string trim(const std::string& str); void replaceAll( std::string& str, const std::string& from, const std::string& repl); bool startsWith(const std::string& input, const std::string& pattern); bool endsWith(const std::string& input, const std::string& pattern); std::vector<std::string> split(char delim, const std::string& input, bool ignoreEmpty = false); std::vector<std::string> split( const std::string& delim, const std::string& input, bool ignoreEmpty = false); std::vector<std::string> splitOnAnyOf( const std::string& delim, const std::string& input, bool ignoreEmpty = false); std::vector<std::string> splitOnWhitespace( const std::string& input, bool ignoreEmpty = false); /** * Join a vector of `std::string` inserting `delim` in between. */ std::string join(const std::string& delim, const std::vector<std::string>& vec); /** * Join a range of `std::string` specified by iterators. */ template < typename FwdIt, typename = EnableIfSame<DecayDereference<FwdIt>, std::string>> std::string join(const std::string& delim, FwdIt begin, FwdIt end) { if (begin == end) { return ""; } size_t totalSize = begin->size(); for (auto it = std::next(begin); it != end; ++it) { totalSize += delim.size() + it->size(); } std::string result; result.reserve(totalSize); result.append(*begin); for (auto it = std::next(begin); it != end; ++it) { result.append(delim); result.append(*it); } return result; } /** * Create an output string using a `printf`-style format string and arguments. * Safer than `sprintf` which is vulnerable to buffer overflow. */ template <class... Args> std::string format(const char* fmt, Args&&... args) { auto res = std::snprintf(nullptr, 0, fmt, std::forward<Args>(args)...); if (res < 0) { throw std::runtime_error(std::strerror(errno)); } std::string buf(res, '\0'); // the size here is fine -- it's legal to write '\0' to buf[res] auto res2 = std::snprintf(&buf[0], res + 1, fmt, std::forward<Args>(args)...); if (res2 < 0) { throw std::runtime_error(std::strerror(errno)); } if (res2 != res) { throw std::runtime_error( "The size of the formated string is not equal to what it is expected."); } return buf; } /** * Dedup the elements in a vector. */ template <class T> void dedup(std::vector<T>& in) { if (in.empty()) { return; } auto it = std::unique(in.begin(), in.end()); in.resize(std::distance(in.begin(), it)); } } // namespace lib } // namespace fl
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/extensions/far/stlist.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // A generic (string,type) list file format. // // This is a stripped-down version of STTable that does not support the Find() // operation but that does support reading/writting from standard in/out. #ifndef FST_EXTENSIONS_FAR_STLIST_H_ #define FST_EXTENSIONS_FAR_STLIST_H_ #include <algorithm> #include <functional> #include <iostream> #include <memory> #include <queue> #include <string> #include <utility> #include <vector> #include <fstream> #include <fst/util.h> namespace fst { static constexpr int32_t kSTListMagicNumber = 5656924; static constexpr int32_t kSTListFileVersion = 1; // String-type list writing class for object of type T using a functor Writer. // The Writer functor must provide at least the following interface: // // struct Writer { // void operator()(std::ostream &, const T &) const; // }; template <class T, class Writer> class STListWriter { public: explicit STListWriter(const string &filename) : stream_(filename.empty() ? &std::cout : new std::ofstream( filename, std::ios_base::out | std::ios_base::binary)), error_(false) { WriteType(*stream_, kSTListMagicNumber); WriteType(*stream_, kSTListFileVersion); if (!stream_) { FSTERROR() << "STListWriter::STListWriter: Error writing to file: " << filename; error_ = true; } } static STListWriter<T, Writer> *Create(const string &filename) { return new STListWriter<T, Writer>(filename); } void Add(const string &key, const T &t) { if (key == "") { FSTERROR() << "STListWriter::Add: Key empty: " << key; error_ = true; } else if (key < last_key_) { FSTERROR() << "STListWriter::Add: Key out of order: " << key; error_ = true; } if (error_) return; last_key_ = key; WriteType(*stream_, key); entry_writer_(*stream_, t); } bool Error() const { return error_; } ~STListWriter() { WriteType(*stream_, string()); if (stream_ != &std::cout) delete stream_; } private: Writer entry_writer_; std::ostream *stream_; // Output stream. string last_key_; // Last key. bool error_; STListWriter(const STListWriter &) = delete; STListWriter &operator=(const STListWriter &) = delete; }; // String-type list reading class for object of type T using a functor Reader. // Reader must provide at least the following interface: // // struct Reader { // T *operator()(std::istream &) const; // }; template <class T, class Reader> class STListReader { public: explicit STListReader(const std::vector<string> &filenames) : sources_(filenames), error_(false) { streams_.resize(filenames.size(), 0); bool has_stdin = false; for (size_t i = 0; i < filenames.size(); ++i) { if (filenames[i].empty()) { if (!has_stdin) { streams_[i] = &std::cin; sources_[i] = "stdin"; has_stdin = true; } else { FSTERROR() << "STListReader::STListReader: Cannot read multiple " << "inputs from standard input"; error_ = true; return; } } else { streams_[i] = new std::ifstream( filenames[i], std::ios_base::in | std::ios_base::binary); } int32_t magic_number = 0; ReadType(*streams_[i], &magic_number); int32_t file_version = 0; ReadType(*streams_[i], &file_version); if (magic_number != kSTListMagicNumber) { FSTERROR() << "STListReader::STListReader: Wrong file type: " << filenames[i]; error_ = true; return; } if (file_version != kSTListFileVersion) { FSTERROR() << "STListReader::STListReader: Wrong file version: " << filenames[i]; error_ = true; return; } string key; ReadType(*streams_[i], &key); if (!key.empty()) heap_.push(std::make_pair(key, i)); if (!*streams_[i]) { FSTERROR() << "STListReader: Error reading file: " << sources_[i]; error_ = true; return; } } if (heap_.empty()) return; const auto current = heap_.top().second; entry_.reset(entry_reader_(*streams_[current])); if (!entry_ || !*streams_[current]) { FSTERROR() << "STListReader: Error reading entry for key " << heap_.top().first << ", file " << sources_[current]; error_ = true; } } ~STListReader() { for (auto &stream : streams_) { if (stream != &std::cin) delete stream; } } static STListReader<T, Reader> *Open(const string &filename) { std::vector<string> filenames; filenames.push_back(filename); return new STListReader<T, Reader>(filenames); } static STListReader<T, Reader> *Open(const std::vector<string> &filenames) { return new STListReader<T, Reader>(filenames); } void Reset() { FSTERROR() << "STListReader::Reset: Operation not supported"; error_ = true; } bool Find(const string &key) { FSTERROR() << "STListReader::Find: Operation not supported"; error_ = true; return false; } bool Done() const { return error_ || heap_.empty(); } void Next() { if (error_) return; auto current = heap_.top().second; string key; heap_.pop(); ReadType(*(streams_[current]), &key); if (!*streams_[current]) { FSTERROR() << "STListReader: Error reading file: " << sources_[current]; error_ = true; return; } if (!key.empty()) heap_.push(std::make_pair(key, current)); if (!heap_.empty()) { current = heap_.top().second; entry_.reset(entry_reader_(*streams_[current])); if (!entry_ || !*streams_[current]) { FSTERROR() << "STListReader: Error reading entry for key: " << heap_.top().first << ", file: " << sources_[current]; error_ = true; } } } const string &GetKey() const { return heap_.top().first; } const T *GetEntry() const { return entry_.get(); } bool Error() const { return error_; } private: Reader entry_reader_; // Read functor. std::vector<std::istream *> streams_; // Input streams. std::vector<string> sources_; // Corresponding filenames. std::priority_queue< std::pair<string, size_t>, std::vector<std::pair<string, size_t>>, std::greater<std::pair<string, size_t>>> heap_; // (Key, stream id) heap mutable std::unique_ptr<T> entry_; // The currently read entry. bool error_; STListReader(const STListReader &) = delete; STListReader &operator=(const STListReader &) = delete; }; // String-type list header reading function, templated on the entry header type. // The Header type must provide at least the following interface: // // struct Header { // void Read(std::istream &strm, const string &filename); // }; template <class Header> bool ReadSTListHeader(const string &filename, Header *header) { if (filename.empty()) { LOG(ERROR) << "ReadSTListHeader: Can't read header from standard input"; return false; } std::ifstream strm(filename, std::ios_base::in | std::ios_base::binary); if (!strm) { LOG(ERROR) << "ReadSTListHeader: Could not open file: " << filename; return false; } int32_t magic_number = 0; ReadType(strm, &magic_number); int32_t file_version = 0; ReadType(strm, &file_version); if (magic_number != kSTListMagicNumber) { LOG(ERROR) << "ReadSTListHeader: Wrong file type: " << filename; return false; } if (file_version != kSTListFileVersion) { LOG(ERROR) << "ReadSTListHeader: Wrong file version: " << filename; return false; } string key; ReadType(strm, &key); header->Read(strm, filename + ":" + key); if (!strm) { LOG(ERROR) << "ReadSTListHeader: Error reading file: " << filename; return false; } return true; } bool IsSTList(const string &filename); } // namespace fst #endif // FST_EXTENSIONS_FAR_STLIST_H_
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-nodejs_13x_16k_multiarchpkg-linux-amd64-opt.yml
build: template_file: test-linux-opt-base.tyml docker_image: "ubuntu:16.04" dependencies: - "node-package-cpu" - "test-training_16k-linux-amd64-py36m-opt" test_model_task: "test-training_16k-linux-amd64-py36m-opt" system_setup: > ${nodejs.packages_xenial.prep_13} && ${nodejs.packages_xenial.apt_pinning} && apt-get -qq update && apt-get -qq -y install ${nodejs.packages_xenial.apt} args: tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-node-tests.sh 13.x 16k" workerType: "${docker.dsTests}" metadata: name: "DeepSpeech Linux AMD64 CPU NodeJS MultiArch Package 13.x tests (16kHz)" description: "Testing DeepSpeech for Linux/AMD64 on NodeJS MultiArch Package v13.x, CPU only, optimized version (16kHz)"
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/script/difference.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_DIFFERENCE_H_ #define FST_SCRIPT_DIFFERENCE_H_ #include <tuple> #include <fst/difference.h> #include <fst/script/compose.h> #include <fst/script/fst-class.h> namespace fst { namespace script { using DifferenceArgs = std::tuple<const FstClass &, const FstClass &, MutableFstClass *, const ComposeOptions &>; template <class Arc> void Difference(DifferenceArgs *args) { const Fst<Arc> &ifst1 = *(std::get<0>(*args).GetFst<Arc>()); const Fst<Arc> &ifst2 = *(std::get<1>(*args).GetFst<Arc>()); MutableFst<Arc> *ofst = std::get<2>(*args)->GetMutableFst<Arc>(); const auto &opts = std::get<3>(*args); Difference(ifst1, ifst2, ofst, opts); } void Difference(const FstClass &ifst1, const FstClass &ifst2, MutableFstClass *ofst, const ComposeOptions &opts = ComposeOptions()); } // namespace script } // namespace fst #endif // FST_SCRIPT_DIFFERENCE_H_
0
coqui_public_repos/STT/native_client/dotnet
coqui_public_repos/STT/native_client/dotnet/STTWPF/App.xaml
<Application x:Class="STTWPF.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:STTWPF" StartupUri="MainWindow.xaml"> <Application.Resources /> </Application>
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/script/fst-class.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // These classes are only recommended for use in high-level scripting // applications. Most users should use the lower-level templated versions // corresponding to these classes. #include <istream> #include <fst/log.h> #include <fst/equal.h> #include <fst/fst-decl.h> #include <fst/reverse.h> #include <fst/union.h> #include <fst/script/fst-class.h> #include <fst/script/register.h> namespace fst { namespace script { // Registration. REGISTER_FST_CLASSES(StdArc); REGISTER_FST_CLASSES(LogArc); REGISTER_FST_CLASSES(Log64Arc); // Helper functions. namespace { template <class F> F *ReadFstClass(std::istream &istrm, const string &fname) { if (!istrm) { LOG(ERROR) << "ReadFstClass: Can't open file: " << fname; return nullptr; } FstHeader hdr; if (!hdr.Read(istrm, fname)) return nullptr; const FstReadOptions read_options(fname, &hdr); const auto &arc_type = hdr.ArcType(); static const auto *io_register = IORegistration<F>::Register::GetRegister(); const auto reader = io_register->GetReader(arc_type); if (!reader) { LOG(ERROR) << "ReadFstClass: Unknown arc type: " << arc_type; return nullptr; } return reader(istrm, read_options); } template <class F> FstClassImplBase *CreateFstClass(const string &arc_type) { static const auto *io_register = IORegistration<F>::Register::GetRegister(); auto creator = io_register->GetCreator(arc_type); if (!creator) { FSTERROR() << "CreateFstClass: Unknown arc type: " << arc_type; return nullptr; } return creator(); } template <class F> FstClassImplBase *ConvertFstClass(const FstClass &other) { static const auto *io_register = IORegistration<F>::Register::GetRegister(); auto converter = io_register->GetConverter(other.ArcType()); if (!converter) { FSTERROR() << "ConvertFstClass: Unknown arc type: " << other.ArcType(); return nullptr; } return converter(other); } } // namespace // FstClass methods. FstClass *FstClass::Read(const string &fname) { if (!fname.empty()) { std::ifstream istrm(fname, std::ios_base::in | std::ios_base::binary); return ReadFstClass<FstClass>(istrm, fname); } else { return ReadFstClass<FstClass>(std::cin, "standard input"); } } FstClass *FstClass::Read(std::istream &istrm, const string &source) { return ReadFstClass<FstClass>(istrm, source); } bool FstClass::WeightTypesMatch(const WeightClass &weight, const string &op_name) const { if (WeightType() != weight.Type()) { FSTERROR() << "FST and weight with non-matching weight types passed to " << op_name << ": " << WeightType() << " and " << weight.Type(); return false; } return true; } // MutableFstClass methods. MutableFstClass *MutableFstClass::Read(const string &fname, bool convert) { if (convert == false) { if (!fname.empty()) { std::ifstream in(fname, std::ios_base::in | std::ios_base::binary); return ReadFstClass<MutableFstClass>(in, fname); } else { return ReadFstClass<MutableFstClass>(std::cin, "standard input"); } } else { // Converts to VectorFstClass if not mutable. std::unique_ptr<FstClass> ifst(FstClass::Read(fname)); if (!ifst) return nullptr; if (ifst->Properties(kMutable, false) == kMutable) { return static_cast<MutableFstClass *>(ifst.release()); } else { return new VectorFstClass(*ifst.release()); } } } // VectorFstClass methods. VectorFstClass *VectorFstClass::Read(const string &fname) { if (!fname.empty()) { std::ifstream in(fname, std::ios_base::in | std::ios_base::binary); return ReadFstClass<VectorFstClass>(in, fname); } else { return ReadFstClass<VectorFstClass>(std::cin, "standard input"); } } VectorFstClass::VectorFstClass(const string &arc_type) : MutableFstClass(CreateFstClass<VectorFstClass>(arc_type)) {} VectorFstClass::VectorFstClass(const FstClass &other) : MutableFstClass(ConvertFstClass<VectorFstClass>(other)) {} } // namespace script } // namespace fst
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/config.h.in
// OpenFst config file /* Define to 1 if you have the ICU library. */ #undef HAVE_ICU /* Define to 1 if the system has the type `std::tr1::hash<long long unsigned>'. */ #define HAVE_STD__TR1__HASH_LONG_LONG_UNSIGNED_ 1 /* Define to 1 if the system has the type `__gnu_cxx::slist<int>'. */ #define HAVE___GNU_CXX__SLIST_INT_ 1
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/tf_android-arm64-dbg.yml
build: template_file: generic_tc_caching-linux-opt-base.tyml cache: artifact_url: ${system.tensorflow_dbg.android_arm64.url} artifact_namespace: ${system.tensorflow_dbg.android_arm64.namespace} system_config: > ${tensorflow.packages_xenial.apt} && ${java.packages_xenial.apt} scripts: setup: "taskcluster/tf_tc-setup.sh --android-arm64" build: "taskcluster/tf_tc-build.sh --android-arm64 dbg" package: "taskcluster/tf_tc-package.sh" maxRunTime: 14400 workerType: "${docker.tfBuild}" metadata: name: "TensorFlow Android ARM64 debug" description: "Building TensorFlow for Android ARM64, debug version"
0
coqui_public_repos/inference-engine/third_party
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/install-sh
#!/bin/sh # install - install a program, script, or datafile scriptversion=2011-11-20.07; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # 'make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. nl=' ' IFS=" "" $nl" # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit=${DOITPROG-} if test -z "$doit"; then doit_exec=exec else doit_exec=$doit fi # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_glob='?' initialize_posix_glob=' test "$posix_glob" != "?" || { if (set -f) 2>/dev/null; then posix_glob= else posix_glob=: fi } ' posix_mkdir= # Desired mode of installed file. mode=0755 chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false no_target_directory= usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve the last data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -s $stripprog installed files. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *' '* | *' '* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -s) stripcmd=$stripprog;; -t) dst_arg=$2 # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) no_target_directory=true;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call 'install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for 'test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename; won't work # if double slashes aren't ignored. if test -d "$dst"; then if test -n "$no_target_directory"; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dst=$dstdir/`basename "$src"` dstdir_status=0 else # Prefer dirname, but fall back on a substitute if dirname fails. dstdir=` (dirname "$dst") 2>/dev/null || expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$dst" : 'X\(//\)[^/]' \| \ X"$dst" : 'X\(//\)$' \| \ X"$dst" : 'X\(/\)' \| . 2>/dev/null || echo X"$dst" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q' ` test -d "$dstdir" dstdir_status=$? fi fi obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # Create intermediate dirs using mode 755 as modified by the umask. # This is like FreeBSD 'install' as of 1997-10-28. umask=`umask` case $stripcmd.$umask in # Optimize common cases. *[2367][2367]) mkdir_umask=$umask;; .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; *[0-7]) mkdir_umask=`expr $umask + 22 \ - $umask % 100 % 40 + $umask % 20 \ - $umask % 10 % 4 + $umask % 2 `;; *) mkdir_umask=$umask,go-w;; esac # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false case $umask in *[123567][0-7][0-7]) # POSIX mkdir -p sets u+wx bits regardless of umask, which # is incompatible with FreeBSD 'install' when (umask & 300) != 0. ;; *) tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 if (umask $mkdir_umask && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. ls_ld_tmpdir=`ls -ld "$tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/d" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null fi trap '' 0;; esac;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # The umask is ridiculous, or mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac eval "$initialize_posix_glob" oIFS=$IFS IFS=/ $posix_glob set -f set fnord $dstdir shift $posix_glob set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask=$mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=$dstdir/_inst.$$_ rmtmp=$dstdir/_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && eval "$initialize_posix_glob" && $posix_glob set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && $posix_glob set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd -f "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End:
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/bin/fstrmepsilon-main.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Removes epsilons from an FST. #include <cstring> #include <memory> #include <string> #include <fst/flags.h> #include <fst/log.h> #include <fst/script/getters.h> #include <fst/script/rmepsilon.h> DECLARE_bool(connect); DECLARE_double(delta); DECLARE_int64(nstate); DECLARE_string(queue_type); DECLARE_string(weight); int fstrmepsilon_main(int argc, char **argv) { namespace s = fst::script; using fst::script::MutableFstClass; using fst::script::WeightClass; string usage = "Removes epsilons from an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; std::set_new_handler(FailedNewHandler); SET_FLAGS(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } const string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : ""; const string out_name = argc > 2 ? argv[2] : ""; std::unique_ptr<MutableFstClass> fst(MutableFstClass::Read(in_name, true)); if (!fst) return 1; const auto weight_threshold = FLAGS_weight.empty() ? WeightClass::Zero(fst->WeightType()) : WeightClass(fst->WeightType(), FLAGS_weight); fst::QueueType queue_type; if (!s::GetQueueType(FLAGS_queue_type, &queue_type)) { LOG(ERROR) << argv[0] << ": Unknown or unsupported queue type: " << FLAGS_queue_type; return 1; } const s::RmEpsilonOptions opts(queue_type, FLAGS_connect, weight_threshold, FLAGS_nstate, FLAGS_delta); s::RmEpsilon(fst.get(), opts); return !fst->Write(out_name); }
0
coqui_public_repos/STT-models/chuvash/itml
coqui_public_repos/STT-models/chuvash/itml/v0.1.0/alphabet.txt
- а б в г д е ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я ё ҫ ӑ ӗ ӳ
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions/CMakeLists.txt
if(HAVE_COMPACT) add_subdirectory(compact) endif(HAVE_COMPACT) if(HAVE_COMPRESS) add_subdirectory(compress) endif(HAVE_COMPRESS) if(HAVE_CONST) add_subdirectory(const) endif(HAVE_CONST) if(HAVE_FAR OR HAVE_GRM) add_subdirectory(far) endif(HAVE_FAR OR HAVE_GRM) if(HAVE_LINEAR) add_subdirectory(linear) endif(HAVE_LINEAR) if(HAVE_LOOKAHEAD) add_subdirectory(lookahead) endif(HAVE_LOOKAHEAD) if(HAVE_MPDT OR HAVE_GRM) add_subdirectory(mpdt) endif(HAVE_MPDT OR HAVE_GRM) if(HAVE_NGRAM) add_subdirectory(ngram) endif(HAVE_NGRAM) #if(HAVE_PYTHON) # add_subdirectory(far) # add_subdirectory(python) #endif(HAVE_PDT) # if(HAVE_PDT OR HAVE_MPDT OR HAVE_GRM) add_subdirectory(pdt) endif(HAVE_PDT OR HAVE_MPDT OR HAVE_GRM) if(HAVE_SPECIAL) add_subdirectory(special) endif(HAVE_SPECIAL)
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-electronjs_v10.0-win-amd64-opt.yml
build: template_file: test-win-opt-base.tyml dependencies: - "win-amd64-cpu-opt" - "test-training_16k-linux-amd64-py36m-opt" test_model_task: "test-training_16k-linux-amd64-py36m-opt" system_setup: > ${system.sox_win} && ${nodejs.win.prep_12} args: tests_cmdline: "${system.homedir.win}/DeepSpeech/ds/taskcluster/tc-electron-tests.sh 12.x 10.0.0 16k" metadata: name: "DeepSpeech Windows AMD64 CPU ElectronJS v10.0 tests" description: "Testing DeepSpeech for Windows/AMD64 on ElectronJS v10.0, CPU only, optimized version"
0
coqui_public_repos
coqui_public_repos/coqui-py/Makefile
.DEFAULT_GOAL := help .PHONY: help package node_deps help: @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' node_deps: package.json yarn install react_build: node_deps yarn build package: react_build # build Python package python -m pip install build python -m build dev_install: react_build python -m pip install -e ".[test]" install: react_build python -m pip install . install_test: react_build python -m pip install ".[test]" install_pre_commit_hooks: .pre-commit-config.yaml python .pre-commit-2.13.0.pyz install frontend_tests: yarn run test:client backend_tests: pytest
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/test/rand-fst.h
#ifndef FST_TEST_RAND_FST_H_ #define FST_TEST_RAND_FST_H_ #include <fst/log.h> #include <fst/mutable-fst.h> #include <fst/verify.h> namespace fst { // Generates a random FST. template <class Arc, class WeightGenerator> void RandFst(const int num_random_states, const int num_random_arcs, const int num_random_labels, const float acyclic_prob, WeightGenerator *weight_generator, MutableFst<Arc> *fst) { typedef typename Arc::Label Label; typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; // Determines direction of the arcs wrt state numbering. This way we // can force acyclicity when desired. enum ArcDirection { ANY_DIRECTION = 0, FORWARD_DIRECTION = 1, REVERSE_DIRECTION = 2, NUM_DIRECTIONS = 3 }; ArcDirection arc_direction = ANY_DIRECTION; if (rand() / (RAND_MAX + 1.0) < acyclic_prob) arc_direction = rand() % 2 ? FORWARD_DIRECTION : REVERSE_DIRECTION; fst->DeleteStates(); StateId ns = rand() % num_random_states; if (ns == 0) return; for (StateId s = 0; s < ns; ++s) fst->AddState(); StateId start = rand() % ns; fst->SetStart(start); size_t na = rand() % num_random_arcs; for (size_t n = 0; n < na; ++n) { StateId s = rand() % ns; Arc arc; arc.ilabel = rand() % num_random_labels; arc.olabel = rand() % num_random_labels; arc.weight = (*weight_generator)(); arc.nextstate = rand() % ns; if ((arc_direction == FORWARD_DIRECTION || arc_direction == REVERSE_DIRECTION) && s == arc.nextstate) { continue; // skips self-loops } if ((arc_direction == FORWARD_DIRECTION && s > arc.nextstate) || (arc_direction == REVERSE_DIRECTION && s < arc.nextstate)) { StateId t = s; // reverses arcs s = arc.nextstate; arc.nextstate = t; } fst->AddArc(s, arc); } StateId nf = rand() % (ns + 1); for (StateId n = 0; n < nf; ++n) { StateId s = rand() % ns; Weight final = (*weight_generator)(); fst->SetFinal(s, final); } VLOG(1) << "Check FST for sanity (including property bits)."; CHECK(Verify(*fst)); // Get/compute all properties. uint64_t props = fst->Properties(kFstProperties, true); // Select random set of properties to be unknown. uint64_t mask = 0; for (int n = 0; n < 8; ++n) { mask |= rand() & 0xff; mask <<= 8; } mask &= ~kTrinaryProperties; fst->SetProperties(props & ~mask, mask); } } // namespace fst #endif // FST_TEST_RAND_FST_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/bin/fstclosure.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/flags.h> DEFINE_bool(closure_plus, false, "Do not add the empty path (T+ instead of T*)?"); int fstclosure_main(int argc, char **argv); int main(int argc, char **argv) { return fstclosure_main(argc, argv); }
0
coqui_public_repos/Trainer/trainer
coqui_public_repos/Trainer/trainer/utils/cpu_memory.py
def get_available_cpu_memory(): import psutil # pylint: disable=import-outside-toplevel this_process = psutil.Process() available_memory = psutil.virtual_memory().available try: import resource # pylint: disable=import-outside-toplevel _, hard_mem_limit = resource.getrlimit(resource.RLIMIT_AS) # pylint: disable=unused-variable if hard_mem_limit != resource.RLIM_INFINITY: used_memory = this_process.memory_info().vms available_memory = min(hard_mem_limit - used_memory, available_memory) except ImportError: pass return available_memory def set_cpu_memory_limit(num_gigabytes): try: import resource # pylint: disable=import-outside-toplevel num_bytes = int(num_gigabytes * 2**30) _, hard_limit = resource.getrlimit(resource.RLIMIT_AS) if hard_limit != resource.RLIM_INFINITY: hard_limit = min(num_bytes, hard_limit) else: hard_limit = num_bytes resource.setrlimit(resource.RLIMIT_AS, (hard_limit, hard_limit)) except ImportError: pass def is_out_of_cpu_memory(exception): return ( isinstance(exception, RuntimeError) and len(exception.args) == 1 and "DefaultCPUAllocator: can't allocate memory" in exception.args[0] )
0
coqui_public_repos/STT-examples/net_framework
coqui_public_repos/STT-examples/net_framework/STTWPF/App.xaml
<Application x:Class="STTWPF.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:STTWPF" StartupUri="MainWindow.xaml"> <Application.Resources /> </Application>
0
coqui_public_repos/TTS/TTS/vocoder
coqui_public_repos/TTS/TTS/vocoder/utils/distribution.py
import math import numpy as np import torch import torch.nn.functional as F from torch.distributions.normal import Normal def gaussian_loss(y_hat, y, log_std_min=-7.0): assert y_hat.dim() == 3 assert y_hat.size(2) == 2 mean = y_hat[:, :, :1] log_std = torch.clamp(y_hat[:, :, 1:], min=log_std_min) # TODO: replace with pytorch dist log_probs = -0.5 * (-math.log(2.0 * math.pi) - 2.0 * log_std - torch.pow(y - mean, 2) * torch.exp((-2.0 * log_std))) return log_probs.squeeze().mean() def sample_from_gaussian(y_hat, log_std_min=-7.0, scale_factor=1.0): assert y_hat.size(2) == 2 mean = y_hat[:, :, :1] log_std = torch.clamp(y_hat[:, :, 1:], min=log_std_min) dist = Normal( mean, torch.exp(log_std), ) sample = dist.sample() sample = torch.clamp(torch.clamp(sample, min=-scale_factor), max=scale_factor) del dist return sample def log_sum_exp(x): """numerically stable log_sum_exp implementation that prevents overflow""" # TF ordering axis = len(x.size()) - 1 m, _ = torch.max(x, dim=axis) m2, _ = torch.max(x, dim=axis, keepdim=True) return m + torch.log(torch.sum(torch.exp(x - m2), dim=axis)) # It is adapted from https://github.com/r9y9/wavenet_vocoder/blob/master/wavenet_vocoder/mixture.py def discretized_mix_logistic_loss(y_hat, y, num_classes=65536, log_scale_min=None, reduce=True): if log_scale_min is None: log_scale_min = float(np.log(1e-14)) y_hat = y_hat.permute(0, 2, 1) assert y_hat.dim() == 3 assert y_hat.size(1) % 3 == 0 nr_mix = y_hat.size(1) // 3 # (B x T x C) y_hat = y_hat.transpose(1, 2) # unpack parameters. (B, T, num_mixtures) x 3 logit_probs = y_hat[:, :, :nr_mix] means = y_hat[:, :, nr_mix : 2 * nr_mix] log_scales = torch.clamp(y_hat[:, :, 2 * nr_mix : 3 * nr_mix], min=log_scale_min) # B x T x 1 -> B x T x num_mixtures y = y.expand_as(means) centered_y = y - means inv_stdv = torch.exp(-log_scales) plus_in = inv_stdv * (centered_y + 1.0 / (num_classes - 1)) cdf_plus = torch.sigmoid(plus_in) min_in = inv_stdv * (centered_y - 1.0 / (num_classes - 1)) cdf_min = torch.sigmoid(min_in) # log probability for edge case of 0 (before scaling) # equivalent: torch.log(F.sigmoid(plus_in)) log_cdf_plus = plus_in - F.softplus(plus_in) # log probability for edge case of 255 (before scaling) # equivalent: (1 - F.sigmoid(min_in)).log() log_one_minus_cdf_min = -F.softplus(min_in) # probability for all other cases cdf_delta = cdf_plus - cdf_min mid_in = inv_stdv * centered_y # log probability in the center of the bin, to be used in extreme cases # (not actually used in our code) log_pdf_mid = mid_in - log_scales - 2.0 * F.softplus(mid_in) # tf equivalent # log_probs = tf.where(x < -0.999, log_cdf_plus, # tf.where(x > 0.999, log_one_minus_cdf_min, # tf.where(cdf_delta > 1e-5, # tf.log(tf.maximum(cdf_delta, 1e-12)), # log_pdf_mid - np.log(127.5)))) # TODO: cdf_delta <= 1e-5 actually can happen. How can we choose the value # for num_classes=65536 case? 1e-7? not sure.. inner_inner_cond = (cdf_delta > 1e-5).float() inner_inner_out = inner_inner_cond * torch.log(torch.clamp(cdf_delta, min=1e-12)) + (1.0 - inner_inner_cond) * ( log_pdf_mid - np.log((num_classes - 1) / 2) ) inner_cond = (y > 0.999).float() inner_out = inner_cond * log_one_minus_cdf_min + (1.0 - inner_cond) * inner_inner_out cond = (y < -0.999).float() log_probs = cond * log_cdf_plus + (1.0 - cond) * inner_out log_probs = log_probs + F.log_softmax(logit_probs, -1) if reduce: return -torch.mean(log_sum_exp(log_probs)) return -log_sum_exp(log_probs).unsqueeze(-1) def sample_from_discretized_mix_logistic(y, log_scale_min=None): """ Sample from discretized mixture of logistic distributions Args: y (Tensor): :math:`[B, C, T]` log_scale_min (float): Log scale minimum value Returns: Tensor: sample in range of [-1, 1]. """ if log_scale_min is None: log_scale_min = float(np.log(1e-14)) assert y.size(1) % 3 == 0 nr_mix = y.size(1) // 3 # B x T x C y = y.transpose(1, 2) logit_probs = y[:, :, :nr_mix] # sample mixture indicator from softmax temp = logit_probs.data.new(logit_probs.size()).uniform_(1e-5, 1.0 - 1e-5) temp = logit_probs.data - torch.log(-torch.log(temp)) _, argmax = temp.max(dim=-1) # (B, T) -> (B, T, nr_mix) one_hot = to_one_hot(argmax, nr_mix) # select logistic parameters means = torch.sum(y[:, :, nr_mix : 2 * nr_mix] * one_hot, dim=-1) log_scales = torch.clamp(torch.sum(y[:, :, 2 * nr_mix : 3 * nr_mix] * one_hot, dim=-1), min=log_scale_min) # sample from logistic & clip to interval # we don't actually round to the nearest 8bit value when sampling u = means.data.new(means.size()).uniform_(1e-5, 1.0 - 1e-5) x = means + torch.exp(log_scales) * (torch.log(u) - torch.log(1.0 - u)) x = torch.clamp(torch.clamp(x, min=-1.0), max=1.0) return x def to_one_hot(tensor, n, fill_with=1.0): # we perform one hot encore with respect to the last axis one_hot = torch.FloatTensor(tensor.size() + (n,)).zero_().type_as(tensor) one_hot.scatter_(len(tensor.size()), tensor.unsqueeze(-1), fill_with) return one_hot
0
coqui_public_repos/Trainer
coqui_public_repos/Trainer/trainer/logger.py
import logging handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("")) logger = logging.getLogger("trainer") logger.addHandler(handler) logger.setLevel(logging.INFO) logger.propagate = False
0
coqui_public_repos/TTS/TTS/tts/utils/text
coqui_public_repos/TTS/TTS/tts/utils/text/english/abbreviations.py
import re # List of (regular expression, replacement) pairs for abbreviations in english: abbreviations_en = [ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1]) for x in [ ("mrs", "misess"), ("mr", "mister"), ("dr", "doctor"), ("st", "saint"), ("co", "company"), ("jr", "junior"), ("maj", "major"), ("gen", "general"), ("drs", "doctors"), ("rev", "reverend"), ("lt", "lieutenant"), ("hon", "honorable"), ("sgt", "sergeant"), ("capt", "captain"), ("esq", "esquire"), ("ltd", "limited"), ("col", "colonel"), ("ft", "fort"), ] ]
0
coqui_public_repos/STT/native_client
coqui_public_repos/STT/native_client/kenlm/CMakeLists.txt
cmake_minimum_required(VERSION 3.1) if (WIN32) set(Boost_USE_STATIC_LIBS OFF) # The auto-linking feature has problems with USE_STATIC_LIBS off, so we use # BOOST_ALL_NO_LIB to turn it off. # Several boost libraries headers aren't configured correctly if # USE_STATIC_LIBS is off, so we explicitly say they are dynamic with the # remaining definitions. add_definitions(-DBOOST_ALL_NO_LIB -DBOOST_PROGRAM_OPTIONS_DYN_LINK -DBOOST_IOSTREAMS_DYN_LINK -DBOOST_THREAD_DYN_LINK) endif( ) # Define a single cmake project project(kenlm) option(FORCE_STATIC "Build static executables" OFF) option(COMPILE_TESTS "Compile tests" OFF) option(ENABLE_PYTHON "Build Python bindings" OFF) # Eigen3 less than 3.1.0 has a race condition: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=466 find_package(Eigen3 3.1.0 CONFIG) include(CMakeDependentOption) cmake_dependent_option(ENABLE_INTERPOLATE "Build interpolation program (depends on Eigen3)" ON "EIGEN3_FOUND AND NOT WIN32" OFF) if (FORCE_STATIC) #presumably overkill, is there a better way? #http://cmake.3232098.n2.nabble.com/Howto-compile-static-executable-td5580269.html set(Boost_USE_STATIC_LIBS ON) set_property(GLOBAL PROPERTY LINK_SEARCH_START_STATIC ON) set_property(GLOBAL PROPERTY LINK_SEARCH_END_STATIC ON) set(BUILD_SHARED_LIBRARIES OFF) if (MSVC) set(flag_vars CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO) foreach(flag_var ${flag_vars}) if(${flag_var} MATCHES "/MD") string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") endif(${flag_var} MATCHES "/MD") endforeach(flag_var) else (MSVC) if (NOT CMAKE_C_COMPILER_ID MATCHES ".*Clang") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc -static-libstdc++ -static") endif () set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") endif () #Annoyingly the exectuables say "File not found" unless these are set set(CMAKE_EXE_LINK_DYNAMIC_C_FLAGS) set(CMAKE_EXE_LINK_DYNAMIC_CXX_FLAGS) set(CMAKE_SHARED_LIBRARY_C_FLAGS) set(CMAKE_SHARED_LIBRARY_CXX_FLAGS) set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS) set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS) endif () # Compile all executables into bin/ set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin) # Compile all libraries into lib/ set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib) if (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() if (COMPILE_TESTS) # Tell cmake that we want unit tests to be compiled include(CTest) enable_testing() endif() # Add our CMake helper functions include(cmake/KenLMFunctions.cmake) if(MSVC) set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} /w34716") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /w34716") endif() # And our helper modules list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules) # We need boost find_package(Boost 1.41.0 REQUIRED COMPONENTS program_options system thread unit_test_framework ) # Define where include files live include_directories(${Boost_INCLUDE_DIRS}) set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) # Process subdirectories add_subdirectory(util) add_subdirectory(lm) if(ENABLE_PYTHON) add_subdirectory(python) endif() # Install targets install(EXPORT kenlmTargets FILE kenlmTargets.cmake NAMESPACE kenlm:: DESTINATION share/kenlm/cmake ) foreach(SUBDIR IN ITEMS util util/double-conversion util/stream lm lm/builder lm/common lm/filter lm/interpolate) file(GLOB HEADERS ${CMAKE_CURRENT_LIST_DIR}/${SUBDIR}/*.h ${CMAKE_CURRENT_LIST_DIR}/${SUBDIR}/*.hh) install(FILES ${HEADERS} DESTINATION include/kenlm/${SUBDIR} COMPONENT headers) endforeach(SUBDIR) # Config include(CMakePackageConfigHelpers) # generate the config file that is includes the exports configure_package_config_file(${PROJECT_SOURCE_DIR}/cmake/kenlmConfig.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/kenlmConfig.cmake" INSTALL_DESTINATION share/kenlm/cmake NO_SET_AND_CHECK_MACRO NO_CHECK_REQUIRED_COMPONENTS_MACRO ) # install the configuration file install(FILES ${CMAKE_CURRENT_BINARY_DIR}/kenlmConfig.cmake DESTINATION share/kenlm/cmake )
0
coqui_public_repos/STT/native_client
coqui_public_repos/STT/native_client/javascript/stt.i
%module model %include "typemaps.i" %{ #define SWIG_FILE_WITH_INIT #include <string.h> #include <node_buffer.h> #include "coqui-stt.h" using namespace v8; using namespace node; %} // convert Node Buffer into a C ptr + length %typemap(in) (short* IN_ARRAY1, int DIM1) { Local<Object> bufferObj = SWIGV8_TO_OBJECT($input); char* bufferData = Buffer::Data(bufferObj); size_t bufferLength = Buffer::Length(bufferObj); if (bufferLength % 2 != 0) { SWIG_exception_fail(SWIG_ERROR, "Buffer length must be even. Make sure your input audio is 16-bits per sample."); } $1 = ($1_ltype)bufferData; $2 = ($2_ltype)(bufferLength / 2); } // apply to STT_FeedAudioContent and STT_SpeechToText %apply (short* IN_ARRAY1, int DIM1) {(const short* aBuffer, unsigned int aBufferSize)}; // apply the buffer typemap to STT_CreateModelFromBuffer %apply (short* IN_ARRAY1, int DIM1) {(const char *aModelBuffer, unsigned int aBufferSize)}; // make sure the string returned by SpeechToText is freed %typemap(newfree) char* "STT_FreeString($1);"; %newobject STT_SpeechToText; %newobject STT_IntermediateDecode; %newobject STT_IntermediateDecodeFlushBuffers; %newobject STT_FinishStream; %newobject STT_Version; %newobject STT_ErrorCodeToErrorMessage; // convert double pointer retval in CreateModel to an output %typemap(in, numinputs=0) ModelState **retval (ModelState *ret) { ret = NULL; $1 = &ret; } %typemap(argout) ModelState **retval { $result = SWIGV8_ARRAY_NEW(0); SWIGV8_AppendOutput($result, SWIG_From_int(result)); // owned by the application. NodeJS does not guarantee the finalizer will be called so applications must call FreeMetadata themselves. %append_output(SWIG_NewPointerObj(%as_voidptr(*$1), $*1_descriptor, 0)); } // convert double pointer retval in CreateStream to an output %typemap(in, numinputs=0) StreamingState **retval (StreamingState *ret) { ret = NULL; $1 = &ret; } %typemap(argout) StreamingState **retval { $result = SWIGV8_ARRAY_NEW(0); SWIGV8_AppendOutput($result, SWIG_From_int(result)); // not owned, STT_FinishStream deallocates StreamingState %append_output(SWIG_NewPointerObj(%as_voidptr(*$1), $*1_descriptor, 0)); } %nodefaultctor ModelState; %nodefaultdtor ModelState; %typemap(out) TokenMetadata* %{ $result = SWIGV8_ARRAY_NEW(0); for (int i = 0; i < arg1->num_tokens; ++i) { SWIGV8_AppendOutput($result, SWIG_NewPointerObj(SWIG_as_voidptr(&result[i]), SWIGTYPE_p_TokenMetadata, 0)); } %} %typemap(out) CandidateTranscript* %{ $result = SWIGV8_ARRAY_NEW(0); for (int i = 0; i < arg1->num_transcripts; ++i) { SWIGV8_AppendOutput($result, SWIG_NewPointerObj(SWIG_as_voidptr(&result[i]), SWIGTYPE_p_CandidateTranscript, 0)); } %} %ignore Metadata::num_transcripts; %ignore CandidateTranscript::num_tokens; %nodefaultctor Metadata; %nodefaultdtor Metadata; %nodefaultctor CandidateTranscript; %nodefaultdtor CandidateTranscript; %nodefaultctor TokenMetadata; %nodefaultdtor TokenMetadata; %rename ("%(strip:[STT_])s") ""; %include "../coqui-stt.h"
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/generic_tc_caching-linux-opt-base.tyml
taskId: ${taskcluster.taskId} provisionerId: ${taskcluster.docker.provisionerId} workerType: ${build.workerType} taskGroupId: ${taskcluster.taskGroupId} schedulerId: ${taskcluster.schedulerId} created: { $fromNow: '0 sec' } deadline: { $fromNow: '1 day' } expires: { $fromNow: '6 months' } scopes: - "index:insert-task:project.deepspeech.*" payload: maxRunTime: { $eval: to_int(build.maxRunTime) } image: ${build.docker_image} features: taskclusterProxy: true env: DEBIAN_FRONTEND: "noninteractive" command: - "/bin/bash" - "--login" - "-cxe" - $let: extraSystemSetup: { $eval: strip(str(build.system_setup)) } extraSystemConfig: { $eval: strip(str(build.system_config)) } taskIndexExpire: { $fromNow: '6 months' } in: > (apt-get -qq -y remove --purge ubuntu-advantage-tools || true) && apt-get -qq update && apt-get -qq -y install curl git sudo && ${extraSystemSetup}; cache_artifact=`curl -sSIL -o /dev/null -w "%{http_code}" ${build.cache.artifact_url}` && if [ "$cache_artifact" != "200" ]; then adduser --system --home ${system.homedir.linux} ${system.username} && cd ${system.homedir.linux}/ && mkdir -p /tmp/artifacts/ && chmod 777 /tmp/artifacts && echo -e "#!/bin/bash\nset -xe\n env && id && (git clone --quiet ${build.build_or_cache.repo} ~/${build.build_or_cache.dir}/ && cd ~/${build.build_or_cache.dir}/ && git checkout --quiet ${build.build_or_cache.sha})" > /tmp/clone.sh && chmod +x /tmp/clone.sh && sudo -H -u ${system.username} /bin/bash /tmp/clone.sh && ${extraSystemConfig} && sudo -H -u ${system.username} --preserve-env /bin/bash ${system.homedir.linux}/${build.build_or_cache.dir}/${build.scripts.setup} && sudo -H -u ${system.username} --preserve-env /bin/bash ${system.homedir.linux}/${build.build_or_cache.dir}/${build.scripts.build} && sudo -H -u ${system.username} /bin/bash ${system.homedir.linux}/${build.build_or_cache.dir}/${build.scripts.package} && sudo -H -u ${system.username} --preserve-env /bin/bash ${system.homedir.linux}/${build.build_or_cache.dir}/taskcluster/tc-update-index.sh ${taskIndexExpire} taskcluster ${build.cache.artifact_namespace} fi; artifacts: "public": type: "directory" path: "/tmp/artifacts/" expires: { $fromNow: '6 months' } metadata: name: ${build.metadata.name} description: ${build.metadata.description} owner: ${event.head.user.email} source: ${event.head.repo.url}
0
coqui_public_repos/STT-models/frisian/itml
coqui_public_repos/STT-models/frisian/itml/v0.1.1/MODEL_CARD.md
# Model card for Frisian STT Jump to section: - [Model details](#model-details) - [Intended use](#intended-use) - [Performance Factors](#performance-factors) - [Metrics](#metrics) - [Training data](#training-data) - [Evaluation data](#evaluation-data) - [Ethical considerations](#ethical-considerations) - [Caveats and recommendations](#caveats-and-recommendations) ## Model details - Person or organization developing model: Originally trained by [Francis Tyers](https://scholar.google.fr/citations?user=o5HSM6cAAAAJ) and the [Inclusive Technology for Marginalised Languages](https://itml.cl.indiana.edu/) group. - Model language: Frisian / Frysk / `fy-NL` - Model date: April 26, 2021 - Model type: `Speech-to-Text` - Model version: `v0.1.1` - Compatible with 🐸 STT version: `v0.9.3` - License: AGPL - Citation details: `@techreport{frisian-stt, author = {Tyers,Francis}, title = {Frisian STT 0.1}, institution = {Coqui}, address = {\url{https://github.com/coqui-ai/STT-models}} year = {2021}, month = {April}, number = {STT-CV6.1-FY_NL-0.1} }` - Where to send questions or comments about the model: You can leave an issue on [`STT-model` issues](https://github.com/coqui-ai/STT-models/issues), open a new discussion on [`STT-model` discussions](https://github.com/coqui-ai/STT-models/discussions), or chat with us on [Gitter](https://gitter.im/coqui-ai/). ## Intended use Speech-to-Text for the [Frisian Language](https://en.wikipedia.org/wiki/Frisian_language) on 16kHz, mono-channel audio. ## Performance Factors Factors relevant to Speech-to-Text performance include but are not limited to speaker demographics, recording quality, and background noise. Read more about STT performance factors [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). ## Metrics STT models are usually evaluated in terms of their transcription accuracy, deployment Real-Time Factor, and model size on disk. #### Transcription Accuracy The following Word Error Rates and Character Error Rates are reported on [omnilingo](https://tepozcatl.omnilingo.cc/cv/). |Test Corpus|WER|CER| |-----------|---|---| |Common Voice|74.0\%|26.5\%| #### Real-Time Factor Real-Time Factor (RTF) is defined as `proccesing-time / length-of-audio`. The exact real-time factor of an STT model will depend on the hardware setup, so you may experience a different RTF. Recorded average RTF on laptop CPU: `` #### Model Size `model.pbmm`: 181M `model.tflite`: 46M ### Approaches to uncertainty and variability Confidence scores and multiple paths from the decoding beam can be used to measure model uncertainty and provide multiple, variable transcripts for any processed audio. ## Training data This model was trained on Common Voice 6.1 train. ## Evaluation data The Model was evaluated on Common Voice 6.1 test. ## Ethical considerations Deploying a Speech-to-Text model into any production setting has ethical implications. You should consider these implications before use. ### Demographic Bias You should assume every machine learning model has demographic bias unless proven otherwise. For STT models, it is often the case that transcription accuracy is better for men than it is for women. If you are using this model in production, you should acknowledge this as a potential issue. ### Surveillance Speech-to-Text may be mis-used to invade the privacy of others by recording and mining information from private conversations. This kind of individual privacy is protected by law in may countries. You should not assume consent to record and analyze private speech. ## Caveats and recommendations Machine learning models (like this STT model) perform best on data that is similar to the data on which they were trained. Read about what to expect from an STT model with regard to your data [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). In most applications, it is recommended that you [train your own language model](https://stt.readthedocs.io/en/latest/LANGUAGE_MODEL.html) to improve transcription accuracy on your speech data.
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/script/decode.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_DECODE_H_ #define FST_SCRIPT_DECODE_H_ #include <memory> #include <string> #include <utility> #include <fst/encode.h> #include <fst/script/encodemapper-class.h> #include <fst/script/fst-class.h> namespace fst { namespace script { using DecodeArgs1 = std::pair<MutableFstClass *, const string &>; template <class Arc> void Decode(DecodeArgs1 *args) { MutableFst<Arc> *fst = std::get<0>(*args)->GetMutableFst<Arc>(); std::unique_ptr<EncodeMapper<Arc>> decoder( EncodeMapper<Arc>::Read(std::get<1>(*args), DECODE)); if (!decoder) { fst->SetProperties(kError, kError); return; } Decode(fst, *decoder); } using DecodeArgs2 = std::pair<MutableFstClass *, const EncodeMapperClass &>; template <class Arc> void Decode(DecodeArgs2 *args) { MutableFst<Arc> *fst = std::get<0>(*args)->GetMutableFst<Arc>(); const EncodeMapper<Arc> &encoder = *(std::get<1>(*args).GetEncodeMapper<Arc>()); Decode(fst, encoder); } void Decode(MutableFstClass *fst, const string &coder_fname); void Decode(MutableFstClass *fst, const EncodeMapperClass &encoder); } // namespace script } // namespace fst #endif // FST_SCRIPT_DECODE_H_
0
coqui_public_repos/STT
coqui_public_repos/STT/doc/Contributed-Examples.rst
User contributed examples ========================= There are also several user contributed examples available on a separate examples repository: `https://github.com/coqui-ai/STT-examples <https://github.com/coqui-ai/STT-examples>`_.
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/Makefile.am
SUBDIRS = include lib script bin test extensions
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/arc-arena.h
#ifndef FST_ARC_ARENA_H_ #define FST_ARC_ARENA_H_ #include <deque> #include <memory> #include <utility> #include <fst/fst.h> #include <fst/memory.h> #include <unordered_map> namespace fst { // ArcArena is used for fast allocation of contiguous arrays of arcs. // // To create an arc array: // for each state: // for each arc: // arena.PushArc(); // // Commits these arcs and returns pointer to them. // Arc *arcs = arena.GetArcs(); // // OR // // arena.DropArcs(); // Throws away current arcs, reuse the space. // // The arcs returned are guaranteed to be contiguous and the pointer returned // will never be invalidated until the arena is cleared for reuse. // // The contents of the arena can be released with a call to arena.Clear() after // which the arena will restart with an initial allocation capable of holding at // least all of the arcs requested in the last usage before Clear() making // subsequent uses of the Arena more efficient. // // The max_retained_size option can limit the amount of arc space requested on // Clear() to avoid excess growth from intermittent high usage. template <typename Arc> class ArcArena { public: explicit ArcArena(size_t block_size = 256, size_t max_retained_size = 1e6) : block_size_(block_size), max_retained_size_(max_retained_size) { blocks_.emplace_back(MakeSharedBlock(block_size_)); first_block_size_ = block_size_; total_size_ = block_size_; arcs_ = blocks_.back().get(); end_ = arcs_ + block_size_; next_ = arcs_; } ArcArena(const ArcArena& copy) : arcs_(copy.arcs_), next_(copy.next_), end_(copy.end_), block_size_(copy.block_size_), first_block_size_(copy.first_block_size_), total_size_(copy.total_size_), max_retained_size_(copy.max_retained_size_), blocks_(copy.blocks_) { NewBlock(block_size_); } void ReserveArcs(size_t n) { if (next_ + n < end_) return; NewBlock(n); } void PushArc(const Arc& arc) { if (next_ == end_) { size_t length = next_ - arcs_; NewBlock(length * 2); } *next_ = arc; ++next_; } const Arc* GetArcs() { const auto *arcs = arcs_; arcs_ = next_; return arcs; } void DropArcs() { next_ = arcs_; } size_t Size() { return total_size_; } void Clear() { blocks_.resize(1); if (total_size_ > first_block_size_) { first_block_size_ = std::min(max_retained_size_, total_size_); blocks_.back() = MakeSharedBlock(first_block_size_); } total_size_ = first_block_size_; arcs_ = blocks_.back().get(); end_ = arcs_ + first_block_size_; next_ = arcs_; } private: // Allocates a new block with capacity of at least n or block_size, // copying incomplete arc sequence from old block to new block. void NewBlock(size_t n) { const auto length = next_ - arcs_; const auto new_block_size = std::max(n, block_size_); total_size_ += new_block_size; blocks_.emplace_back(MakeSharedBlock(new_block_size)); std::copy(arcs_, next_, blocks_.back().get()); arcs_ = blocks_.back().get(); next_ = arcs_ + length; end_ = arcs_ + new_block_size; } std::shared_ptr<Arc> MakeSharedBlock(size_t size) { return std::shared_ptr<Arc>(new Arc[size], std::default_delete<Arc[]>()); } Arc *arcs_; Arc *next_; const Arc *end_; size_t block_size_; size_t first_block_size_; size_t total_size_; size_t max_retained_size_; std::list<std::shared_ptr<Arc>> blocks_; }; // ArcArenaStateStore uses a resusable ArcArena to store arc arrays and does not // require that the Expander call ReserveArcs first. // // TODO(tombagby): Make cache type configurable. // TODO(tombagby): Provide ThreadLocal/Concurrent configuration. template <class A> class ArcArenaStateStore { public: using Arc = A; using Weight = typename Arc::Weight; using StateId = typename Arc::StateId; ArcArenaStateStore() : arena_(64 * 1024) { } class State { public: Weight Final() const { return final_; } size_t NumInputEpsilons() const { return niepsilons_; } size_t NumOutputEpsilons() const { return noepsilons_; } size_t NumArcs() const { return narcs_; } const Arc &GetArc(size_t n) const { return arcs_[n]; } const Arc *Arcs() const { return arcs_; } int* MutableRefCount() const { return nullptr; } private: State(Weight weight, int32_t niepsilons, int32_t noepsilons, int32_t narcs, const Arc *arcs) : final_(std::move(weight)), niepsilons_(niepsilons), noepsilons_(noepsilons), narcs_(narcs), arcs_(arcs) {} Weight final_; size_t niepsilons_; size_t noepsilons_; size_t narcs_; const Arc *arcs_; friend class ArcArenaStateStore<Arc>; }; template <class Expander> State *FindOrExpand(Expander &expander, StateId state_id) { // NOLINT auto it = cache_.insert(std::pair<StateId, State*>(state_id, nullptr)); if (!it.second) return it.first->second; // Needs a new state. StateBuilder builder(&arena_); expander.Expand(state_id, &builder); const auto arcs = arena_.GetArcs(); size_t narcs = builder.narcs_; size_t niepsilons = 0; size_t noepsilons = 0; for (size_t i = 0; i < narcs; ++i) { if (arcs[i].ilabel == 0) ++niepsilons; if (arcs[i].olabel == 0) ++noepsilons; } states_.emplace_back( State(builder.final_, niepsilons, noepsilons, narcs, arcs)); // Places it in the cache. auto state = &states_.back(); it.first->second = state; return state; } State *Find(StateId state_id) const { auto it = cache_.find(state_id); return (it == cache_.end()) ? nullptr : it->second; } private: class StateBuilder { public: explicit StateBuilder(ArcArena<Arc>* arena) : arena_(arena), final_(Weight::Zero()), narcs_(0) {} void SetFinal(Weight weight) { final_ = std::move(weight); } void ReserveArcs(size_t n) { arena_->ReserveArcs(n); } void AddArc(const Arc &arc) { ++narcs_; arena_->PushArc(arc); } private: friend class ArcArenaStateStore<Arc>; ArcArena<Arc> *arena_; Weight final_; size_t narcs_; }; std::unordered_map<StateId, State *> cache_; std::deque<State> states_; ArcArena<Arc> arena_; }; } // namespace fst #endif // FST_ARC_ARENA_H_
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-nodejs_13x_multiarchpkg-win-tflite-opt.yml
build: template_file: test-win-opt-base.tyml dependencies: - "node-package-tflite" - "test-training_16k-linux-amd64-py36m-opt" test_model_task: "test-training_16k-linux-amd64-py36m-opt" system_setup: > ${system.sox_win} && ${nodejs.win.prep_13} args: tests_cmdline: "${system.homedir.win}/DeepSpeech/ds/taskcluster/tc-node_tflite-tests.sh 13.x 16k" metadata: name: "DeepSpeech Windows AMD64 TFLite NodeJS MultiArch Package 13.x tests" description: "Testing DeepSpeech for Windows/AMD64 on NodeJS MultiArch Package v13.x, TFLite only, optimized version"
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/extensions/ngram/bitmap-index.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_EXTENSIONS_NGRAM_BITMAP_INDEX_H_ #define FST_EXTENSIONS_NGRAM_BITMAP_INDEX_H_ #include <utility> #include <vector> #include <fst/compat.h> // This class is a bitstring storage class with an index that allows // seeking to the Nth set or clear bit in time O(Log(N)) where N is // the length of the bit vector. In addition, it allows counting set or // clear bits over ranges in constant time. // // This is accomplished by maintaining an "secondary" index of limited // size in bits that maintains a running count of the number of bits set // in each block of bitmap data. A block is defined as the number of // uint64_t values that can fit in the secondary index before an overflow // occurs. // // To handle overflows, a "primary" index containing a running count of // bits set in each block is created using the type uint64_t. namespace fst { class BitmapIndex { public: static size_t StorageSize(size_t size) { return ((size + kStorageBlockMask) >> kStorageLogBitSize); } BitmapIndex() : bits_(nullptr), size_(0) {} bool Get(size_t index) const { return (bits_[index >> kStorageLogBitSize] & (kOne << (index & kStorageBlockMask))) != 0; } static void Set(uint64_t* bits, size_t index) { bits[index >> kStorageLogBitSize] |= (kOne << (index & kStorageBlockMask)); } static void Clear(uint64_t* bits, size_t index) { bits[index >> kStorageLogBitSize] &= ~(kOne << (index & kStorageBlockMask)); } size_t Bits() const { return size_; } size_t ArraySize() const { return StorageSize(size_); } // Returns the number of one bits in the bitmap size_t GetOnesCount() const { return primary_index_[primary_index_size() - 1]; } // Returns the number of one bits in positions 0 to limit - 1. // REQUIRES: limit <= Bits() size_t Rank1(size_t end) const; // Returns the number of one bits in the range start to end - 1. // REQUIRES: limit <= Bits() size_t GetOnesCountInRange(size_t start, size_t end) const { return Rank1(end) - Rank1(start); } // Returns the number of zero bits in positions 0 to limit - 1. // REQUIRES: limit <= Bits() size_t Rank0(size_t end) const { return end - Rank1(end); } // Returns the number of zero bits in the range start to end - 1. // REQUIRES: limit <= Bits() size_t GetZeroesCountInRange(size_t start, size_t end) const { return end - start - GetOnesCountInRange(start, end); } // Return true if any bit between begin inclusive and end exclusive // is set. 0 <= begin <= end <= Bits() is required. // bool TestRange(size_t start, size_t end) const { return Rank1(end) > Rank1(start); } // Returns the offset to the nth set bit (zero based) // or Bits() if index >= number of ones size_t Select1(size_t bit_index) const; // Returns the offset to the nth clear bit (zero based) // or Bits() if index > number of size_t Select0(size_t bit_index) const; // Returns the offset of the nth and nth+1 clear bit (zero based), // equivalent to two calls to Select0, but more efficient. std::pair<size_t, size_t> Select0s(size_t bit_index) const; // Rebuilds from index for the associated Bitmap, should be called // whenever changes have been made to the Bitmap or else behavior // of the indexed bitmap methods will be undefined. void BuildIndex(const uint64_t* bits, size_t size); // the secondary index accumulates counts until it can possibly overflow // this constant computes the number of uint64_t units that can fit into // units the size of uint16_t. static const uint64_t kOne = 1; static const uint32_t kStorageBitSize = 64; static const uint32_t kStorageLogBitSize = 6; static const uint32_t kSecondaryBlockSize = ((1 << 16) - 1) >> kStorageLogBitSize; private: static const uint32_t kStorageBlockMask = kStorageBitSize - 1; // returns, from the index, the count of ones up to array_index size_t get_index_ones_count(size_t array_index) const; // because the indexes, both primary and secondary, contain a running // count of the population of one bits contained in [0,i), there is // no reason to have an element in the zeroth position as this value would // necessarily be zero. (The bits are indexed in a zero based way.) Thus // we don't store the 0th element in either index. Both of the following // functions, if greater than 0, must be decremented by one before retreiving // the value from the corresponding array. // returns the 1 + the block that contains the bitindex in question // the inverted version works the same but looks for zeros using an inverted // view of the index size_t find_primary_block(size_t bit_index) const; size_t find_inverted_primary_block(size_t bit_index) const; // similarly, the secondary index (which resets its count to zero at // the end of every kSecondaryBlockSize entries) does not store the element // at 0. Note that the rem_bit_index parameter is the number of bits // within the secondary block, after the bits accounted for by the primary // block have been removed (i.e. the remaining bits) And, because we // reset to zero with each new block, there is no need to store those // actual zeros. // returns 1 + the secondary block that contains the bitindex in question size_t find_secondary_block(size_t block, size_t rem_bit_index) const; size_t find_inverted_secondary_block(size_t block, size_t rem_bit_index) const; // We create a primary index based upon the number of secondary index // blocks. The primary index uses fields wide enough to accomodate any // index of the bitarray so cannot overflow // The primary index is the actual running // count of one bits set for all blocks (and, thus, all uint64_ts). size_t primary_index_size() const { return (ArraySize() + kSecondaryBlockSize - 1) / kSecondaryBlockSize; } const uint64_t* bits_; size_t size_; // The primary index contains the running popcount of all blocks // which means the nth value contains the popcounts of // [0,n*kSecondaryBlockSize], however, the 0th element is omitted. std::vector<uint32_t> primary_index_; // The secondary index contains the running popcount of the associated // bitmap. It is the same length (in units of uint16_t) as the // bitmap's map is in units of uint64_ts. std::vector<uint16_t> secondary_index_; }; } // end namespace fst #endif // FST_EXTENSIONS_NGRAM_BITMAP_INDEX_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/script/arciterator-class.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_ARCITERATOR_CLASS_H_ #define FST_SCRIPT_ARCITERATOR_CLASS_H_ #include <memory> #include <utility> #include <fst/fstlib.h> #include <fst/script/fst-class.h> // Scripting API support for ArcIterator. // // A call to Value() causes the underlying arc to be used to construct the // associated ArcClass. namespace fst { namespace script { // Non-mutable arc iterators. // Virtual interface implemented by each concrete ArcIteratorImpl<F>. class ArcIteratorImplBase { public: virtual bool Done() const = 0; virtual uint32_t Flags() const = 0; virtual void Next() = 0; virtual size_t Position() const = 0; virtual void Reset() = 0; virtual void Seek(size_t a) = 0; virtual void SetFlags(uint32_t flags, uint32_t mask) = 0; virtual ArcClass Value() const = 0; virtual ~ArcIteratorImplBase() {} }; // Templated implementation. template <class Arc> class ArcIteratorClassImpl : public ArcIteratorImplBase { public: explicit ArcIteratorClassImpl(const Fst<Arc> &fst, int64_t s) : aiter_(fst, s) {} bool Done() const final { return aiter_.Done(); } uint32_t Flags() const final { return aiter_.Flags(); } void Next() final { aiter_.Next(); } size_t Position() const final { return aiter_.Position(); } void Reset() final { aiter_.Reset(); } void Seek(size_t a) final { aiter_.Seek(a); } void SetFlags(uint32_t flags, uint32_t mask) final { aiter_.SetFlags(flags, mask); } // This is returned by value because it has not yet been constructed, and // is likely to participate in return-value optimization. ArcClass Value() const final { return ArcClass(aiter_.Value()); } ~ArcIteratorClassImpl() final {} private: ArcIterator<Fst<Arc>> aiter_; }; class ArcIteratorClass; using InitArcIteratorClassArgs = std::tuple<const FstClass &, int64_t, ArcIteratorClass *>; // Untemplated user-facing class holding a templated pimpl. class ArcIteratorClass { public: ArcIteratorClass(const FstClass &fst, int64_t s); template <class Arc> ArcIteratorClass(const Fst<Arc> &fst, int64_t s) : impl_(new ArcIteratorClassImpl<Arc>(fst, s)) {} bool Done() const { return impl_->Done(); } uint32_t Flags() const { return impl_->Flags(); } void Next() { impl_->Next(); } size_t Position() const { return impl_->Position(); } void Reset() { impl_->Reset(); } void Seek(size_t a) { impl_->Seek(a); } void SetFlags(uint32_t flags, uint32_t mask) { impl_->SetFlags(flags, mask); } ArcClass Value() const { return impl_->Value(); } template <class Arc> friend void InitArcIteratorClass(InitArcIteratorClassArgs *args); private: std::unique_ptr<ArcIteratorImplBase> impl_; }; template <class Arc> void InitArcIteratorClass(InitArcIteratorClassArgs *args) { const Fst<Arc> &fst = *(std::get<0>(*args).GetFst<Arc>()); std::get<2>(*args)->impl_.reset( new ArcIteratorClassImpl<Arc>(fst, std::get<1>(*args))); } // Mutable arc iterators. // Virtual interface implemented by each concrete MutableArcIteratorImpl<F>. class MutableArcIteratorImplBase : public ArcIteratorImplBase { public: virtual void SetValue(const ArcClass &) = 0; ~MutableArcIteratorImplBase() override {} }; // Templated implementation. template <class Arc> class MutableArcIteratorClassImpl : public MutableArcIteratorImplBase { public: explicit MutableArcIteratorClassImpl(MutableFst<Arc> *fst, int64_t s) : aiter_(fst, s) {} bool Done() const final { return aiter_.Done(); } uint32_t Flags() const final { return aiter_.Flags(); } void Next() final { aiter_.Next(); } size_t Position() const final { return aiter_.Position(); } void Reset() final { aiter_.Reset(); } void Seek(size_t a) final { aiter_.Seek(a); } void SetFlags(uint32_t flags, uint32_t mask) final { aiter_.SetFlags(flags, mask); } void SetValue(const Arc &arc) { aiter_.SetValue(arc); } void SetValue(const ArcClass &ac) final { aiter_.SetValue(ac.GetArc<Arc>()); } // This is returned by value because it has not yet been constructed, and // is likely to participate in return-value optimization. ArcClass Value() const final { return ArcClass(aiter_.Value()); } ~MutableArcIteratorClassImpl() override {} private: MutableArcIterator<MutableFst<Arc>> aiter_; }; class MutableArcIteratorClass; using InitMutableArcIteratorClassArgs = std::tuple<MutableFstClass *, int64_t, MutableArcIteratorClass *>; // Untemplated user-facing class holding a templated pimpl. class MutableArcIteratorClass { public: MutableArcIteratorClass(MutableFstClass *fst, int64_t s); template <class Arc> MutableArcIteratorClass(MutableFst<Arc> *fst, int64_t s) : impl_(new MutableArcIteratorClassImpl<Arc>(fst, s)) {} bool Done() const { return impl_->Done(); } uint32_t Flags() const { return impl_->Flags(); } void Next() { impl_->Next(); } size_t Position() const { return impl_->Position(); } void Reset() { impl_->Reset(); } void Seek(size_t a) { impl_->Seek(a); } void SetFlags(uint32_t flags, uint32_t mask) { impl_->SetFlags(flags, mask); } void SetValue(const ArcClass &ac) { impl_->SetValue(ac); } ArcClass Value() const { return impl_->Value(); } template <class Arc> friend void InitMutableArcIteratorClass( InitMutableArcIteratorClassArgs *args); private: std::unique_ptr<MutableArcIteratorImplBase> impl_; }; template <class Arc> void InitMutableArcIteratorClass(InitMutableArcIteratorClassArgs *args) { MutableFst<Arc> *fst = std::get<0>(*args)->GetMutableFst<Arc>(); std::get<2>(*args)->impl_.reset( new MutableArcIteratorClassImpl<Arc>(fst, std::get<1>(*args))); } } // namespace script } // namespace fst #endif // FST_SCRIPT_ARCITERATOR_CLASS_H_
0
coqui_public_repos/inference-engine/src
coqui_public_repos/inference-engine/src/ctcdecode/Makefile
.PHONY: bindings clean workspace_status.cc include ../definitions.mk NUM_PROCESSES ?= 1 DS_SWIG_DEP ?= ds-swig # Allow to disable the ds-swig dependency, useful for GitHub Actions move # ARM64 can't find the proper libm.so without this ifeq ($(TARGET),rpi3-armv8) LDFLAGS_NEEDED += $(RASPBIAN)/lib/aarch64-linux-gnu/libm.so.6 endif ifeq ($(OS),Darwin) GENERATE_DEBUG_SYMS := dsymutil temp_build/temp_build/coqui_stt_ctcdecoder/_swigwrapper.*.so else GENERATE_DEBUG_SYMS := endif ifeq ($(findstring _NT,$(OS)),_NT) ARCHIVE_EXT := lib else ARCHIVE_EXT := a endif FIRST_PARTY := first_party.$(ARCHIVE_EXT) THIRD_PARTY := third_party.$(ARCHIVE_EXT) all: bindings clean-keep-third-party: rm -rf dist temp_build coqui_stt_ctcdecoder.egg-info rm -f swigwrapper_wrap.cpp swigwrapper.py $(FIRST_PARTY) clean: clean-keep-third-party rm -f $(THIRD_PARTY) rm workspace_status.cc rm -fr bazel-out/ workspace_status.cc: mkdir -p bazel-out/ && \ ../bazel_workspace_status_cmd.sh > bazel-out/stable-status.txt && \ ../gen_workspace_status.sh > $@ # Enforce PATH here because swig calls from build_ext looses track of some # variables over several runs bindings: clean-keep-third-party workspace_status.cc $(DS_SWIG_DEP) python -m pip install --quiet $(PYTHON_PACKAGES) wheel==0.33.6 setuptools==45.0.0 DISTUTILS_USE_SDK=1 PATH=$(DS_SWIG_BIN_PATH):$(TOOLCHAIN_DIR):$$PATH SWIG_LIB="$(SWIG_LIB)" AS=$(AS) CC=$(CC) CXX=$(CXX) LD=$(LD) LIBEXE=$(LIBEXE) CFLAGS="$(CFLAGS) $(CXXFLAGS)" LDFLAGS="$(LDFLAGS_NEEDED)" $(PYTHON_PATH) $(NUMPY_INCLUDE) python ./setup.py build_ext --num_processes $(NUM_PROCESSES) $(PYTHON_PLATFORM_NAME) $(SETUP_FLAGS) find temp_build -type f -name "*.o" -delete DISTUTILS_USE_SDK=1 AS=$(AS) CC=$(CC) CXX=$(CXX) LD=$(LD) LIBEXE=$(LIBEXE) CFLAGS="$(CFLAGS) $(CXXFLAGS)" LDFLAGS="$(LDFLAGS_NEEDED)" $(PYTHON_PATH) $(NUMPY_INCLUDE) python ./setup.py bdist_wheel $(PYTHON_PLATFORM_NAME) $(SETUP_FLAGS) rm -rf temp_build bindings-debug: clean-keep-third-party workspace_status.cc $(DS_SWIG_DEP) python -m pip install --quiet $(PYTHON_PACKAGES) wheel==0.33.6 setuptools==45.0.0 DISTUTILS_USE_SDK=1 PATH=$(DS_SWIG_BIN_PATH):$(TOOLCHAIN_DIR):$$PATH SWIG_LIB="$(SWIG_LIB)" AS=$(AS) CC=$(CC) CXX=$(CXX) LD=$(LD) LIBEXE=$(LIBEXE) CFLAGS="$(CFLAGS) $(CXXFLAGS) -DDEBUG" LDFLAGS="$(LDFLAGS_NEEDED)" $(PYTHON_PATH) $(NUMPY_INCLUDE) python ./setup.py build_ext --debug --num_processes $(NUM_PROCESSES) $(PYTHON_PLATFORM_NAME) $(SETUP_FLAGS) $(GENERATE_DEBUG_SYMS) find temp_build -type f -name "*.o" -delete DISTUTILS_USE_SDK=1 AS=$(AS) CC=$(CC) CXX=$(CXX) LD=$(LD) LIBEXE=$(LIBEXE) CFLAGS="$(CFLAGS) $(CXXFLAGS) -DDEBUG" LDFLAGS="$(LDFLAGS_NEEDED)" $(PYTHON_PATH) $(NUMPY_INCLUDE) python ./setup.py bdist_wheel $(PYTHON_PLATFORM_NAME) $(SETUP_FLAGS) rm -rf temp_build
0
coqui_public_repos/STT-models/breton/itml
coqui_public_repos/STT-models/breton/itml/v0.1.1/alphabet.txt
' - a b c d e f g h i j k l m n o p q r s t u v w x y z â ê î ñ ô ù û ü
0
coqui_public_repos/inference-engine/src
coqui_public_repos/inference-engine/src/ctcdecode/output.h
#ifndef OUTPUT_H_ #define OUTPUT_H_ #include <vector> /* Struct for the beam search output, containing the tokens based on the vocabulary indices, and the timesteps * for each token in the beam search output */ struct Output { double confidence; std::vector<unsigned int> tokens; std::vector<unsigned int> timesteps; }; #endif // OUTPUT_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/isomorphic.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Function to test two FSTs are isomorphic, i.e., they are equal up to a state // and arc re-ordering. FSTs should be deterministic when viewed as // unweighted automata. #ifndef FST_ISOMORPHIC_H_ #define FST_ISOMORPHIC_H_ #include <algorithm> #include <list> #include <type_traits> #include <vector> #include <fst/log.h> #include <fst/fst.h> namespace fst { namespace internal { // Orders weights for equality checking. template <class Weight, typename std::enable_if< IsIdempotent<Weight>::value>::type * = nullptr> bool WeightCompare(const Weight &w1, const Weight &w2, float delta, bool *error) { return NaturalLess<Weight>()(w1, w2); } template <class Weight, typename std::enable_if< !IsIdempotent<Weight>::value>::type * = nullptr> bool WeightCompare(const Weight &w1, const Weight &w2, float delta, bool *error) { // No natural order; use hash. const auto q1 = w1.Quantize(delta); const auto q2 = w2.Quantize(delta); auto n1 = q1.Hash(); auto n2 = q2.Hash(); // Hash not unique; very unlikely to happen. if (n1 == n2 && q1 != q2) { VLOG(1) << "Isomorphic: Weight hash collision"; *error = true; } return n1 < n2; } template <class Arc> class Isomorphism { using StateId = typename Arc::StateId; public: Isomorphism(const Fst<Arc> &fst1, const Fst<Arc> &fst2, float delta) : fst1_(fst1.Copy()), fst2_(fst2.Copy()), delta_(delta), error_(false), comp_(delta, &error_) {} // Checks if input FSTs are isomorphic. bool IsIsomorphic() { if (fst1_->Start() == kNoStateId && fst2_->Start() == kNoStateId) { return true; } if (fst1_->Start() == kNoStateId || fst2_->Start() == kNoStateId) { return false; } PairState(fst1_->Start(), fst2_->Start()); while (!queue_.empty()) { const auto &pr = queue_.front(); if (!IsIsomorphicState(pr.first, pr.second)) return false; queue_.pop_front(); } return true; } bool Error() const { return error_; } private: // Orders arcs for equality checking. class ArcCompare { public: ArcCompare(float delta, bool *error) : delta_(delta), error_(error) {} bool operator()(const Arc &arc1, const Arc &arc2) const { if (arc1.ilabel < arc2.ilabel) return true; if (arc1.ilabel > arc2.ilabel) return false; if (arc1.olabel < arc2.olabel) return true; if (arc1.olabel > arc2.olabel) return false; return WeightCompare(arc1.weight, arc2.weight, delta_, error_); } private: float delta_; bool *error_; }; // Maintains state correspondences and queue. bool PairState(StateId s1, StateId s2) { if (state_pairs_.size() <= s1) state_pairs_.resize(s1 + 1, kNoStateId); if (state_pairs_[s1] == s2) { return true; // already seen this pair } else if (state_pairs_[s1] != kNoStateId) { return false; // s1 already paired with another s2 } state_pairs_[s1] = s2; queue_.push_back(std::make_pair(s1, s2)); return true; } // Checks if state pair is isomorphic bool IsIsomorphicState(StateId s1, StateId s2); std::unique_ptr<Fst<Arc>> fst1_; std::unique_ptr<Fst<Arc>> fst2_; float delta_; // Weight equality delta. std::vector<Arc> arcs1_; // For sorting arcs on FST1. std::vector<Arc> arcs2_; // For sorting arcs on FST2. std::vector<StateId> state_pairs_; // Maintains state correspondences. std::list<std::pair<StateId, StateId>> queue_; // Queue of state pairs. bool error_; // Error flag. ArcCompare comp_; }; template <class Arc> bool Isomorphism<Arc>::IsIsomorphicState(StateId s1, StateId s2) { if (!ApproxEqual(fst1_->Final(s1), fst2_->Final(s2), delta_)) return false; auto narcs1 = fst1_->NumArcs(s1); auto narcs2 = fst2_->NumArcs(s2); if (narcs1 != narcs2) return false; ArcIterator<Fst<Arc>> aiter1(*fst1_, s1); ArcIterator<Fst<Arc>> aiter2(*fst2_, s2); arcs1_.clear(); arcs1_.reserve(narcs1); arcs2_.clear(); arcs2_.reserve(narcs2); for (; !aiter1.Done(); aiter1.Next(), aiter2.Next()) { arcs1_.push_back(aiter1.Value()); arcs2_.push_back(aiter2.Value()); } std::sort(arcs1_.begin(), arcs1_.end(), comp_); std::sort(arcs2_.begin(), arcs2_.end(), comp_); for (size_t i = 0; i < arcs1_.size(); ++i) { const auto &arc1 = arcs1_[i]; const auto &arc2 = arcs2_[i]; if (arc1.ilabel != arc2.ilabel) return false; if (arc1.olabel != arc2.olabel) return false; if (!ApproxEqual(arc1.weight, arc2.weight, delta_)) return false; if (!PairState(arc1.nextstate, arc2.nextstate)) return false; if (i > 0) { // Checks for non-determinism. const auto &arc0 = arcs1_[i - 1]; if (arc1.ilabel == arc0.ilabel && arc1.olabel == arc0.olabel && ApproxEqual(arc1.weight, arc0.weight, delta_)) { VLOG(1) << "Isomorphic: Non-determinism as an unweighted automaton"; error_ = true; return false; } } } return true; } } // namespace internal // Tests if two FSTs have the same states and arcs up to a reordering. // Inputs should be non-deterministic when viewed as unweighted automata. template <class Arc> bool Isomorphic(const Fst<Arc> &fst1, const Fst<Arc> &fst2, float delta = kDelta) { internal::Isomorphism<Arc> iso(fst1, fst2, delta); bool result = iso.IsIsomorphic(); if (iso.Error()) { FSTERROR() << "Isomorphic: Cannot determine if inputs are isomorphic"; return false; } else { return result; } } } // namespace fst #endif // FST_ISOMORPHIC_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/extensions
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/extensions/pdt/info.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Prints information about a PDT. #ifndef FST_EXTENSIONS_PDT_INFO_H_ #define FST_EXTENSIONS_PDT_INFO_H_ #include <unordered_map> #include <unordered_set> #include <vector> #include <fst/extensions/pdt/pdt.h> #include <fst/fst.h> namespace fst { // Compute various information about PDTs. template <class Arc> class PdtInfo { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; PdtInfo(const Fst<Arc> &fst, const std::vector<std::pair<Label, Label>> &parents); const string &FstType() const { return fst_type_; } const string &ArcType() const { return Arc::Type(); } int64 NumStates() const { return nstates_; } int64 NumArcs() const { return narcs_; } int64 NumOpenParens() const { return nopen_parens_; } int64 NumCloseParens() const { return nclose_parens_; } int64 NumUniqueOpenParens() const { return nuniq_open_parens_; } int64 NumUniqueCloseParens() const { return nuniq_close_parens_; } int64 NumOpenParenStates() const { return nopen_paren_states_; } int64 NumCloseParenStates() const { return nclose_paren_states_; } private: string fst_type_; int64 nstates_; int64 narcs_; int64 nopen_parens_; int64 nclose_parens_; int64 nuniq_open_parens_; int64 nuniq_close_parens_; int64 nopen_paren_states_; int64 nclose_paren_states_; }; template <class Arc> PdtInfo<Arc>::PdtInfo( const Fst<Arc> &fst, const std::vector<std::pair<typename Arc::Label, typename Arc::Label>> &parens) : fst_type_(fst.Type()), nstates_(0), narcs_(0), nopen_parens_(0), nclose_parens_(0), nuniq_open_parens_(0), nuniq_close_parens_(0), nopen_paren_states_(0), nclose_paren_states_(0) { std::unordered_map<Label, size_t> paren_map; std::unordered_set<Label> paren_set; std::unordered_set<StateId> open_paren_state_set; std::unordered_set<StateId> close_paren_state_set; for (size_t i = 0; i < parens.size(); ++i) { const auto &pair = parens[i]; paren_map[pair.first] = i; paren_map[pair.second] = i; } for (StateIterator<Fst<Arc>> siter(fst); !siter.Done(); siter.Next()) { ++nstates_; const auto s = siter.Value(); for (ArcIterator<Fst<Arc>> aiter(fst, s); !aiter.Done(); aiter.Next()) { const auto &arc = aiter.Value(); ++narcs_; const auto it = paren_map.find(arc.ilabel); if (it != paren_map.end()) { const auto open_paren = parens[it->second].first; const auto close_paren = parens[it->second].second; if (arc.ilabel == open_paren) { ++nopen_parens_; if (!paren_set.count(open_paren)) { ++nuniq_open_parens_; paren_set.insert(open_paren); } if (!open_paren_state_set.count(arc.nextstate)) { ++nopen_paren_states_; open_paren_state_set.insert(arc.nextstate); } } else { ++nclose_parens_; if (!paren_set.count(close_paren)) { ++nuniq_close_parens_; paren_set.insert(close_paren); } if (!close_paren_state_set.count(s)) { ++nclose_paren_states_; close_paren_state_set.insert(s); } } } } } } template <class Arc> void PrintPdtInfo(const PdtInfo<Arc> &info) { const auto old = std::cout.setf(std::ios::left); std::cout.width(50); std::cout << "fst type" << info.FstType() << std::endl; std::cout.width(50); std::cout << "arc type" << info.ArcType() << std::endl; std::cout.width(50); std::cout << "# of states" << info.NumStates() << std::endl; std::cout.width(50); std::cout << "# of arcs" << info.NumArcs() << std::endl; std::cout.width(50); std::cout << "# of open parentheses" << info.NumOpenParens() << std::endl; std::cout.width(50); std::cout << "# of close parentheses" << info.NumCloseParens() << std::endl; std::cout.width(50); std::cout << "# of unique open parentheses" << info.NumUniqueOpenParens() << std::endl; std::cout.width(50); std::cout << "# of unique close parentheses" << info.NumUniqueCloseParens() << std::endl; std::cout.width(50); std::cout << "# of open parenthesis dest. states" << info.NumOpenParenStates() << std::endl; std::cout.width(50); std::cout << "# of close parenthesis source states" << info.NumCloseParenStates() << std::endl; std::cout.setf(old); } } // namespace fst #endif // FST_EXTENSIONS_PDT_INFO_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions/lookahead/olabel_lookahead-fst.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/fst.h> #include <fst/matcher-fst.h> namespace fst { static FstRegisterer<StdOLabelLookAheadFst> OLabelLookAheadFst_StdArc_registerer; static FstRegisterer<MatcherFst< ConstFst<LogArc>, LabelLookAheadMatcher<SortedMatcher<ConstFst<LogArc>>, olabel_lookahead_flags, FastLogAccumulator<LogArc>>, olabel_lookahead_fst_type, LabelLookAheadRelabeler<LogArc>>> OLabelLookAheadFst_LogArc_registerer; static FstRegisterer<MatcherFst< ConstFst<Log64Arc>, LabelLookAheadMatcher<SortedMatcher<ConstFst<Log64Arc>>, olabel_lookahead_flags, FastLogAccumulator<Log64Arc>>, olabel_lookahead_fst_type, LabelLookAheadRelabeler<Log64Arc>>> OLabelLookAheadFst_Log64Arc_registerer; } // namespace fst
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/weight.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // General weight set and associated semiring operation definitions. #ifndef FST_WEIGHT_H_ #define FST_WEIGHT_H_ #include <cctype> #include <cmath> #include <iostream> #include <sstream> #include <type_traits> #include <utility> #include <fst/compat.h> #include <fst/log.h> #include <fst/util.h> DECLARE_string(fst_weight_parentheses); DECLARE_string(fst_weight_separator); namespace fst { // A semiring is specified by two binary operations Plus and Times and two // designated elements Zero and One with the following properties: // // Plus: associative, commutative, and has Zero as its identity. // // Times: associative and has identity One, distributes w.r.t. Plus, and // has Zero as an annihilator: // Times(Zero(), a) == Times(a, Zero()) = Zero(). // // A left semiring distributes on the left; a right semiring is similarly // defined. // // A Weight class must have binary functions Plus and Times and static member // functions Zero() and One() and these must form (at least) a left or right // semiring. // // In addition, the following should be defined for a Weight: // // Member: predicate on set membership. // // NoWeight: static member function that returns an element that is // not a set member; used to signal an error. // // >>: reads textual representation of a weight. // // <<: prints textual representation of a weight. // // Read(istream &istrm): reads binary representation of a weight. // // Write(ostream &ostrm): writes binary representation of a weight. // // Hash: maps weight to size_t. // // ApproxEqual: approximate equality (for inexact weights) // // Quantize: quantizes w.r.t delta (for inexact weights) // // Divide: for all a, b, c s.t. Times(a, b) == c // // --> b' = Divide(c, a, DIVIDE_LEFT) if a left semiring, b'.Member() // and Times(a, b') == c // --> a' = Divide(c, b, DIVIDE_RIGHT) if a right semiring, a'.Member() // and Times(a', b) == c // --> b' = Divide(c, a) = Divide(c, a, DIVIDE_ANY) = // Divide(c, a, DIVIDE_LEFT) = Divide(c, a, DIVIDE_RIGHT) if a // commutative semiring, b'.Member() and Times(a, b') = Times(b', a) = c // // ReverseWeight: the type of the corresponding reverse weight. // // Typically the same type as Weight for a (both left and right) semiring. // For the left string semiring, it is the right string semiring. // // Reverse: a mapping from Weight to ReverseWeight s.t. // // --> Reverse(Reverse(a)) = a // --> Reverse(Plus(a, b)) = Plus(Reverse(a), Reverse(b)) // --> Reverse(Times(a, b)) = Times(Reverse(b), Reverse(a)) // Typically the identity mapping in a (both left and right) semiring. // In the left string semiring, it maps to the reverse string in the right // string semiring. // // Properties: specifies additional properties that hold: // LeftSemiring: indicates weights form a left semiring. // RightSemiring: indicates weights form a right semiring. // Commutative: for all a,b: Times(a,b) == Times(b,a) // Idempotent: for all a: Plus(a, a) == a. // Path: for all a, b: Plus(a, b) == a or Plus(a, b) == b. // CONSTANT DEFINITIONS // A representable float near .001. constexpr float kDelta = 1.0F / 1024.0F; // For all a, b, c: Times(c, Plus(a, b)) = Plus(Times(c, a), Times(c, b)). constexpr uint64 kLeftSemiring = 0x0000000000000001ULL; // For all a, b, c: Times(Plus(a, b), c) = Plus(Times(a, c), Times(b, c)). constexpr uint64 kRightSemiring = 0x0000000000000002ULL; constexpr uint64 kSemiring = kLeftSemiring | kRightSemiring; // For all a, b: Times(a, b) = Times(b, a). constexpr uint64 kCommutative = 0x0000000000000004ULL; // For all a: Plus(a, a) = a. constexpr uint64 kIdempotent = 0x0000000000000008ULL; // For all a, b: Plus(a, b) = a or Plus(a, b) = b. constexpr uint64 kPath = 0x0000000000000010ULL; // For random weight generation: default number of distinct weights. // This is also used for a few other weight generation defaults. constexpr size_t kNumRandomWeights = 5; // Weight property boolean constants needed for SFINAE. template <class W> using IsIdempotent = std::integral_constant<bool, (W::Properties() & kIdempotent) != 0>; template <class W> using IsPath = std::integral_constant<bool, (W::Properties() & kPath) != 0>; // Determines direction of division. enum DivideType { DIVIDE_LEFT, // left division DIVIDE_RIGHT, // right division DIVIDE_ANY }; // division in a commutative semiring // NATURAL ORDER // // By definition: // // a <= b iff a + b = a // // The natural order is a negative partial order iff the semiring is // idempotent. It is trivially monotonic for plus. It is left // (resp. right) monotonic for times iff the semiring is left // (resp. right) distributive. It is a total order iff the semiring // has the path property. // // For more information, see: // // Mohri, M. 2002. Semiring framework and algorithms for shortest-distance // problems, Journal of Automata, Languages and // Combinatorics 7(3): 321-350, 2002. // // We define the strict version of this order below. // Declares the template with a second parameter determining whether or not it // can actually be constructed. template <class W, class IdempotentType = void> class NaturalLess; // Variant for idempotent weights. template <class W> class NaturalLess<W, typename std::enable_if<IsIdempotent<W>::value>::type> { public: using Weight = W; NaturalLess() {} bool operator()(const Weight &w1, const Weight &w2) const { return w1 != w2 && Plus(w1, w2) == w1; } }; // Non-constructible variant for non-idempotent weights. template <class W> class NaturalLess<W, typename std::enable_if<!IsIdempotent<W>::value>::type> { public: using Weight = W; // TODO(kbg): Trace down anywhere this is being instantiated, then add a // static_assert to prevent this from being instantiated. NaturalLess() { FSTERROR() << "NaturalLess: Weight type is not idempotent: " << W::Type(); } bool operator()(const Weight &, const Weight &) const { return false; } }; // Power is the iterated product for arbitrary semirings such that Power(w, 0) // is One() for the semiring, and Power(w, n) = Times(Power(w, n - 1), w). template <class Weight> Weight Power(const Weight &weight, size_t n) { auto result = Weight::One(); for (size_t i = 0; i < n; ++i) result = Times(result, weight); return result; } // Simple default adder class. Specializations might be more complex. template <class Weight> class Adder { public: explicit Adder(Weight w = Weight::Zero()) : sum_(w) { } Weight Add(const Weight &w) { sum_ = Plus(sum_, w); return sum_; } Weight Sum() { return sum_; } void Reset(Weight w = Weight::Zero()) { sum_ = w; } private: Weight sum_; }; // General weight converter: raises error. template <class W1, class W2> struct WeightConvert { W2 operator()(W1 w1) const { FSTERROR() << "WeightConvert: Can't convert weight from \"" << W1::Type() << "\" to \"" << W2::Type(); return W2::NoWeight(); } }; // Specialized weight converter to self. template <class W> struct WeightConvert<W, W> { W operator()(W weight) const { return weight; } }; // General random weight generator: raises error. template <class W> struct WeightGenerate { W operator()() const { FSTERROR() << "WeightGenerate: No random generator for " << W::Type(); return W::NoWeight(); } }; namespace internal { class CompositeWeightIO { public: CompositeWeightIO(); CompositeWeightIO(char separator, std::pair<char, char> parentheses); std::pair<char, char> parentheses() const { return {open_paren_, close_paren_}; } char separator() const { return separator_; } bool error() const { return error_; } protected: const char separator_; const char open_paren_; const char close_paren_; private: bool error_; }; } // namespace internal // Helper class for writing textual composite weights. class CompositeWeightWriter : public internal::CompositeWeightIO { public: // Uses configuration from flags (FLAGS_fst_weight_separator, // FLAGS_fst_weight_parentheses). explicit CompositeWeightWriter(std::ostream &ostrm); // parentheses defines the opening and closing parenthesis characters. // Set parentheses = {0, 0} to disable writing parenthesis. CompositeWeightWriter(std::ostream &ostrm, char separator, std::pair<char, char> parentheses); CompositeWeightWriter(const CompositeWeightWriter &) = delete; CompositeWeightWriter &operator=(const CompositeWeightWriter &) = delete; // Writes open parenthesis to a stream if option selected. void WriteBegin(); // Writes element to a stream. template <class T> void WriteElement(const T &comp) { if (i_++ > 0) ostrm_ << separator_; ostrm_ << comp; } // Writes close parenthesis to a stream if option selected. void WriteEnd(); private: std::ostream &ostrm_; int i_ = 0; // Element position. }; // Helper class for reading textual composite weights. Elements are separated by // a separator character. There must be at least one element per textual // representation. Parentheses characters should be set if the composite // weights themselves contain composite weights to ensure proper parsing. class CompositeWeightReader : public internal::CompositeWeightIO { public: // Uses configuration from flags (FLAGS_fst_weight_separator, // FLAGS_fst_weight_parentheses). explicit CompositeWeightReader(std::istream &istrm); // parentheses defines the opening and closing parenthesis characters. // Set parentheses = {0, 0} to disable reading parenthesis. CompositeWeightReader(std::istream &istrm, char separator, std::pair<char, char> parentheses); CompositeWeightReader(const CompositeWeightReader &) = delete; CompositeWeightReader &operator=(const CompositeWeightReader &) = delete; // Reads open parenthesis from a stream if option selected. void ReadBegin(); // Reads element from a stream. The second argument, when true, indicates that // this will be the last element (allowing more forgiving formatting of the // last element). Returns false when last element is read. template <class T> bool ReadElement(T *comp, bool last = false); // Finalizes reading. void ReadEnd(); private: std::istream &istrm_; // Input stream. int c_ = 0; // Last character read, or EOF. int depth_ = 0; // Weight parentheses depth. }; template <class T> inline bool CompositeWeightReader::ReadElement(T *comp, bool last) { string s; const bool has_parens = open_paren_ != 0; while ((c_ != std::istream::traits_type::eof()) && !std::isspace(c_) && (c_ != separator_ || depth_ > 1 || last) && (c_ != close_paren_ || depth_ != 1)) { s += c_; // If parentheses encountered before separator, they must be matched. if (has_parens && c_ == open_paren_) { ++depth_; } else if (has_parens && c_ == close_paren_) { // Failure on unmatched parentheses. if (depth_ == 0) { FSTERROR() << "CompositeWeightReader: Unmatched close paren: " << "Is the fst_weight_parentheses flag set correctly?"; istrm_.clear(std::ios::badbit); return false; } --depth_; } c_ = istrm_.get(); } if (s.empty()) { FSTERROR() << "CompositeWeightReader: Empty element: " << "Is the fst_weight_parentheses flag set correctly?"; istrm_.clear(std::ios::badbit); return false; } std::istringstream istrm(s); istrm >> *comp; // Skips separator/close parenthesis. if (c_ != std::istream::traits_type::eof() && !std::isspace(c_)) { c_ = istrm_.get(); } const bool is_eof = c_ == std::istream::traits_type::eof(); // Clears fail bit if just EOF. if (is_eof && !istrm_.bad()) istrm_.clear(std::ios::eofbit); return !is_eof && !std::isspace(c_); } } // namespace fst #endif // FST_WEIGHT_H_
0
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external/rapidjson/memorystream.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef CEREAL_RAPIDJSON_MEMORYSTREAM_H_ #define CEREAL_RAPIDJSON_MEMORYSTREAM_H_ #include "stream.h" #ifdef __clang__ CEREAL_RAPIDJSON_DIAG_PUSH CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) CEREAL_RAPIDJSON_DIAG_OFF(missing-noreturn) #endif CEREAL_RAPIDJSON_NAMESPACE_BEGIN //! Represents an in-memory input byte stream. /*! This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream. It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file. Differences between MemoryStream and StringStream: 1. StringStream has encoding but MemoryStream is a byte stream. 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source. 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4(). \note implements Stream concept */ struct MemoryStream { typedef char Ch; // byte MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {} Ch Peek() const { return CEREAL_RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_; } Ch Take() { return CEREAL_RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_++; } size_t Tell() const { return static_cast<size_t>(src_ - begin_); } Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } // For encoding detection only. const Ch* Peek4() const { return Tell() + 4 <= size_ ? src_ : 0; } const Ch* src_; //!< Current read position. const Ch* begin_; //!< Original head of the string. const Ch* end_; //!< End of stream. size_t size_; //!< Size of the stream. }; CEREAL_RAPIDJSON_NAMESPACE_END #ifdef __clang__ CEREAL_RAPIDJSON_DIAG_POP #endif #endif // CEREAL_RAPIDJSON_MEMORYBUFFER_H_
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-cpp_metadata_tflite_valgrind-linux-amd64-dbg.yml
build: template_file: test-linux-opt-base.tyml dependencies: - "linux-amd64-tflite-dbg" - "test-training_16k-linux-amd64-py36m-opt" test_model_task: "test-training_16k-linux-amd64-py36m-opt" docker_image: "ubuntu:20.04" system_setup: > ${valgrind.packages_bionic.apt} args: tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-valgrind-cpp_tflite.sh --metadata" workerType: "${docker.dsHighMemTests}" metadata: name: "DeepSpeech Linux AMD64 valgrind C++ TFLite metadata tests" description: "Testing metadata DeepSpeech valgrind C++ TFLite for Linux/AMD64"
0
coqui_public_repos/STT-models/thai/itml
coqui_public_repos/STT-models/thai/itml/v0.1.0/alphabet.txt
ก ข ค ฆ ง จ ฉ ช ซ ญ ฎ ฏ ฐ ฑ ฒ ณ ด ต ถ ท ธ น บ ป ผ ฝ พ ฟ ภ ม ย ร ฤ ล ว ศ ษ ส ห ฬ อ ฮ ะ ั า ำ ิ ี ึ ื ุ ู เ แ โ ใ ไ ๅ ็ ่ ้ ๊ ๋ ์ ํ ๎ ◌
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions/lookahead/olabel_lookahead-fst.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/fst.h> #include <fst/matcher-fst.h> namespace fst { static FstRegisterer<StdOLabelLookAheadFst> OLabelLookAheadFst_StdArc_registerer; static FstRegisterer<MatcherFst< ConstFst<LogArc>, LabelLookAheadMatcher<SortedMatcher<ConstFst<LogArc>>, olabel_lookahead_flags, FastLogAccumulator<LogArc>>, olabel_lookahead_fst_type, LabelLookAheadRelabeler<LogArc>>> OLabelLookAheadFst_LogArc_registerer; static FstRegisterer<MatcherFst< ConstFst<Log64Arc>, LabelLookAheadMatcher<SortedMatcher<ConstFst<Log64Arc>>, olabel_lookahead_flags, FastLogAccumulator<Log64Arc>>, olabel_lookahead_fst_type, LabelLookAheadRelabeler<Log64Arc>>> OLabelLookAheadFst_Log64Arc_registerer; } // namespace fst
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/bin/fstintersect.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/flags.h> DEFINE_string(compose_filter, "auto", "Composition filter, one of: \"alt_sequence\", \"auto\", " "\"match\", \"null\", \"sequence\", \"trivial\""); DEFINE_bool(connect, true, "Trim output"); int fstintersect_main(int argc, char **argv); int main(int argc, char **argv) { return fstintersect_main(argc, argv); }
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/script/topsort.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_TOPSORT_H_ #define FST_SCRIPT_TOPSORT_H_ #include <fst/topsort.h> #include <fst/script/arg-packs.h> #include <fst/script/fst-class.h> namespace fst { namespace script { using TopSortArgs = WithReturnValue<bool, MutableFstClass *>; template <class Arc> void TopSort(TopSortArgs *args) { args->retval = TopSort(args->args->GetMutableFst<Arc>()); } bool TopSort(MutableFstClass *fst); } // namespace script } // namespace fst #endif // FST_SCRIPT_TOPSORT_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/script/arcsort.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_ARCSORT_H_ #define FST_SCRIPT_ARCSORT_H_ #include <utility> #include <fst/arcsort.h> #include <fst/script/fst-class.h> namespace fst { namespace script { enum ArcSortType { ILABEL_SORT, OLABEL_SORT }; using ArcSortArgs = std::pair<MutableFstClass *, ArcSortType>; template <class Arc> void ArcSort(ArcSortArgs *args) { MutableFst<Arc> *fst = std::get<0>(*args)->GetMutableFst<Arc>(); switch (std::get<1>(*args)) { case ILABEL_SORT: { const ILabelCompare<Arc> icomp; ArcSort(fst, icomp); return; } case OLABEL_SORT: { const OLabelCompare<Arc> ocomp; ArcSort(fst, ocomp); return; } } } void ArcSort(MutableFstClass *ofst, ArcSortType); } // namespace script } // namespace fst #endif // FST_SCRIPT_ARCSORT_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/script/connect.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/script/fst-class.h> #include <fst/script/connect.h> #include <fst/script/script-impl.h> namespace fst { namespace script { void Connect(MutableFstClass *fst) { Apply<Operation<MutableFstClass>>("Connect", fst->ArcType(), fst); } REGISTER_FST_OPERATION(Connect, StdArc, MutableFstClass); REGISTER_FST_OPERATION(Connect, LogArc, MutableFstClass); REGISTER_FST_OPERATION(Connect, Log64Arc, MutableFstClass); } // namespace script } // namespace fst
0
coqui_public_repos/STT-examples
coqui_public_repos/STT-examples/web_microphone_websocket/server.js
const http = require('http'); const socketIO = require('socket.io'); const STT = require('stt'); const VAD = require('node-vad'); let STT_MODEL = __dirname + '/coqui-stt-models'; // path to stt english model directory let SILENCE_THRESHOLD = 200; // how many milliseconds of inactivity before processing the audio const SERVER_PORT = 4000; // websocket server port // const VAD_MODE = VAD.Mode.NORMAL; // const VAD_MODE = VAD.Mode.LOW_BITRATE; // const VAD_MODE = VAD.Mode.AGGRESSIVE; const VAD_MODE = VAD.Mode.VERY_AGGRESSIVE; const vad = new VAD(VAD_MODE); function createModel(modelDir) { let modelPath = modelDir + '.tflite'; let scorerPath = modelDir + '.scorer'; let model = new STT.Model(modelPath); model.enableExternalScorer(scorerPath); return model; } let englishModel = createModel(STT_MODEL); let modelStream; let recordedChunks = 0; let silenceStart = null; let recordedAudioLength = 0; let endTimeout = null; let silenceBuffers = []; function processAudioStream(data, callback) { vad.processAudio(data, 16000).then((res) => { switch (res) { case VAD.Event.ERROR: console.log("VAD ERROR"); break; case VAD.Event.NOISE: console.log("VAD NOISE"); break; case VAD.Event.SILENCE: processSilence(data, callback); break; case VAD.Event.VOICE: processVoice(data); break; default: console.log('default', res); } }); // timeout after 1s of inactivity clearTimeout(endTimeout); endTimeout = setTimeout(function() { console.log('timeout'); resetAudioStream(); },1000); } function endAudioStream(callback) { console.log('[end]'); let results = intermediateDecode(); if (results) { if (callback) { callback(results); } } } function resetAudioStream() { clearTimeout(endTimeout); console.log('[reset]'); intermediateDecode(); // ignore results recordedChunks = 0; silenceStart = null; } function processSilence(data, callback) { if (recordedChunks > 0) { // recording is on process.stdout.write('-'); // silence detected while recording feedAudioContent(data); if (silenceStart === null) { silenceStart = new Date().getTime(); } else { let now = new Date().getTime(); if (now - silenceStart > SILENCE_THRESHOLD) { silenceStart = null; console.log('[end]'); let results = intermediateDecode(); if (results) { if (callback) { callback(results); } } } } } else { process.stdout.write('.'); // silence detected while not recording bufferSilence(data); } } function bufferSilence(data) { // VAD has a tendency to cut the first bit of audio data from the start of a recording // so keep a buffer of that first bit of audio and in addBufferedSilence() reattach it to the beginning of the recording silenceBuffers.push(data); if (silenceBuffers.length >= 3) { silenceBuffers.shift(); } } function addBufferedSilence(data) { let audioBuffer; if (silenceBuffers.length) { silenceBuffers.push(data); let length = 0; silenceBuffers.forEach(function (buf) { length += buf.length; }); audioBuffer = Buffer.concat(silenceBuffers, length); silenceBuffers = []; } else audioBuffer = data; return audioBuffer; } function processVoice(data) { silenceStart = null; if (recordedChunks === 0) { console.log(''); process.stdout.write('[start]'); // recording started } else { process.stdout.write('='); // still recording } recordedChunks++; data = addBufferedSilence(data); feedAudioContent(data); } function createStream() { modelStream = englishModel.createStream(); recordedChunks = 0; recordedAudioLength = 0; } function finishStream() { if (modelStream) { let start = new Date(); let text = modelStream.finishStream(); if (text) { console.log(''); console.log('Recognized Text:', text); let recogTime = new Date().getTime() - start.getTime(); return { text, recogTime, audioLength: Math.round(recordedAudioLength) }; } } silenceBuffers = []; modelStream = null; } function intermediateDecode() { let results = finishStream(); createStream(); return results; } function feedAudioContent(chunk) { recordedAudioLength += (chunk.length / 2) * (1 / 16000) * 1000; modelStream.feedAudioContent(chunk); } const app = http.createServer(function (req, res) { res.writeHead(200); res.write('web-microphone-websocket'); res.end(); }); const io = socketIO(app, {}); io.set('origins', '*:*'); io.on('connection', function(socket) { console.log('client connected'); socket.once('disconnect', () => { console.log('client disconnected'); }); createStream(); socket.on('stream-data', function(data) { processAudioStream(data, (results) => { socket.emit('recognize', results); }); }); socket.on('stream-end', function() { endAudioStream((results) => { socket.emit('recognize', results); }); }); socket.on('stream-reset', function() { resetAudioStream(); }); }); app.listen(SERVER_PORT, 'localhost', () => { console.log('Socket server listening on:', SERVER_PORT); }); module.exports = app;
0
coqui_public_repos/STT-models/mongolian/itml
coqui_public_repos/STT-models/mongolian/itml/v0.1.0/LICENSE
GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <https://www.gnu.org/licenses/>.
0
coqui_public_repos/TTS/TTS/tts/layers
coqui_public_repos/TTS/TTS/tts/layers/generic/pos_encoding.py
import math import torch from torch import nn class PositionalEncoding(nn.Module): """Sinusoidal positional encoding for non-recurrent neural networks. Implementation based on "Attention Is All You Need" Args: channels (int): embedding size dropout_p (float): dropout rate applied to the output. max_len (int): maximum sequence length. use_scale (bool): whether to use a learnable scaling coefficient. """ def __init__(self, channels, dropout_p=0.0, max_len=5000, use_scale=False): super().__init__() if channels % 2 != 0: raise ValueError( "Cannot use sin/cos positional encoding with " "odd channels (got channels={:d})".format(channels) ) self.use_scale = use_scale if use_scale: self.scale = torch.nn.Parameter(torch.ones(1)) pe = torch.zeros(max_len, channels) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.pow(10000, torch.arange(0, channels, 2).float() / channels) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0).transpose(1, 2) self.register_buffer("pe", pe) if dropout_p > 0: self.dropout = nn.Dropout(p=dropout_p) self.channels = channels def forward(self, x, mask=None, first_idx=None, last_idx=None): """ Shapes: x: [B, C, T] mask: [B, 1, T] first_idx: int last_idx: int """ x = x * math.sqrt(self.channels) if first_idx is None: if self.pe.size(2) < x.size(2): raise RuntimeError( f"Sequence is {x.size(2)} but PositionalEncoding is" f" limited to {self.pe.size(2)}. See max_len argument." ) if mask is not None: pos_enc = self.pe[:, :, : x.size(2)] * mask else: pos_enc = self.pe[:, :, : x.size(2)] if self.use_scale: x = x + self.scale * pos_enc else: x = x + pos_enc else: if self.use_scale: x = x + self.scale * self.pe[:, :, first_idx:last_idx] else: x = x + self.pe[:, :, first_idx:last_idx] if hasattr(self, "dropout"): x = self.dropout(x) return x
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/expanded-fst.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Generic FST augmented with state count-interface class definition. #ifndef FST_EXPANDED_FST_H_ #define FST_EXPANDED_FST_H_ #include <sys/types.h> #include <istream> #include <string> #include <fst/log.h> #include <fstream> #include <fst/fst.h> namespace fst { // A generic FST plus state count. template <class A> class ExpandedFst : public Fst<A> { public: using Arc = A; using StateId = typename Arc::StateId; virtual StateId NumStates() const = 0; // State count // Get a copy of this ExpandedFst. See Fst<>::Copy() for further doc. ExpandedFst<Arc> *Copy(bool safe = false) const override = 0; // Read an ExpandedFst from an input stream; return NULL on error. static ExpandedFst<Arc> *Read(std::istream &strm, const FstReadOptions &opts) { FstReadOptions ropts(opts); FstHeader hdr; if (ropts.header) { hdr = *opts.header; } else { if (!hdr.Read(strm, opts.source)) return nullptr; ropts.header = &hdr; } if (!(hdr.Properties() & kExpanded)) { LOG(ERROR) << "ExpandedFst::Read: Not an ExpandedFst: " << ropts.source; return nullptr; } const auto reader = FstRegister<Arc>::GetRegister()->GetReader(hdr.FstType()); if (!reader) { LOG(ERROR) << "ExpandedFst::Read: Unknown FST type \"" << hdr.FstType() << "\" (arc type = \"" << A::Type() << "\"): " << ropts.source; return nullptr; } auto *fst = reader(strm, ropts); if (!fst) return nullptr; return static_cast<ExpandedFst<Arc> *>(fst); } // Read an ExpandedFst from a file; return NULL on error. // Empty filename reads from standard input. static ExpandedFst<Arc> *Read(const string &filename) { if (!filename.empty()) { std::ifstream strm(filename, std::ios_base::in | std::ios_base::binary); if (!strm) { LOG(ERROR) << "ExpandedFst::Read: Can't open file: " << filename; return nullptr; } return Read(strm, FstReadOptions(filename)); } else { return Read(std::cin, FstReadOptions("standard input")); } } }; namespace internal { // ExpandedFst<A> case - abstract methods. template <class Arc> inline typename Arc::Weight Final(const ExpandedFst<Arc> &fst, typename Arc::StateId s) { return fst.Final(s); } template <class Arc> inline std::ptrdiff_t NumArcs(const ExpandedFst<Arc> &fst, typename Arc::StateId s) { return fst.NumArcs(s); } template <class Arc> inline std::ptrdiff_t NumInputEpsilons(const ExpandedFst<Arc> &fst, typename Arc::StateId s) { return fst.NumInputEpsilons(s); } template <class Arc> inline std::ptrdiff_t NumOutputEpsilons(const ExpandedFst<Arc> &fst, typename Arc::StateId s) { return fst.NumOutputEpsilons(s); } } // namespace internal // A useful alias when using StdArc. using StdExpandedFst = ExpandedFst<StdArc>; // This is a helper class template useful for attaching an ExpandedFst // interface to its implementation, handling reference counting. It // delegates to ImplToFst the handling of the Fst interface methods. template <class Impl, class FST = ExpandedFst<typename Impl::Arc>> class ImplToExpandedFst : public ImplToFst<Impl, FST> { public: using Arc = typename FST::Arc; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using ImplToFst<Impl, FST>::operator=; StateId NumStates() const override { return GetImpl()->NumStates(); } protected: using ImplToFst<Impl, FST>::GetImpl; explicit ImplToExpandedFst(std::shared_ptr<Impl> impl) : ImplToFst<Impl, FST>(impl) {} ImplToExpandedFst(const ImplToExpandedFst<Impl, FST> &fst) : ImplToFst<Impl, FST>(fst) {} ImplToExpandedFst(const ImplToExpandedFst<Impl, FST> &fst, bool safe) : ImplToFst<Impl, FST>(fst, safe) {} static Impl *Read(std::istream &strm, const FstReadOptions &opts) { return Impl::Read(strm, opts); } // Read FST implementation from a file; return NULL on error. // Empty filename reads from standard input. static Impl *Read(const string &filename) { if (!filename.empty()) { std::ifstream strm(filename, std::ios_base::in | std::ios_base::binary); if (!strm) { LOG(ERROR) << "ExpandedFst::Read: Can't open file: " << filename; return nullptr; } return Impl::Read(strm, FstReadOptions(filename)); } else { return Impl::Read(std::cin, FstReadOptions("standard input")); } } }; // Function to return the number of states in an FST, counting them // if necessary. template <class Arc> typename Arc::StateId CountStates(const Fst<Arc> &fst) { if (fst.Properties(kExpanded, false)) { const auto *efst = static_cast<const ExpandedFst<Arc> *>(&fst); return efst->NumStates(); } else { typename Arc::StateId nstates = 0; for (StateIterator<Fst<Arc>> siter(fst); !siter.Done(); siter.Next()) { ++nstates; } return nstates; } } // Function to return the number of arcs in an FST. template <class Arc> typename Arc::StateId CountArcs(const Fst<Arc> &fst) { size_t narcs = 0; for (StateIterator<Fst<Arc>> siter(fst); !siter.Done(); siter.Next()) { narcs += fst.NumArcs(siter.Value()); } return narcs; } } // namespace fst #endif // FST_EXPANDED_FST_H_
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/android-cache-arm64-v8a-android-25.yml
build: template_file: generic_tc_caching-linux-opt-base.tyml system_setup: > ${java.packages_xenial.apt} cache: artifact_url: ${system.android_cache.arm64_v8a.android_25.url} artifact_namespace: ${system.android_cache.arm64_v8a.android_25.namespace} scripts: setup: "taskcluster/tc-true.sh" build: "taskcluster/android_cache-build.sh arm64-v8a android-25" package: "taskcluster/android_cache-package.sh" workerType: "${docker.smallTask}" metadata: name: "Builds Android cache arm64-v8a / android-25" description: "Setup an Android SDK / emulator cache for Android arm64-v8a / android-25"
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/extensions
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/extensions/linear/linear-classifier-fst.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/extensions/linear/linear-fst.h> #include <fst/register.h> using fst::LinearClassifierFst; using fst::StdArc; using fst::LogArc; REGISTER_FST(LinearClassifierFst, StdArc); REGISTER_FST(LinearClassifierFst, LogArc);
0
coqui_public_repos/STT/training
coqui_public_repos/STT/training/coqui_stt_training/GRAPH_VERSION
6
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-nodejs_13x_8k_multiarchpkg-linux-amd64-prod_pbmodel-opt.yml
build: template_file: test-linux-opt-base.tyml docker_image: "ubuntu:16.04" dependencies: - "node-package-cpu" system_setup: > ${nodejs.packages_xenial.prep_13} && ${nodejs.packages_xenial.apt_pinning} && apt-get -qq update && apt-get -qq -y install ${nodejs.packages_xenial.apt} args: tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-node-tests-prod.sh 13.x 8k" workerType: "${docker.dsTests}" metadata: name: "DeepSpeech Linux AMD64 CPU NodeJS MultiArch Package 13.x prod tests (8kHz)" description: "Testing DeepSpeech for Linux/AMD64 on NodeJS MultiArch Package v13.x on prod model, CPU only, optimized version (8kHz)"
0
coqui_public_repos/STT
coqui_public_repos/STT/bin/run-ci-ldc93s1_new_sdb.sh
#!/bin/sh set -xe ldc93s1_dir="./data/smoke_test" ldc93s1_csv="${ldc93s1_dir}/ldc93s1.csv" ldc93s1_sdb="${ldc93s1_dir}/ldc93s1.sdb" epoch_count=$1 audio_sample_rate=$2 if [ ! -f "${ldc93s1_dir}/ldc93s1.csv" ]; then echo "Downloading and preprocessing LDC93S1 example data, saving in ${ldc93s1_dir}." python -u bin/import_ldc93s1.py ${ldc93s1_dir} fi; if [ ! -f "${ldc93s1_dir}/ldc93s1.sdb" ]; then echo "Converting LDC93S1 example data, saving to ${ldc93s1_sdb}." python -u bin/data_set_tool.py --sources ${ldc93s1_csv} --target ${ldc93s1_sdb} fi; # Force only one visible device because we have a single-sample dataset # and when trying to run on multiple devices (like GPUs), this will break export CUDA_VISIBLE_DEVICES=0 python -u train.py --alphabet_config_path "data/alphabet.txt" \ --show_progressbar false --early_stop false \ --train_files ${ldc93s1_sdb} --train_batch_size 1 \ --dev_files ${ldc93s1_sdb} --dev_batch_size 1 \ --test_files ${ldc93s1_sdb} --test_batch_size 1 \ --n_hidden 100 --epochs $epoch_count \ --max_to_keep 1 --checkpoint_dir '/tmp/ckpt_sdb' \ --learning_rate 0.001 --dropout_rate 0.05 --export_dir '/tmp/train_sdb' \ --scorer_path 'data/smoke_test/pruned_lm.scorer' \ --audio_sample_rate ${audio_sample_rate}
0
coqui_public_repos/STT-models/maltese/itml
coqui_public_repos/STT-models/maltese/itml/v0.1.0/MODEL_CARD.md
# Model card for Maltese STT Jump to section: - [Model details](#model-details) - [Intended use](#intended-use) - [Performance Factors](#performance-factors) - [Metrics](#metrics) - [Training data](#training-data) - [Evaluation data](#evaluation-data) - [Ethical considerations](#ethical-considerations) - [Caveats and recommendations](#caveats-and-recommendations) ## Model details - Person or organization developing model: Originally trained by [Francis Tyers](https://scholar.google.fr/citations?user=o5HSM6cAAAAJ) and the [Inclusive Technology for Marginalised Languages](https://itml.cl.indiana.edu/) group. - Model language: Maltese / Malti / `mt` - Model date: April 9, 2021 - Model type: `Speech-to-Text` - Model version: `v0.1.0` - Compatible with 🐸 STT version: `v0.9.3` - License: AGPL - Citation details: `@techreport{maltese-stt, author = {Tyers,Francis}, title = {Maltese STT 0.1}, institution = {Coqui}, address = {\url{https://github.com/coqui-ai/STT-models}} year = {2021}, month = {April}, number = {STT-CV6.1-MT-0.1} }` - Where to send questions or comments about the model: You can leave an issue on [`STT-model` issues](https://github.com/coqui-ai/STT-models/issues), open a new discussion on [`STT-model` discussions](https://github.com/coqui-ai/STT-models/discussions), or chat with us on [Gitter](https://gitter.im/coqui-ai/). ## Intended use Speech-to-Text for the [Maltese Language](https://en.wikipedia.org/wiki/Maltese_language) on 16kHz, mono-channel audio. ## Performance Factors Factors relevant to Speech-to-Text performance include but are not limited to speaker demographics, recording quality, and background noise. Read more about STT performance factors [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). ## Metrics STT models are usually evaluated in terms of their transcription accuracy, deployment Real-Time Factor, and model size on disk. #### Transcription Accuracy The following Word Error Rates and Character Error Rates are reported on [omnilingo](https://tepozcatl.omnilingo.cc/mt/). |Test Corpus|WER|CER| |-----------|---|---| |Common Voice|93.6\%|33.7\%| #### Real-Time Factor Real-Time Factor (RTF) is defined as `processing-time / length-of-audio`. The exact real-time factor of an STT model will depend on the hardware setup, so you may experience a different RTF. Recorded average RTF on laptop CPU: `` #### Model Size `model.pbmm`: 181M `model.tflite`: 46M ### Approaches to uncertainty and variability Confidence scores and multiple paths from the decoding beam can be used to measure model uncertainty and provide multiple, variable transcripts for any processed audio. ## Training data This model was trained on Common Voice 6.1 train. ## Evaluation data The Model was evaluated on Common Voice 6.1 test. ## Ethical considerations Deploying a Speech-to-Text model into any production setting has ethical implications. You should consider these implications before use. ### Demographic Bias You should assume every machine learning model has demographic bias unless proven otherwise. For STT models, it is often the case that transcription accuracy is better for men than it is for women. If you are using this model in production, you should acknowledge this as a potential issue. ### Surveillance Speech-to-Text may be mis-used to invade the privacy of others by recording and mining information from private conversations. This kind of individual privacy is protected by law in may countries. You should not assume consent to record and analyze private speech. ## Caveats and recommendations Machine learning models (like this STT model) perform best on data that is similar to the data on which they were trained. Read about what to expect from an STT model with regard to your data [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data). In most applications, it is recommended that you [train your own language model](https://stt.readthedocs.io/en/latest/LANGUAGE_MODEL.html) to improve transcription accuracy on your speech data.
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/extensions
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/extensions/python/pywrapfst.pyx
#cython: nonecheck=True # See www.openfst.org for extensive documentation on this weighted # finite-state transducer library. """Python interface to the FST scripting API. Operations which construct new FSTs are implemented as traditional functions, as are two-argument boolean functions like `equal` and `equivalent`. Destructive operations---those that mutate an FST, in place---are instance methods, as is `write`. Operator overloading is not used. The following example, based on Mohri et al. 2002, shows the construction of an ASR system given a pronunciation lexicon L, grammar G, a transducer from context-dependent phones to context-independent phones C, and an HMM set H: L = fst.Fst.read("L.fst") G = fst.Fst.read("G.fst") C = fst.Fst.read("C.fst") H = fst.Fst.read("H.fst") LG = fst.determinize(fst.compose(L, G)) CLG = fst.determinize(fst.compose(C, LG)) HCLG = fst.determinize(fst.compose(H, CLG)) HCLG.minimize() # NB: works in-place. Python variables here use snake_case and constants are in all caps, minus the normal `k` prefix. """ # Overview of the file: # # * Imports # * Custom exceptions # * General helpers # * Weight and helpers # * _SymbolTable, _EncodeMapperSymbolTable, _FstSymbolTable, # _MutableFstSymbolTable, SymbolTable, and helpers # * SymbolTableIterator # * EncodeMapper # * _Fst, _MutableFst, Fst, and helpers # * FST properties # * Arc, ArcIterator, and MutableArcIterator # * StateIterator # * FST operations # * Compiler # * FarReader and FarWriter # * Cleanup operations for module entrance and exit. # # TODO(kbg): Try breaking this apart into smaller pieces. # # A few of the more idiosyncratic choices made here are due to "impedance # mismatches" between C++ and Python, as follows. # # Another issue is that due to differences in C++ and Python scope rules, most # C++ class instances have to be heap-allocated. Since all are packed into # Python class instances, Python destructors are used to semi-automatically # free C++ instances. The one exception are the various `...Options` structs. # All that is included here are the constructors; there is no need to include # the names of the struct members. Cython does not draw any meaningful # distinction between structs and C++ classes, so these look just like class # definitions. # # Cython's type annotations (e.g., `string`) are used when the variables will # be sent as arguments to C++ functions, but are not used for variables used # within the module. # # Internal functions which may raise a Python error do not have a C++ return # type simply because this leads the C++ compiler to think that the resulting # value could be used before it is populated. ## Imports. # C imports. from libc.stdint cimport INT32_MAX from libc.stdint cimport SIZE_MAX from posix.unistd cimport getpid # C++ imports. from libcpp cimport bool from libcpp.cast cimport const_cast from libcpp.cast cimport static_cast # Our C++ imports. from ios cimport ofstream from memory cimport static_pointer_cast # Cython operator workarounds. from cython.operator cimport address as addr # &foo from cython.operator cimport dereference as deref # *foo from cython.operator cimport preincrement as inc # ++foo # Python imports. import atexit import numbers import subprocess import logging # TODO(kbg): Figure out how to access static class variables so I don't have # to do it this way. kNoSymbol = -1 ## Custom exceptions. class FstError(Exception): pass class FstArgError(FstError, ValueError): pass class FstBadWeightError(FstError, ValueError): pass class FstDeletedConstructorError(FstError, RuntimeError): pass class FstIndexError(FstError, IndexError): pass class FstIOError(FstError, IOError): pass class FstOpError(FstError, RuntimeError): pass ## General helpers. cdef string tostring(data, encoding="utf8") except *: """Converts strings to bytestrings. This function converts Python bytestrings and Unicode strings to bytestrings encoded in UTF-8. It is used to process most Python string arguments before passing them to the lower-level library. Args: data: A Unicode string or bytestring. encoding: The desired encoding, defaulting to UTF-8. Returns: A bytestring. Raises: FstArgError: Cannot encode string. UnicodeEncodeError. This function is not visible to Python users. """ # A Python bytestring can be implicitly cast to a C++ string. if isinstance(data, bytes): return data elif isinstance(data, unicode): return data.encode(encoding) raise FstArgError("Cannot encode as string: {!r}".format(data)) cdef string weight_tostring(data, encoding="utf8") except *: """Converts strings or numerics to bytestrings. This function converts Python bytestrings, Unicode strings, and numerics which can be cast to floats to bytestrings encoded in UTF-8. It is used to process Python string arguments so they can be used to construct Weight objects. In most cases, weights are underlyingly floating-point, but since not all weights are, they can only be constructed using a string. Args: data: A Unicode string, bytestring, or type which can be converted to a Python float. Returns: A bytestring. Raise: FstArgError: Cannot encode string. ValueError: Invalid literal for float. UnicodeEncodeError. This function is not visible to Python users. """ # A Python bytestring can be implicitly cast to a C++ string. if isinstance(data, bytes): return data elif isinstance(data, unicode): return data.encode(encoding) elif isinstance(data, numbers.Number): return str(data).encode(encoding) raise FstArgError("Cannot encode as string: {!r}".format(data)) cdef fst.ComposeFilter _get_compose_filter( const string &compose_filter) except *: """Matches string with the appropriate ComposeFilter enum value. This function takes a string argument and returns the matching ComposeFilter enum value used to initialize ComposeOptions instances. ComposeOptions is used by difference and intersection in addition to composition. Args: compose_filter: A string matching a known composition filter; one of: "alt_sequence", "auto", "match", "null", "sequence", "trivial". Returns: A ComposeFilter enum value. Raises: FstArgError: Unknown compose filter type. This function is not visible to Python users. """ cdef fst.ComposeFilter compose_filter_enum if not fst.GetComposeFilter(compose_filter, addr(compose_filter_enum)): raise FstArgError("Unknown compose filter type: {!r}".format( compose_filter)) return compose_filter_enum cdef fst.DeterminizeType _get_determinize_type(const string &det_type) except *: """Matches string with the appropriate DeterminizeType enum value. Args: det_type: A string matching a known determinization type; one of: "functional", "nonfunctional", "disambiguate". Returns: A DeterminizeType enum value. Raises: FstArgError: Unknown determinization type. This function is not visible to Python users. """ cdef fst.DeterminizeType det_type_enum if not fst.GetDeterminizeType(det_type, addr(det_type_enum)): raise FstArgError("Unknown determinization type: {!r}".format(det_type)) return det_type_enum cdef fst.QueueType _get_queue_type(const string &queue_type) except *: """Matches string with the appropriate QueueType enum value. This function takes a string argument and returns the matching QueueType enum value passed to the RmEpsilonOptions constructor. Args: queue_type: A string matching a known queue type; one of: "auto", "fifo", "lifo", "shortest", "state", "top". Returns: A QueueType enum value. Raises: FstArgError: Unknown queue type. This function is not visible to Python users. """ cdef fst.QueueType queue_type_enum if not fst.GetQueueType(queue_type, addr(queue_type_enum)): raise FstArgError("Unknown queue type: {!r}".format(queue_type)) return queue_type_enum cdef fst.RandArcSelection _get_rand_arc_selection( const string &select) except *: """Matches string with the appropriate RandArcSelection enum value. This function takes a string argument and returns the matching RandArcSelection enum value passed to the RandGenOptions constructor. Args: select: A string matching a known random arc selection type; one of: "uniform", "log_prob", "fast_log_prob". Returns: A RandArcSelection enum value. Raises: FstArgError: Unknown random arc selection type. This function is not visible to Python users. """ cdef fst.RandArcSelection select_enum if not fst.GetRandArcSelection(select, addr(select_enum)): raise FstArgError("Unknown random arc selection type: {!r}".format(select)) return select_enum cdef fst.ReplaceLabelType _get_replace_label_type( const string &replace_label_type, bool epsilon_on_replace) except *: """Matches string with the appropriate ReplaceLabelType enum value. This function takes a string argument and returns the matching ReplaceLabelType enum value passed to the ReplaceOptions constructor. Args: replace_label_type: A string matching a known replace label type; one of: "neither", "input", "output", "both". epsilon_on_replace: Should call/return arcs be epsilon arcs? Returns: A ReplaceLabelType enum value. Raises: FstArgError: Unknown replace label type. This function is not visible to Python users. """ cdef fst.ReplaceLabelType replace_label_type_enum if not fst.GetReplaceLabelType(replace_label_type, epsilon_on_replace, addr(replace_label_type_enum)): raise FstArgError("Unknown replace label type: {!r}".format( replace_label_type)) return replace_label_type_enum ## Weight and helpers. cdef class Weight(object): """ Weight(weight_type, weight_string) FST weight class. This class represents an FST weight. When passed as an argument to an FST operation, it should have the weight type of the input FST(s) to said operation. Args: weight_type: A string indicating the weight type. weight_string: A string indicating the underlying weight. Raises: FstArgError: Weight type not found. FstBadWeightError: Invalid weight. """ def __repr__(self): return "<{} Weight {} at 0x{:x}>".format(self.type(), self.to_string(), id(self)) def __str__(self): return self.to_string() # This attempts to convert the string form into a float, raising # ValueError when that is not appropriate. def __float__(self): return float(self.to_string()) def __init__(self, weight_type, weight): self._weight.reset(new fst.WeightClass(tostring(weight_type), weight_tostring(weight))) self._check_weight() cdef void _check_weight(self) except *: if self.type() == b"none": raise FstArgError("Weight type not found") if self.to_string() == b"BadNumber": raise FstBadWeightError("Invalid weight") cpdef Weight copy(self): """ copy(self) Returns a copy of the Weight. """ cdef Weight result = Weight.__new__(Weight) result._weight.reset(new fst.WeightClass(deref(self._weight))) return result # To get around the inability to declare cdef class methods, we define the # C++ part out-of-class and then call it from within. @classmethod def Zero(cls, weight_type): """ Weight.Zero(weight_type) Constructs semiring zero. """ return _Zero(weight_type) @classmethod def One(cls, weight_type): """ Weight.One(weight_type) Constructs semiring One. """ return _One(weight_type) @classmethod def NoWeight(cls, weight_type): """ Weight.NoWeight(weight_type) Constructs a non-member weight in the semiring. """ return _NoWeight(weight_type) def __eq__(Weight w1, Weight w2): return fst.Eq(deref(w1._weight), deref(w2._weight)) def __ne__(Weight w1, Weight w2): return not w1 == w2 cpdef string to_string(self): return self._weight.get().ToString() cpdef string type(self): """type(self) Returns a string indicating the weight type. """ return self._weight.get().Type() cdef Weight _plus(Weight lhs, Weight rhs): cdef Weight result = Weight.__new__(Weight) result._weight.reset(new fst.WeightClass(fst.Plus(deref(lhs._weight), deref(rhs._weight)))) return result def plus(Weight lhs, Weight rhs): """ plus(lhs, rhs) Computes the sum of two Weights in the same semiring. This function computes lhs \oplus rhs, raising an exception if lhs and rhs are not in the same semiring. Args: lhs: Left-hand side Weight. rhs: Right-hand side Weight. Returns: A Weight object. Raises: FstArgError: Weight type not found (or not in same semiring). FstBadWeightError: invalid weight. """ cdef Weight result = _plus(lhs, rhs) result._check_weight() return result cdef Weight _times(Weight lhs, Weight rhs): cdef Weight result = Weight.__new__(Weight) result._weight.reset(new fst.WeightClass(fst.Times(deref(lhs._weight), deref(rhs._weight)))) return result def times(Weight lhs, Weight rhs): """ times(lhs, rhs) Computes the product of two Weights in the same semiring. This function computes lhs \otimes rhs, raising an exception if lhs and rhs are not in the same semiring. Args: lhs: Left-hand side Weight. rhs: Right-hand side Weight. Returns: A Weight object. Raises: FstArgError: Weight type not found (or not in same semiring). FstBadWeightError: Invalid weight. """ cdef Weight result = _times(lhs, rhs) result._check_weight() return result cdef Weight _divide(Weight lhs, Weight rhs): cdef Weight result = Weight.__new__(Weight) result._weight.reset(new fst.WeightClass(fst.Divide(deref(lhs._weight), deref(rhs._weight)))) return result def divide(Weight lhs, Weight rhs): """ divide(lhs, rhs) Computes the quotient of two Weights in the same semiring. This function computes lhs \oslash rhs, raising an exception if lhs and rhs are not in the same semiring. As there is no way to specify whether to use left vs. right division, this assumes a commutative semiring in which these are equivalent operations. Args: lhs: Left-hand side Weight. rhs: Right-hand side Weight. Returns: A Weight object. Raises: FstArgError: Weight type not found (or not in same semiring). FstBadWeightError: Invalid weight. """ cdef Weight result = _divide(lhs, rhs) result._check_weight() return result cdef Weight _power(Weight w, size_t n): cdef Weight result = Weight.__new__(Weight) result._weight.reset(new fst.WeightClass(fst.Power(deref(w._weight), n))) return result def power(Weight w, size_t n): """ power(lhs, rhs) Computes the iterated product of a weight. Args: w: The weight. n: The power. Returns: A Weight object. Raises: FstArgError: Weight type not found (or not in same semiring). FstBadWeightError: Invalid weight. """ cdef Weight result = _power(w, n) result._check_weight() return result cdef fst.WeightClass _get_WeightClass_or_Zero(const string &weight_type, weight) except *: """Converts weight string to a WeightClass. This function constructs a WeightClass instance of the desired weight type. If the first argument is null, the weight is set to semiring Zero. Args: weight_type: A string denoting the desired weight type. weight: A object indicating the desired weight; if omitted, the weight is set to semiring Zero. Returns: A WeightClass object. This function is not visible to Python users. """ cdef fst.WeightClass result if weight is None: result = fst.WeightClass.Zero(weight_type) elif isinstance(weight, Weight): result = deref(<fst.WeightClass *> (<Weight> weight)._weight.get()) else: result = fst.WeightClass(weight_type, weight_tostring(weight)) if result.ToString() == b"BadNumber": raise FstBadWeightError(weight_tostring(weight)) return result cdef fst.WeightClass _get_WeightClass_or_One(const string &weight_type, weight) except *: """Converts weight string to a WeightClass. This function constructs a WeightClass instance of the desired weight type. If the first argument is null, the weight is set to semiring One. Args: weight_type: A string denoting the desired weight type. weight: A object indicating the desired weight; if omitted, the weight is set to semiring One. Returns: A WeightClass object. This function is not visible to Python users. """ cdef fst.WeightClass result if weight is None: result = fst.WeightClass.One(weight_type) elif isinstance(weight, Weight): result = deref(<fst.WeightClass *> (<Weight> weight)._weight.get()) else: result = fst.WeightClass(weight_type, weight_tostring(weight)) if result.ToString() == b"BadNumber": raise FstBadWeightError(weight_tostring(weight)) return result cdef Weight _Zero(weight_type): cdef Weight result = Weight.__new__(Weight) result._weight.reset(new fst.WeightClass(fst.WeightClass.Zero( tostring(weight_type)))) if result._weight.get().Type() == b"none": raise FstArgError("Weight type not found") return result cdef Weight _One(weight_type): cdef Weight result = Weight.__new__(Weight) result._weight.reset(new fst.WeightClass( fst.WeightClass.One(tostring(weight_type)))) if result._weight.get().Type() == b"none": raise FstArgError("Weight type not found") return result cdef Weight _NoWeight(weight_type): cdef Weight result = Weight.__new__(Weight) result._weight.reset(new fst.WeightClass( fst.WeightClass.NoWeight(tostring(weight_type)))) return result ## _SymbolTable, _MutableSymbolTable, _EncodeMapperSymbolTable, _FstSymbolTable, ## _MutableFstSymbolTable, SymbolTable, and helpers. # # SymbolTable hierarchy: # # _SymbolTable: abstract base class; has-a SymbolTable* # _EncodeMapperSymbolTable(_SymbolTable): constant symbol table returned by # EncodeMapper.input_symbols/output_symbols # _FstSymbolTable(_SymbolTable): constant symbol table returned by # _Fst.input_symbols/output_symbols # # _MutableSymbolTable(_SymbolTable): abstract base class adding mutation methods # _MutableFstSymbolTable(_MutableSymbolTable): mutable symbol table returned by # _MutableFst.mutable_input_symbols/mutable_output_symbols # SymbolTable(_MutableSymbolTable): adds constructor cdef class _SymbolTable(object): """ (No constructor.) Base class for the symbol table hierarchy. This class is the base class for SymbolTable. It has a "deleted" constructor and implementations for the const methods of the wrapped SymbolTable. """ # NB: Do not expose any non-const methods of the wrapped SymbolTable here. # Doing so will allow undefined behavior. def __init__(self): raise FstDeletedConstructorError( "Cannot construct {}".format(self.__class__.__name__)) def __iter__(self): return SymbolTableIterator(self) cpdef int64 available_key(self): """ available_key(self) Returns an integer indicating the next available key index in the table. """ return self._table.AvailableKey() cpdef string checksum(self): """ checksum(self) Returns a string indicating the label-agnostic MD5 checksum for the table. """ return self._table.CheckSum() cpdef SymbolTable copy(self): """ copy(self) Returns a mutable copy of the SymbolTable. """ return _init_SymbolTable(self._table.Copy()) def find(self, key): """ find(self, key) Given a symbol or index, finds the other one. This method returns the index associated with a symbol key, or the symbol associated with a index key. Args: key: Either a string or an index. Returns: If the key is a string, the associated index or NO_LABEL if not found; if the key is an integer, the associated symbol or an empty string if not found. """ try: return self._table.FindIndex(tostring(key)) except FstArgError: return self._table.FindSymbol(key) cpdef int64 get_nth_key(self, ssize_t pos) except *: """ get_nth_key(self, pos) Retrieves the integer index of the n-th key in the table. Args: pos: The n-th key to retrieve. Returns: The integer index of the n-th key, or NO_LABEL if not found. """ return self._table.GetNthKey(pos) cpdef string labeled_checksum(self): """ labeled_checksum(self) Returns a string indicating the label-dependent MD5 checksum for the table. """ return self._table.LabeledCheckSum() cpdef bool member(self, key): """ member(self, key) Given a symbol or index, returns whether it is found in the table. This method returns a boolean indicating whether the given symbol or index is present in the table. If one intends to perform subsequent lookup, it is better to simply call the find method, catching the KeyError. Args: key: Either a string or an index. Returns: Whether or not the key is present (as a string or a index) in the table. """ try: return self._table.MemberSymbol(tostring(key)) except FstArgError: return self._table.MemberIndex(key) def __contains__(self, key): return self.member(key) cpdef string name(self): """ name(self) Returns the symbol table's name. """ return self._table.Name() cpdef size_t num_symbols(self): """ num_symbols(self) Returns the number of symbols in the symbol table. """ return self._table.NumSymbols() cpdef void write(self, filename) except *: """ write(self, filename) Serializes symbol table to a file. This methods writes the SymbolTable to a file in binary format. Args: filename: The string location of the output file. Raises: FstIOError: Write failed. """ if not self._table.Write(tostring(filename)): raise FstIOError("Write failed: {!r}".format(filename)) cpdef void write_text(self, filename) except *: """ write_text(self, filename) Writes symbol table to text file. This method writes the SymbolTable to a file in human-readable format. Args: filename: The string location of the output file. Raises: FstIOError: Write failed. """ if not self._table.WriteText(tostring(filename)): raise FstIOError("Write failed: {!r}".format(filename)) cdef class _EncodeMapperSymbolTable(_SymbolTable): """ (No constructor.) Immutable SymbolTable class for tables stored in an EncodeMapper. This class wraps a library const SymbolTable and exposes const methods of the wrapped object. It is only to be returned by method, never constructed directly. """ # NB: Do not expose any non-const methods of the wrapped SymbolTable here. # Doing so will allow undefined behavior. def __repr__(self): return "<const EncodeMapper SymbolTable {!r} at 0x{:x}>".format(self.name(), id(self)) cdef class _FstSymbolTable(_SymbolTable): """ (No constructor.) Mutable SymbolTable class for tables stored in a mutable FST. This class wraps a library SymbolTable and exposes methods of the wrapped object. It is only to be returned by method, never constructed directly. """ # NB: Do not expose any non-const methods of the wrapped SymbolTable here. # Doing so will allow undefined behavior. def __repr__(self): return "<const Fst SymbolTable {!r} at 0x{:x}>".format(self.name(), id(self)) cdef class _MutableSymbolTable(_SymbolTable): """ (No constructor.) Base class for mutable symbol tables. This class is the base class for a mutable SymbolTable. It has a "deleted" constructor and implementations of all methods of the wrapped SymbolTable. """ cpdef int64 add_symbol(self, symbol, int64 key=kNoSymbol): """ add_symbol(self, symbol, key=NO_SYMBOL) Adds a symbol to the table and returns the index. This method adds a symbol to the table. The caller can optionally specify a non-negative integer index for the key. Args: symbol: A symbol string. key: An index for the symbol; if not specified, the next index will be used. Returns: The integer key of the new symbol. """ cdef string symbol_string = tostring(symbol) if key != kNoSymbol: return self._table.AddSymbol(symbol_string, key) else: return self._table.AddSymbol(symbol_string) cpdef void add_table(self, _SymbolTable syms): """ add_table(self, syms) Adds another SymbolTable to this table. This method merges another symbol table into the current table. All key values will be offset by the current available key. Args: syms: A SymbolTable to be merged with the current table. """ self._table.AddTable(deref(syms._table)) cpdef void set_name(self, new_name) except *: self._table.SetName(tostring(new_name)) cdef class _MutableFstSymbolTable(_MutableSymbolTable): """ (No constructor.) Mutable SymbolTable assigned to an FST. """ def __repr__(self): return "<Fst SymbolTable {!r} at 0x{:x}>".format(self.name(), id(self)) cdef class SymbolTable(_MutableSymbolTable): """ SymbolTable(name="<unspecified>") Mutable SymbolTable class. This class wraps the library SymbolTable and exposes both const (i.e., access) and non-const (i.e., mutation) methods of wrapped object. Unlike other classes in the hierarchy, it has a working constructor and can be used to programmatically construct a SymbolTable in memory. Args: name: An optional string indicating the table's name. """ def __repr__(self): return "<SymbolTable {!r} at 0x{:x}>".format(self.name(), id(self)) def __init__(self, name=b"<unspecified>"): self._table = new fst.SymbolTable(tostring(name)) self._smart_table.reset(self._table) @classmethod def read(cls, filename): """ SymbolTable.read(filename) Reads symbol table from binary file. This class method creates a new SymbolTable from a symbol table binary file. Args: filename: The string location of the input binary file. Returns: A new SymbolTable instance. See also: `SymbolTable.read_fst`, `SymbolTable.read_text`. """ cdef fst.SymbolTable *tsyms = fst.SymbolTable.Read(tostring(filename)) if tsyms == NULL: raise FstIOError("Read failed: {!r}".format(filename)) return _init_SymbolTable(tsyms) @classmethod def read_text(cls, filename, bool allow_negative_labels=False): """ SymbolTable.read_text(filename) Reads symbol table from text file. This class method creates a new SymbolTable from a symbol table text file. Args: filename: The string location of the input text file. allow_negative_labels: Should negative labels be allowed? (Not recommended; may cause conflicts). Returns: A new SymbolTable instance. See also: `SymbolTable.read`, `SymbolTable.read_fst`. """ cdef unique_ptr[fst.SymbolTableTextOptions] opts opts.reset(new fst.SymbolTableTextOptions(allow_negative_labels)) cdef fst.SymbolTable *tsyms = fst.SymbolTable.ReadText(tostring(filename), deref(opts)) if tsyms == NULL: raise FstIOError("Read failed: {!r}".format(filename)) return _init_SymbolTable(tsyms) @classmethod def read_fst(cls, filename, bool input_table): """ SymbolTable.read_fst(filename, input_table) Reads symbol table from an FST file without loading the corresponding FST. This class method creates a new SymbolTable by reading either the input or output symbol table from an FST file, without loading the corresponding FST. Args: filename: The string location of the input FST file. input_table: Should the input table be read (True) or the output table (False)? Returns: A new SymbolTable instance, or None if none can be read. Raises: FstIOError: Read failed. See also: `SymbolTable.read`, `SymbolTable.read_text`. """ cdef fst.SymbolTable *tsyms = fst.FstReadSymbols(filename, input_table) if tsyms == NULL: raise FstIOError("Read failed: {!r}".format(filename)) return _init_SymbolTable(tsyms) cdef _EncodeMapperSymbolTable _init_EncodeMapperSymbolTable( fst.SymbolTable *table, shared_ptr[fst.EncodeMapperClass] encoder): cdef _EncodeMapperSymbolTable result = ( _EncodeMapperSymbolTable.__new__(_EncodeMapperSymbolTable)) result._table = table result._encoder = encoder return result cdef _FstSymbolTable _init_FstSymbolTable(fst.SymbolTable *table, shared_ptr[fst.FstClass] ifst): cdef _FstSymbolTable result = _FstSymbolTable.__new__(_FstSymbolTable) result._table = table result._fst = ifst return result cdef _MutableFstSymbolTable _init_MutableFstSymbolTable(fst.SymbolTable *table, shared_ptr[fst.MutableFstClass] ifst): cdef _MutableFstSymbolTable result = ( _MutableFstSymbolTable.__new__(_MutableFstSymbolTable)) result._table = table result._mfst = ifst return result cdef SymbolTable _init_SymbolTable(fst.SymbolTable *table): cdef SymbolTable result = SymbolTable.__new__(SymbolTable) result._table = table return result # Constructive SymbolTable operations. cpdef SymbolTable compact_symbol_table(_SymbolTable syms): """ compact_symbol_table(syms) Constructively relabels a SymbolTable to make it a contiguous mapping. Args: syms: Input SymbolTable. Returns: A new compacted SymbolTable. """ return _init_SymbolTable(fst.CompactSymbolTable(deref(syms._table))) cpdef SymbolTable merge_symbol_table(_SymbolTable lhs, _SymbolTable rhs): """ merge_symbol_table(lhs, rhs) Merges all symbols from the left table into the right. This function creates a new SymbolTable which is the merger of the two input symbol Tables. Symbols in the right-hand table that conflict with those in the left-hand table will be assigned values from the left-hand table. Thus the returned table will never modify symbol assignments from the left-hand side, but may do so on the right. If the left-hand table is associated with an FST, it may be necessary to relabel it using the output table. Args: lhs: Left-hand side SymbolTable. rhs: Left-hand side SymbolTable. Returns: A new merged SymbolTable. See also: `relabel_symbols`. """ return _init_SymbolTable(fst.MergeSymbolTable(deref(lhs._table), deref(rhs._table), NULL)) ## SymbolTableIterator. cdef class SymbolTableIterator(object): """ SymbolTableIterator(syms) This class is used for iterating over a symbol table. """ def __repr__(self): return "<SymbolTableIterator at 0x{:x}>".format(id(self)) def __init__(self, _SymbolTable syms): self._siter.reset(new fst.SymbolTableIterator(deref(syms._table))) # This just registers this class as a possible iterator. def __iter__(self): return self # Magic method used to get a Pythonic API out of the C++ API. def __next__(self): if self.done(): raise StopIteration cdef int64 value = self.value() cdef string symbol = self.symbol() self.next() return (value, symbol) cpdef bool done(self): """ done(self) Indicates whether the iterator is exhausted or not. Returns: True if the iterator is exhausted, False otherwise. """ return self._siter.get().Done() cpdef void next(self): """ next(self) Advances the iterator. """ self._siter.get().Next() cpdef void reset(self): """ reset(self) Resets the iterator to the initial position. """ self._siter.get().Reset() cpdef string symbol(self): """ symbol(self) Returns the current symbol string. This method returns the current symbol string at this point in the table. Returns: A symbol string. """ return self._siter.get().Symbol() cpdef int64 value(self): """ value(self) Returns the current integer index of the symbol. Returns: An integer index. """ return self._siter.get().Value() ## EncodeMapper. cdef class EncodeMapper(object): """ EncodeMapper(arc_type="standard", encode_labels=False, encode_weights=False) Arc encoder class, wrapping EncodeMapperClass. This class provides an object which can be used to encode or decode FST arcs. This is most useful to convert an FST to an unweighted acceptor, on which some FST operations are more efficient, and then decoding the FST afterwards. To use an instance of this class to encode or decode a mutable FST, pass it as the first argument to the FST instance methods `encode` and `decode`. For implementational reasons, it is not currently possible to use an encoder on disk to construct this class. Args: arc_type: A string indicating the arc type. encode_labels: Should labels be encoded? encode_weights: Should weights be encoded? """ def __repr__(self): return "<EncodeMapper at 0x{:x}>".format(id(self)) def __init__(self, arc_type=b"standard", bool encode_labels=False, bool encode_weights=False): cdef uint32 flags = fst.GetEncodeFlags(encode_labels, encode_weights) self._encoder.reset(new fst.EncodeMapperClass(tostring(arc_type), flags, fst.ENCODE)) if not self._encoder: raise FstOpError("Unknown arc type: {!r}".format(arc_type)) cpdef string arc_type(self): """ arc_type(self) Returns a string indicating the arc type. """ return self._encoder.get().ArcType() # Python's equivalent to operator(). def __call__(self, Arc arc): """ self(state, ilabel, olabel, weight, nextstate) Uses the encoder to encode an arc. Args: ilabel: The integer index of the input label. olabel: The integer index of the output label. weight: A Weight or weight string indicating the desired final weight; if null, it is set to semiring One. nextstate: The integer index of the destination state. Raises: FstOpError: Incompatible or invalid weight. """ return _init_Arc(self._encoder.get().__call__(deref(arc._arc))) cpdef uint32 flags(self): """ flags(self) Returns the encoder's flags. """ return self._encoder.get().Flags() cpdef _EncodeMapperSymbolTable input_symbols(self): """ input_symbols(self) Returns the encoder's input symbol table, or None if none is present. """ cdef fst.SymbolTable *syms = const_cast[SymbolTable_ptr]( self._encoder.get().InputSymbols()) if syms == NULL: return return _init_EncodeMapperSymbolTable(syms, self._encoder) cpdef _EncodeMapperSymbolTable output_symbols(self): """ output_symbols(self) Returns the encoder's output symbol table, or None if none is present. """ cdef fst.SymbolTable *syms = const_cast[SymbolTable_ptr]( self._encoder.get().OutputSymbols()) if syms == NULL: return return _init_EncodeMapperSymbolTable(syms, self._encoder) cpdef uint64 properties(self, uint64 mask): """ properties(self, mask) Provides property bits. This method provides user access to the properties of the encoder. Args: mask: The property mask to be compared to the encoder's properties. Returns: A 64-bit bitmask representing the requested properties. """ return self._encoder.get().Properties(mask) cpdef void set_input_symbols(self, _SymbolTable syms) except *: """ set_input_symbols(self, syms) Sets the encoder's input symbol table. Args: syms: A SymbolTable. See also: `set_output_symbols`. """ self._encoder.get().SetInputSymbols(syms._table) cpdef void set_output_symbols(self, _SymbolTable syms) except *: """ set_output_symbols(self, syms) Sets the encoder's output symbol table. Args: syms: A SymbolTable. See also: `set_input_symbols`. """ self._encoder.get().SetOutputSymbols(syms._table) cpdef string weight_type(self): """ weight_type(self) Returns a string indicating the weight type. """ return self._encoder.get().WeightType() ## _Fst, _MutableFst, Fst, and helpers. # # Fst hierarchy: # # _Fst: base class; has-a FstClass*. # _MutableFst(_Fst): adds mutable methods. # Fst(filename): pseudo-constructor. cdef class _Fst(object): """ (No constructor.) Immutable FST class, wrapping FstClass. This class is the basic user-facing FST object. It does not itself support any mutation operations. """ # IPython notebook magic to produce an SVG of the FST. def _repr_svg_(self): """IPython notebook magic to produce an SVG of the FST using GraphViz. This method produces an SVG of the internal graph. Users wishing to create publication-quality graphs should instead use the method `draw`, which exposes additional parameters. Raises: OSError: Cannot locate the `dot` executable. subprocess.CalledProcessError: `dot` returned non-zero exit code. See also: `draw`, `text`. """ # Throws OSError if the dot executable is not found. proc = subprocess.Popen(["dot", "-Tsvg"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cdef stringstream sstrm fst.DrawFst(deref(self._fst), self._fst.get().InputSymbols(), self._fst.get().OutputSymbols(), NULL, self._fst.get().Properties(fst.kAcceptor, True) == fst.kAcceptor, b"", 8.5, 11, True, False, 0.4, 0.25, 14, 5, b"g", False, addr(sstrm), b"_repr_svg") (sout, serr) = proc.communicate(sstrm.str()) if proc.returncode != 0: # Just to be explicit. raise subprocess.CalledProcessError(proc.returncode, self._DOT_TSVG) return sout.decode("utf8") def __repr__(self): return "<{} Fst at 0x{:x}>".format(self.fst_type(), id(self)) def __init__(self): raise FstDeletedConstructorError( "Cannot construct {}".format(self.__class__.__name__)) def __str__(self): return self.text() # Registers the class for pickling; must be repeated in any subclass which # can't be derived by _init_XFst. def __reduce__(self): return (_read_from_string, (self.write_to_string(),)) cpdef string arc_type(self): """ arc_type(self) Returns a string indicating the arc type. """ return self._fst.get().ArcType() cpdef ArcIterator arcs(self, int64 state): """ arcs(self, state) Returns an iterator over arcs leaving the specified state. Args: state: The source state ID. Returns: An ArcIterator. See also: `mutable_arcs`, `states`. """ return ArcIterator(self, state) cpdef _Fst copy(self): """ copy(self) Makes a copy of the FST. """ return _init_XFst(new fst.FstClass(deref(self._fst))) cpdef void draw(self, filename, _SymbolTable isymbols=None, _SymbolTable osymbols=None, SymbolTable ssymbols=None, bool acceptor=False, title=b"", double width=8.5, double height=11, bool portrait=False, bool vertical=False, double ranksep=0.4, double nodesep=0.25, int32 fontsize=14, int32 precision=5, float_format=b"g", bool show_weight_one=False): """ draw(self, filename, isymbols=None, osymbols=None, ssymbols=None, acceptor=False, title="", width=8.5, height=11, portrait=False, vertical=False, ranksep=0.4, nodesep=0.25, fontsize=14, precision=5, float_format="g", show_weight_one=False): Writes out the FST in Graphviz text format. This method writes out the FST in the dot graph description language. The graph can be rendered using the `dot` executable provided by Graphviz. Args: filename: The string location of the output dot/Graphviz file. isymbols: An optional symbol table used to label input symbols. osymbols: An optional symbol table used to label output symbols. ssymbols: An optional symbol table used to label states. acceptor: Should the figure be rendered in acceptor format if possible? title: An optional string indicating the figure title. width: The figure width, in inches. height: The figure height, in inches. portrait: Should the figure be rendered in portrait rather than landscape? vertical: Should the figure be rendered bottom-to-top rather than left-to-right? ranksep: The minimum separation separation between ranks, in inches. nodesep: The minimum separation between nodes, in inches. fontsize: Font size, in points. precision: Numeric precision for floats, in number of chars. float_format: One of: 'e', 'f' or 'g'. show_weight_one: Should weights equivalent to semiring One be printed? See also: `text`. """ cdef string filename_string = tostring(filename) cdef unique_ptr[ofstream] ostrm ostrm.reset(new ofstream(filename_string)) cdef fst.SymbolTable *ssymbols_ptr = NULL if ssymbols is not None: ssymbols_ptr = ssymbols._table fst.DrawFst(deref(self._fst), self._fst.get().InputSymbols() if isymbols is None else isymbols._table, self._fst.get().OutputSymbols() if osymbols is None else osymbols._table, ssymbols_ptr, acceptor, tostring(title), width, height, portrait, vertical, ranksep, nodesep, fontsize, precision, tostring(float_format), show_weight_one, ostrm.get(), filename_string) cpdef Weight final(self, int64 state): """ final(self, state) Returns the final weight of a state. Args: state: The integer index of a state. Returns: The final Weight of that state. Raises: FstIndexError: State index out of range. """ cdef Weight weight = Weight.__new__(Weight) weight._weight.reset(new fst.WeightClass(self._fst.get().Final(state))) return weight cpdef string fst_type(self): """ fst_type(self) Returns a string indicating the FST type. """ return self._fst.get().FstType() cpdef _FstSymbolTable input_symbols(self): """ input_symbols(self) Returns the FST's input symbol table, or None if none is present. See also: `input_symbols`. """ cdef fst.SymbolTable *syms = const_cast[SymbolTable_ptr]( self._fst.get().InputSymbols()) if syms == NULL: return return _init_FstSymbolTable(syms, self._fst) cpdef size_t num_arcs(self, int64 state) except *: """ num_arcs(self, state) Returns the number of arcs leaving a state. Args: state: The integer index of a state. Returns: The number of arcs leaving that state. Raises: FstIndexError: State index out of range. See also: `num_states`. """ cdef size_t result = self._fst.get().NumArcs(state) if result == SIZE_MAX: raise FstIndexError("State index out of range") return result cpdef size_t num_input_epsilons(self, int64 state) except *: """ num_input_epsilons(self, state) Returns the number of arcs with epsilon input labels leaving a state. Args: state: The integer index of a state. Returns: The number of epsilon-input-labeled arcs leaving that state. Raises: FstIndexError: State index out of range. See also: `num_output_epsilons`. """ cdef size_t result = self._fst.get().NumInputEpsilons(state) if result == SIZE_MAX: raise FstIndexError("State index out of range") return result cpdef size_t num_output_epsilons(self, int64 state) except *: """ num_output_epsilons(self, state) Returns the number of arcs with epsilon output labels leaving a state. Args: state: The integer index of a state. Returns: The number of epsilon-output-labeled arcs leaving that state. Raises: FstIndexError: State index out of range. See also: `num_input_epsilons`. """ cdef size_t result = self._fst.get().NumOutputEpsilons(state) if result == SIZE_MAX: raise FstIndexError("State index out of range") return result cpdef _FstSymbolTable output_symbols(self): """ output_symbols(self) Returns the FST's output symbol table, or None if none is present. See also: `input_symbols`. """ cdef fst.SymbolTable *syms = const_cast[SymbolTable_ptr]( self._fst.get().OutputSymbols()) if syms == NULL: return return _init_FstSymbolTable(syms, self._fst) cpdef uint64 properties(self, uint64 mask, bool test): """ properties(self, mask, test) Provides property bits. This method provides user access to the properties attributes for the FST. The resulting value is a long integer, but when it is cast to a boolean, it represents whether or not the FST has the `mask` property. Args: mask: The property mask to be compared to the FST's properties. test: Should any unknown values be computed before comparing against the mask? Returns: A 64-bit bitmask representing the requested properties. """ return self._fst.get().Properties(mask, test) cpdef int64 start(self): """ start(self) Returns the start state. """ return self._fst.get().Start() cpdef StateIterator states(self): """ states(self) Returns an iterator over all states in the FST. Returns: A StateIterator object for the FST. See also: `arcs`, `mutable_arcs`. """ return StateIterator(self) cpdef string text(self, _SymbolTable isymbols=None, _SymbolTable osymbols=None, _SymbolTable ssymbols=None, bool acceptor=False, bool show_weight_one=False, missing_sym=b""): """ text(self, isymbols=None, osymbols=None, ssymbols=None, acceptor=False, show_weight_one=False, missing_sym="") Produces a human-readable string representation of the FST. This method generates a human-readable string representation of the FST. The caller may optionally specify SymbolTables used to label input labels, output labels, or state labels, respectively. Args: isymbols: An optional symbol table used to label input symbols. osymbols: An optional symbol table used to label output symbols. ssymbols: An optional symbol table used to label states. acceptor: Should the FST be rendered in acceptor format if possible? show_weight_one: Should weights equivalent to semiring One be printed? missing_symbol: The string to be printed when symbol table lookup fails. Returns: A formatted string representing the machine. """ # Prints FST to stringstream, then returns resulting string. cdef fst.SymbolTable *ssymbols_ptr = NULL if ssymbols is not None: ssymbols_ptr = ssymbols._table cdef stringstream sstrm fst.PrintFst(deref(self._fst), sstrm, b"<pywrapfst>", self._fst.get().InputSymbols() if isymbols is None else isymbols._table, self._fst.get().OutputSymbols() if osymbols is None else osymbols._table, ssymbols_ptr, acceptor, show_weight_one, tostring(missing_sym)) return sstrm.str() cpdef bool verify(self): """ verify(self) Verifies that an FST's contents are sane. Returns: True if the contents are sane, False otherwise. """ return fst.Verify(deref(self._fst)) cpdef string weight_type(self): """ weight_type(self) Provides the FST's weight type. Returns: A string representing the weight type. """ return self._fst.get().WeightType() cpdef void write(self, filename) except *: """ write(self, filename) Serializes FST to a file. This method writes the FST to a file in a binary format. Args: filename: The string location of the output file. Raises: FstIOError: Write failed. """ if not self._fst.get().Write(tostring(filename)): raise FstIOError("Write failed: {!r}".format(filename)) cpdef string write_to_string(self): """ write_to_string(self) Serializes FST to a string. Returns: A string. Raises: FstIOError: Write to string failed. See also: `read_from_string`. """ cdef stringstream sstrm if not self._fst.get().Write(sstrm, "write_to_string"): raise FstIOError("Write to string failed") return sstrm.str() cdef class _MutableFst(_Fst): """ (No constructor.) Mutable FST class, wrapping MutableFstClass. This class extends _Fst by adding mutation operations. """ cdef void _check_mutating_imethod(self) except *: """Checks whether an operation mutating the FST has produced an error. This function is not visible to Python users. """ if self._fst.get().Properties(fst.kError, True) == fst.kError: raise FstOpError("Operation failed") cdef void _add_arc(self, int64 state, Arc arc) except *: if not self._fst.get().ValidStateId(state): raise FstIndexError("State index out of range") if not self._mfst.get().AddArc(state, deref(arc._arc)): raise FstOpError("Incompatible or invalid weight type") self._check_mutating_imethod() def add_arc(self, int64 state, Arc arc): """ add_arc(self, state, arc) Adds a new arc to the FST and return self. Args: state: The integer index of the source state. arc: The arc to add. Returns: self. Raises: FstIndexError: State index out of range. FstOpdexError: Incompatible or invalid weight type. See also: `add_state`. """ self._add_arc(state, arc) return self cpdef int64 add_state(self) except *: """ add_state(self) Adds a new state to the FST and returns the state ID. Returns: The integer index of the new state. See also: `add_arc`, `set_start`, `set_final`. """ cdef int64 result = self._mfst.get().AddState() self._check_mutating_imethod() return result cdef void _arcsort(self, sort_type=b"ilabel") except *: cdef fst.ArcSortType sort_type_enum if not fst.GetArcSortType(tostring(sort_type), addr(sort_type_enum)): raise FstArgError("Unknown sort type {!r}".format(sort_type)) fst.ArcSort(self._mfst.get(), sort_type_enum) self._check_mutating_imethod() def arcsort(self, sort_type=b"ilabel"): """ arcsort(self, sort_type="ilabel") Sorts arcs leaving each state of the FST. This operation destructively sorts arcs leaving each state using either input or output labels. Args: sort_type: Either "ilabel" (sort arcs according to input labels) or "olabel" (sort arcs according to output labels). Returns: self. Raises: FstArgError: Unknown sort type. See also: `topsort`. """ self._arcsort(sort_type) return self cdef void _closure(self, bool closure_plus=False) except *: fst.Closure(self._mfst.get(), fst.GetClosureType(closure_plus)) self._check_mutating_imethod() def closure(self, bool closure_plus=False): """ closure(self, closure_plus=False) Computes concatenative closure. This operation destructively converts the FST to its concatenative closure. If A transduces string x to y with weight a, then the closure transduces x to y with weight a, xx to yy with weight a \otimes a, xxx to yyy with weight a \otimes a \otimes a, and so on. The empty string is also transduced to itself with semiring One if `closure_plus` is False. Args: closure_plus: If False, do not accept the empty string. Returns: self. """ self._closure(closure_plus) return self cdef void _concat(self, _Fst ifst) except *: fst.Concat(self._mfst.get(), deref(ifst._fst)) self._check_mutating_imethod() def concat(self, _Fst ifst): """ concat(self, ifst) Computes the concatenation (product) of two FSTs. This operation destructively concatenates the FST with a second FST. If A transduces string x to y with weight a and B transduces string w to v with weight b, then their concatenation transduces string xw to yv with weight a \otimes b. Args: ifst: The second input FST. Returns: self. """ self._concat(ifst) return self cdef void _connect(self) except *: fst.Connect(self._mfst.get()) self._check_mutating_imethod() def connect(self): """ connect(self) Removes unsuccessful paths. This operation destructively trims the FST, removing states and arcs that are not part of any successful path. Returns: self. """ self._connect() return self cdef void _decode(self, EncodeMapper encoder) except *: fst.Decode(self._mfst.get(), deref(encoder._encoder)) self._check_mutating_imethod() def decode(self, EncodeMapper encoder): """ decode(self, encoder) Decodes encoded labels and/or weights. This operation reverses the encoding performed by `encode`. Args: encoder: An EncodeMapper object used to encode the FST. Returns: self. See also: `encode`. """ self._decode(encoder) return self cdef void _delete_arcs(self, int64 state, size_t n=0) except *: if not (self._mfst.get().DeleteArcs(state, n) if n else self._mfst.get().DeleteArcs(state)): raise FstIndexError("State index out of range") self._check_mutating_imethod() def delete_arcs(self, int64 state, size_t n=0): """ delete_arcs(self, state, n=0) Deletes arcs leaving a particular state. Args: state: The integer index of a state. n: An optional argument indicating how many arcs to be deleted. If this argument is omitted or passed as zero, all arcs from this state are deleted. Returns: self. Raises: FstIndexError: State index out of range. See also: `delete_states`. """ self._delete_arcs(state, n) return self cdef void _delete_states(self, states=None) except *: # Only the former signature has a possible indexing failure. if states: if not self._mfst.get().DeleteStates(<const vector[int64]> states): raise FstIndexError("State index out of range") else: self._mfst.get().DeleteStates() self._check_mutating_imethod() def delete_states(self, states=None): """ delete_states(self, states=None) Deletes states. Args: states: An optional iterable of integer indices of the states to be deleted. If this argument is omitted, all states are deleted. Returns: self. Raises: FstIndexError: State index out of range. See also: `delete_arcs`. """ self._delete_states(states) return self cdef void _encode(self, EncodeMapper encoder) except *: fst.Encode(self._mfst.get(), encoder._encoder.get()) self._check_mutating_imethod() def encode(self, EncodeMapper encoder): """ encode(self, encoder) Encodes labels and/or weights. This operation allows for the representation of a weighted transducer as a weighted acceptor, an unweighted transducer, or an unweighted acceptor by considering the pair (input label, output label), the pair (input label, weight), or the triple (input label, output label, weight) as a single label. Applying this operation mutates the EncodeMapper argument, which can then be used to decode. Args: encoder: An EncodeMapper object to be used as the encoder. Returns: self. See also: `decode`. """ self._encode(encoder) return self cdef void _invert(self) except *: fst.Invert(self._mfst.get()) self._check_mutating_imethod() def invert(self): """ invert(self) Inverts the FST's transduction. This operation destructively inverts the FST's transduction by exchanging input and output labels. Returns: self. """ self._invert() return self cdef void _minimize(self, float delta=fst.kShortestDelta, bool allow_nondet=False) except *: # This runs in-place when the second argument is null. fst.Minimize(self._mfst.get(), NULL, delta, allow_nondet) self._check_mutating_imethod() def minimize(self, float delta=fst.kShortestDelta, bool allow_nondet=False): """ minimize(self, delta=1e-6, allow_nondet=False) Minimizes the FST. This operation destructively performs the minimization of deterministic weighted automata and transducers. If the input FST A is an acceptor, this operation produces the minimal acceptor B equivalent to A, i.e. the acceptor with a minimal number of states that is equivalent to A. If the input FST A is a transducer, this operation internally builds an equivalent transducer with a minimal number of states. However, this minimality is obtained by allowing transition having strings of symbols as output labels, this known in the litterature as a real-time transducer. Such transducers are not directly supported by the library. This function will convert such transducer by expanding each string-labeled transition into a sequence of transitions. This will results in the creation of new states, hence losing the minimality property. Args: delta: Comparison/quantization delta. allow_nondet: Attempt minimization of non-deterministic FST? Returns: self. """ self._minimize(delta, allow_nondet) return self cpdef MutableArcIterator mutable_arcs(self, int64 state): """ mutable_arcs(self, state) Returns a mutable iterator over arcs leaving the specified state. Args: state: The source state ID. Returns: A MutableArcIterator. See also: `arcs`, `states`. """ return MutableArcIterator(self, state) def mutable_input_symbols(self): """ mutable_input_symbols(self) Returns the FST's (mutable) input symbol table, or None if none is present. """ cdef fst.SymbolTable *tst = self._mfst.get().MutableInputSymbols() if tst == NULL: return return _init_MutableFstSymbolTable(tst, self._mfst) def mutable_output_symbols(self): """ mutable_output_symbols(self) Returns the FST's (mutable) output symbol table, or None if none is present. """ cdef fst.SymbolTable *tst = self._mfst.get().MutableOutputSymbols() if tst == NULL: return return _init_MutableFstSymbolTable(tst, self._mfst) cpdef int64 num_states(self): """ num_states(self) Returns the number of states. """ return self._mfst.get().NumStates() cdef void _project(self, bool project_output=False) except *: fst.Project(self._mfst.get(), fst.GetProjectType(project_output)) self._check_mutating_imethod() def project(self, bool project_output=False): """ project(self, project_output=False) Converts the FST to an acceptor using input or output labels. This operation destructively projects an FST onto its domain or range by either copying each arc's input label to its output label (the default) or vice versa. Args: project_output: Should the output labels be projected? Returns: self. See also: `decode`, `encode`, `relabel_pairs`, `relabel_symbols`. """ self._project(project_output) return self cdef void _prune(self, float delta=fst.kDelta, int64 nstate=fst.kNoStateId, weight=None) except *: # Threshold is set to semiring Zero (no pruning) if no weight is specified. cdef fst.WeightClass wc = _get_WeightClass_or_Zero(self.weight_type(), weight) fst.Prune(self._mfst.get(), wc, nstate, delta) self._check_mutating_imethod() def prune(self, float delta=fst.kDelta, int64 nstate=fst.kNoStateId, weight=None): """ prune(self, delta=0.0009765625, nstate=NO_STATE_ID, weight=None) Removes paths with weights below a certain threshold. This operation deletes states and arcs in the input FST that do not belong to a successful path whose weight is no more (w.r.t the natural semiring order) than the threshold t \otimes-times the weight of the shortest path in the input FST. Weights must be commutative and have the path property. Args: delta: Comparison/quantization delta. nstate: State number threshold. weight: A Weight or weight string indicating the desired weight threshold below which paths are pruned; if omitted, no paths are pruned. Returns: self. See also: The constructive variant. """ self._prune(delta, nstate, weight) return self cdef void _push(self, float delta=fst.kDelta, bool remove_total_weight=False, bool to_final=False) except *: fst.Push(self._mfst.get(), fst.GetReweightType(to_final), delta, remove_total_weight) self._check_mutating_imethod() def push(self, float delta=fst.kDelta, bool remove_total_weight=False, bool to_final=False): """ push(self, delta=0.0009765625, remove_total_weight=False, to_final=False) Pushes weights towards the initial or final states. This operation destructively produces an equivalent transducer by pushing the weights towards the initial state or toward the final states. When pushing weights towards the initial state, the sum of the weight of the outgoing transitions and final weight at any non-initial state is equal to one in the resulting machine. When pushing weights towards the final states, the sum of the weight of the incoming transitions at any state is equal to one. Weights need to be left distributive when pushing towards the initial state and right distributive when pushing towards the final states. Args: delta: Comparison/quantization delta. remove_total_weight: If pushing weights, should the total weight be removed? to_final: Push towards final states? Returns: self. See also: The constructive variant, which also supports label pushing. """ self._push(delta, remove_total_weight, to_final) return self cdef void _relabel_pairs(self, ipairs=None, opairs=None) except *: cdef unique_ptr[vector[fst.LabelPair]] _ipairs _ipairs.reset(new vector[fst.LabelPair]()) cdef unique_ptr[vector[fst.LabelPair]] _opairs _opairs.reset(new vector[fst.LabelPair]()) cdef int64 before cdef int64 after if ipairs: for (before, after) in ipairs: _ipairs.get().push_back(fst.LabelPair(before, after)) if opairs: for (before, after) in opairs: _opairs.get().push_back(fst.LabelPair(before, after)) if _ipairs.get().empty() and _opairs.get().empty(): raise FstArgError("No relabeling pairs specified.") fst.Relabel(self._mfst.get(), deref(_ipairs), deref(_opairs)) self._check_mutating_imethod() def relabel_pairs(self, ipairs=None, opairs=None): """ relabel_pairs(self, ipairs=None, opairs=None) Replaces input and/or output labels using pairs of labels. This operation destructively relabels the input and/or output labels of the FST using pairs of the form (old_ID, new_ID); omitted indices are identity-mapped. Args: ipairs: An iterable containing (older index, newer index) integer pairs. opairs: An iterable containing (older index, newer index) integer pairs. Returns: self. Raises: FstArgError: No relabeling pairs specified. See also: `decode`, `encode`, `project`, `relabel_tables`. """ self._relabel_pairs(ipairs, opairs) return self cdef void _relabel_tables(self, _SymbolTable old_isymbols=None, _SymbolTable new_isymbols=None, unknown_isymbol=b"", bool attach_new_isymbols=True, _SymbolTable old_osymbols=None, _SymbolTable new_osymbols=None, unknown_osymbol=b"", bool attach_new_osymbols=True) except *: if new_isymbols is None and new_osymbols is None: raise FstArgError("No new SymbolTables specified") cdef fst.SymbolTable *new_isymbols_ptr = NULL if new_isymbols is not None: new_isymbols_ptr = new_isymbols._table cdef fst.SymbolTable *new_osymbols_ptr = NULL if new_osymbols is not None: new_osymbols_ptr = new_osymbols._table fst.Relabel(self._mfst.get(), self._fst.get().InputSymbols() if old_isymbols is None else old_isymbols._table, new_isymbols_ptr, tostring(unknown_isymbol), attach_new_isymbols, self._fst.get().OutputSymbols() if old_osymbols is None else old_osymbols._table, new_osymbols_ptr, tostring(unknown_osymbol), attach_new_osymbols) self._check_mutating_imethod() def relabel_tables(self, _SymbolTable old_isymbols=None, _SymbolTable new_isymbols=None, unknown_isymbol=b"", bool attach_new_isymbols=True, _SymbolTable old_osymbols=None, _SymbolTable new_osymbols=None, unknown_osymbol=b"", bool attach_new_osymbols=True): """ relabel_tables(self, old_isymbols=None, new_isymbols=None, unknown_isymbol="", attach_new_isymbols=True, old_osymbols=None, new_osymbols=None, unknown_osymbol="", attach_new_osymbols=True) Replaces input and/or output labels using SymbolTables. This operation destructively relabels the input and/or output labels of the FST using user-specified symbol tables; omitted symbols are identity-mapped. Args: old_isymbols: The old SymbolTable for input labels, defaulting to the FST's input symbol table. new_isymbols: A SymbolTable used to relabel the input labels unknown_isymbol: Input symbol to use to relabel OOVs (if empty, OOVs raise an exception) attach_new_isymbols: Should new_isymbols be made the FST's input symbol table? old_osymbols: The old SymbolTable for output labels, defaulting to the FST's output symbol table. new_osymbols: A SymbolTable used to relabel the output labels. unknown_osymbol: Outnput symbol to use to relabel OOVs (if empty, OOVs raise an exception) attach_new_isymbols: Should new_osymbols be made the FST's output symbol table? Returns: self. Raises: FstArgError: No SymbolTable specified. See also: `decode`, `encode`, `project`, `relabel_pairs`. """ self._relabel_tables(old_isymbols, new_isymbols, unknown_isymbol, attach_new_isymbols, old_osymbols, new_osymbols, unknown_osymbol, attach_new_osymbols) return self cdef void _reserve_arcs(self, int64 state, size_t n) except *: if not self._mfst.get().ReserveArcs(state, n): raise FstIndexError("State index out of range") self._check_mutating_imethod() def reserve_arcs(self, int64 state, size_t n): """ reserve_arcs(self, state, n) Reserve n arcs at a particular state (best effort). Args: state: The integer index of a state. n: The number of arcs to reserve. Returns: self. Raises: FstIndexError: State index out of range. See also: `reserve_states`. """ self._reserve_arcs(state, n) return self cdef void _reserve_states(self, int64 n) except *: self._mfst.get().ReserveStates(n) self._check_mutating_imethod() def reserve_states(self, int64 n): """ reserve_states(self, n) Reserve n states (best effort). Args: n: The number of states to reserve. Returns: self. See also: `reserve_arcs`. """ self._reserve_states(n) return self cdef void _reweight(self, potentials, bool to_final=False) except *: cdef unique_ptr[vector[fst.WeightClass]] _potentials _potentials.reset(new vector[fst.WeightClass]()) cdef string weight_type = self.weight_type() for weight in potentials: _potentials.get().push_back(_get_WeightClass_or_One(self.weight_type(), weight)) fst.Reweight(self._mfst.get(), deref(_potentials), fst.GetReweightType(to_final)) self._check_mutating_imethod() def reweight(self, potentials, bool to_final=False): """ reweight(self, potentials, to_final=False) Reweights an FST using an iterable of potentials. This operation destructively reweights an FST according to the potentials and in the direction specified by the user. An arc of weight w, with an origin state of potential p and destination state of potential q, is reweighted by p^{-1} \otimes (w \otimes q) when reweighting towards the initial state, and by (p \otimes w) \otimes q^{-1} when reweighting towards the final states. The weights must be left distributive when reweighting towards the initial state and right distributive when reweighting towards the final states (e.g., TropicalWeight and LogWeight). Args: potentials: An iterable of Weight or weight strings. to_final: Push towards final states? Returns: self. """ self._reweight(potentials, to_final) return self cdef void _rmepsilon(self, queue_type=b"auto", bool connect=True, weight=None, int64 nstate=fst.kNoStateId, float delta=fst.kShortestDelta) except *: cdef fst.WeightClass wc = _get_WeightClass_or_Zero(self.weight_type(), weight) cdef unique_ptr[fst.RmEpsilonOptions] opts opts.reset(new fst.RmEpsilonOptions(_get_queue_type(tostring(queue_type)), connect, wc, nstate, delta)) fst.RmEpsilon(self._mfst.get(), deref(opts)) self._check_mutating_imethod() def rmepsilon(self, queue_type=b"auto", bool connect=True, weight=None, int64 nstate=fst.kNoStateId, float delta=fst.kShortestDelta): """ rmepsilon(self, queue_type="auto", connect=True, weight=None, nstate=NO_STATE_ID, delta=1e-6): Removes epsilon transitions. This operation destructively removes epsilon transitions, i.e., those where both input and output labels are epsilon) from an FST. Args: queue_type: A string matching a known queue type; one of: "auto", "fifo", "lifo", "shortest", "state", "top". connect: Should output be trimmed? weight: A Weight or weight string indicating the desired weight threshold below which paths are pruned; if omitted, no paths are pruned. nstate: State number threshold. delta: Comparison/quantization delta. Returns: self. """ self._rmepsilon(queue_type, connect, weight, nstate, delta) return self cdef void _set_final(self, int64 state, weight=None) except *: if not self._mfst.get().ValidStateId(state): raise FstIndexError("State index out of range") cdef fst.WeightClass wc = _get_WeightClass_or_One(self.weight_type(), weight) if not self._mfst.get().SetFinal(state, wc): raise FstOpError("Incompatible or invalid weight") self._check_mutating_imethod() def set_final(self, int64 state, weight=None): """ set_final(self, state, weight) Sets the final weight for a state. Args: state: The integer index of a state. weight: A Weight or weight string indicating the desired final weight; if omitted, it is set to semiring One. Returns: self. Raises: FstIndexError: State index out of range. FstOpError: Incompatible or invalid weight. See also: `set_start`. """ self._set_final(state, weight) return self cdef void _set_input_symbols(self, _SymbolTable syms) except *: if syms is None: self._mfst.get().SetInputSymbols(NULL) return self._mfst.get().SetInputSymbols(syms._table) self._check_mutating_imethod() def set_input_symbols(self, _SymbolTable syms): """ set_input_symbols(self, syms) Sets the input symbol table. Passing None as a value will delete the input symbol table. Args: syms: A SymbolTable. Returns: self. See also: `set_output_symbols`. """ self._set_input_symbols(syms) return self cdef void _set_output_symbols(self, _SymbolTable syms) except *: if syms is None: self._mfst.get().SetOutputSymbols(NULL) return self._mfst.get().SetOutputSymbols(syms._table) self._check_mutating_imethod() def set_output_symbols(self, _SymbolTable syms): """ set_output_symbols(self, syms) Sets the output symbol table. Passing None as a value will delete the output symbol table. Args: syms: A SymbolTable. Returns: self. See also: `set_input_symbols`. """ self._set_output_symbols(syms) return self cdef void _set_properties(self, uint64 props, uint64 mask): self._mfst.get().SetProperties(props, mask) def set_properties(self, uint64 props, uint64 mask): """ set_properties(self, props, mask) Sets the properties bits. Args: props: The properties to be set. mask: A mask to be applied to the `props` argument before setting the FST's properties. Returns: self. """ self._set_properties(props, mask) return self cdef void _set_start(self, int64 state) except *: if not self._mfst.get().SetStart(state): raise FstIndexError("State index out of range") self._check_mutating_imethod() def set_start(self, int64 state): """ set_start(self, state) Sets a state to be the initial state state. Args: state: The integer index of a state. Returns: self. Raises: FstIndexError: State index out of range. See also: `set_final`. """ self._set_start(state) return self cdef void _topsort(self) except *: # TopSort returns False if the FST is cyclic, and thus can't be TopSorted. if not fst.TopSort(self._mfst.get()): logging.warning("Cannot topsort cyclic FST.") self._check_mutating_imethod() def topsort(self): """ topsort(self) Sorts transitions by state IDs. This operation destructively topologically sorts the FST, if it is acyclic; otherwise it remains unchanged. Once sorted, all transitions are from lower state IDs to higher state IDs Returns: self. See also: `arcsort`. """ self._topsort() return self cdef void _union(self, _Fst ifst) except *: fst.Union(self._mfst.get(), deref(ifst._fst)) self._check_mutating_imethod() def union(self, _Fst ifst): """ union(self, ifst) Computes the union (sum) of two FSTs. This operation computes the union (sum) of two FSTs. If A transduces string x to y with weight a and B transduces string w to v with weight b, then their union transduces x to y with weight a and w to v with weight b. Args: ifst: The second input FST. Returns: self. """ self._union(ifst) return self # Pseudo-constructors for _Fst and _MutableFst. # # _init_Fst and _init_MutableFst use an FstClass pointer to instantiate _Fst # and _MutableFst objects, respectively. The latter function is only safe to # call when the FST being wrapped is known to be kMutable. The caller can # safely use it when they have either checked this bit (e.g., by using # _init_XFst) or have themselves constructed a mutable container for the # FstClass pointer they're passing (e.g., most of the constructive operations, # storing their results in a VectorFstClass, a derivative of MutableFstClass). # # _create_Fst constructs an empty VectorFstClass of a user-specified arc type, # and passes this pointer to _init_MutableFst. # # _read_Fst reads an FST from disk, performing FST conversion if requested, and # then passes this pointer to _init_XFst. # # The Python class Fst provides a wrapper for these two operations. The former # can be accessed by calling Fst(...), which acts like a class method, and the # latter via Fst.read(...), which acts like a static method. This is a bit # nasty, but totally hidden from the Python user. cdef _Fst _init_Fst(FstClass_ptr tfst): if tfst.Properties(fst.kError, True): raise FstOpError("Operation failed") cdef _Fst ofst = _Fst.__new__(_Fst) ofst._fst.reset(tfst) return ofst cdef _MutableFst _init_MutableFst(MutableFstClass_ptr tfst): if tfst.Properties(fst.kError, True): raise FstOpError("Operation failed") cdef _MutableFst ofst = _MutableFst.__new__(_MutableFst) ofst._fst.reset(tfst) # Makes a copy of it as the derived type! Cool. ofst._mfst = static_pointer_cast[fst.MutableFstClass, fst.FstClass](ofst._fst) return ofst cdef _Fst _init_XFst(FstClass_ptr tfst): if tfst.Properties(fst.kMutable, True): return _init_MutableFst(static_cast[MutableFstClass_ptr](tfst)) else: return _init_Fst(tfst) cdef _MutableFst _create_Fst(arc_type=b"standard"): cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(tostring(arc_type))) if tfst.get() == NULL: raise FstOpError("Unknown arc type: {!r}".format(arc_type)) return _init_MutableFst(tfst.release()) cpdef _Fst _read(filename): cdef unique_ptr[fst.FstClass] tfst tfst.reset(fst.FstClass.Read(tostring(filename))) if tfst.get() == NULL: raise FstIOError("Read failed: {!r}".format(filename)) return _init_XFst(tfst.release()) cpdef _Fst _read_from_string(state): cdef stringstream sstrm sstrm << tostring(state) cdef unique_ptr[fst.FstClass] tfst tfst.reset(fst.FstClass.ReadFromStream(sstrm, b"<pywrapfst>")) if tfst.get() == NULL: raise FstIOError("Read failed: <string>") return _init_XFst(tfst.release()) class Fst(object): """ Fst(arc_type="standard") Constructs an empty FST. Args: arc_type: A string indicating the arc type. Raises: FstError: Unknown arc type. Raises: FstOpError: operation failed. """ def __new__(cls, arc_type=b"standard"): return _create_Fst(arc_type) @staticmethod def read(filename): """ read(filename): Reads an FST from a file. Args: filename: The string location of the input file. Returns: An FST object. Raises: FstIOError: Read failed. """ return _read(filename) @staticmethod def read_from_string(state): """ read_from_string(string, fst_type=None) Reads an FST from a serialized string. Args: state: A string containing the serialized FST. Returns: An FST object. Raises: FstIOError: Read failed. FstOpError: Read-time conversion failed. See also: `write_to_string`. """ return _read_from_string(state) ## FST constants. NO_LABEL = fst.kNoLabel NO_STATE_ID = fst.kNoStateId # TODO(kbg): Figure out how to access static class variables so I don't have # to do it this way. NO_SYMBOL = kNoSymbol ## FST properties. EXPANDED = fst.kExpanded MUTABLE = fst.kMutable ERROR = fst.kError ACCEPTOR = fst.kAcceptor NOT_ACCEPTOR = fst.kNotAcceptor I_DETERMINISTIC = fst.kIDeterministic NON_I_DETERMINISTIC = fst.kNonIDeterministic O_DETERMINISTIC = fst.kODeterministic NON_O_DETERMINISTIC = fst.kNonODeterministic EPSILONS = fst.kEpsilons NO_EPSILONS = fst.kNoEpsilons I_EPSILONS = fst.kIEpsilons NO_I_EPSILONS = fst.kNoIEpsilons O_EPSILONS = fst.kOEpsilons NO_O_EPSILONS = fst.kNoOEpsilons I_LABEL_SORTED = fst.kILabelSorted NOT_I_LABEL_SORTED = fst.kNotILabelSorted O_LABEL_SORTED = fst.kOLabelSorted NOT_O_LABEL_SORTED = fst.kNotOLabelSorted WEIGHTED = fst.kWeighted UNWEIGHTED = fst.kUnweighted CYCLIC = fst.kCyclic ACYCLIC = fst.kAcyclic INITIAL_CYCLIC = fst.kInitialCyclic INITIAL_ACYCLIC = fst.kInitialAcyclic TOP_SORTED = fst.kTopSorted NOT_TOP_SORTED = fst.kNotTopSorted ACCESSIBLE = fst.kAccessible NOT_ACCESSIBLE = fst.kNotAccessible COACCESSIBLE = fst.kCoAccessible NOT_COACCESSIBLE = fst.kNotCoAccessible STRING = fst.kString NOT_STRING = fst.kNotString WEIGHTED_CYCLES = fst.kWeightedCycles UNWEIGHTED_CYCLES = fst.kUnweightedCycles NULL_PROPERTIES = fst.kNullProperties COPY_PROPERTIES = fst.kCopyProperties INTRINSIC_PROPERTIES = fst.kIntrinsicProperties EXTRINSIC_PROPERTIES = fst.kExtrinsicProperties SET_START_PROPERTIES = fst.kSetStartProperties SET_FINAL_PROPERTIES = fst.kSetFinalProperties ADD_STATE_PROPERTIES = fst.kAddStateProperties ADD_ARC_PROPERTIES = fst.kAddArcProperties SET_ARC_PROPERTIES = fst.kSetArcProperties DELETE_STATE_PROPERTIES = fst.kDeleteStatesProperties DELETE_ARC_PROPERTIES = fst.kDeleteArcsProperties STATE_SORT_PROPERTIES = fst.kStateSortProperties ARC_SORT_PROPERTIES = fst.kArcSortProperties I_LABEL_INVARIANT_PROPERTIES = fst.kILabelInvariantProperties O_LABEL_INVARIANT_PROPERTIES = fst.kOLabelInvariantProperties WEIGHT_INVARIANT_PROPERTIES = fst.kWeightInvariantProperties ADD_SUPERFINAL_PROPERTIES = fst.kAddSuperFinalProperties RM_SUPERFINAL_PROPERTIES = fst.kRmSuperFinalProperties BINARY_PROPERTIES = fst.kBinaryProperties TRINARY_PROPERTIES = fst.kTrinaryProperties POS_TRINARY_PROPERTIES = fst.kPosTrinaryProperties NEG_TRINARY_PROPERTIES = fst.kNegTrinaryProperties FST_PROPERTIES = fst.kFstProperties ## Arc iterator properties. ARC_I_LABEL_VALUE = fst.kArcILabelValue ARC_O_LABEL_VALUE = fst.kArcOLabelValue ARC_WEIGHT_VALUE = fst.kArcWeightValue ARC_NEXT_STATE_VALUE = fst.kArcNextStateValue ARC_NO_CACHE = fst.kArcNoCache ARC_VALUE_FLAGS = fst.kArcValueFlags ARC_FLAGS = fst.kArcFlags ## EncodeMapper properties. ENCODE_LABELS = fst.kEncodeLabels ENCODE_WEIGHTS = fst.kEncodeWeights ENCODE_FLAGS = fst.kEncodeFlags ## Arc, ArcIterator, and MutableArcIterator. cdef class Arc(object): """ Arc(ilabel, olabel, weight, nextstate) This class represents an arc while remaining agnostic about the underlying arc type. Attributes of the arc can be accessed or mutated, and the arc can be copied. Attributes: ilabel: The input label. olabel: The output label. weight: The arc weight. nextstate: The destination state for the arc. """ def __repr__(self): return "<Arc at 0x{:x}>".format(id(self)) def __init__(self, int64 ilabel, int64 olabel, weight, int64 nextstate): cdef fst.WeightClass wc = _get_WeightClass_or_One(b"tropical", weight) self._arc.reset(new fst.ArcClass(ilabel, olabel, wc, nextstate)) cpdef Arc copy(self): return Arc(self.ilabel, self.olabel, self.weight, self.nextstate) property ilabel: def __get__(self): return deref(self._arc).ilabel def __set__(self, int64 value): deref(self._arc).ilabel = value property olabel: def __get__(self): return deref(self._arc).olabel def __set__(self, int64 value): deref(self._arc).olabel = value property weight: def __get__(self): cdef Weight weight = Weight.__new__(Weight) weight._weight.reset(new fst.WeightClass(deref(self._arc).weight)) return weight def __set__(self, weight): deref(self._arc).weight = _get_WeightClass_or_One(b"tropical", weight) property nextstate: def __get__(self): return deref(self._arc).nextstate def __set__(self, int64 value): deref(self._arc).nextstate = value cdef Arc _init_Arc(const fst.ArcClass &arc): cdef Weight weight = Weight.__new__(Weight) weight._weight.reset(new fst.WeightClass(arc.weight)) return Arc(arc.ilabel, arc.olabel, weight, arc.nextstate) cdef class ArcIterator(object): """ ArcIterator(ifst, state) This class is used for iterating over the arcs leaving some state of an FST. """ def __repr__(self): return "<ArcIterator at 0x{:x}>".format(id(self)) def __init__(self, _Fst ifst, int64 state): if not ifst._fst.get().ValidStateId(state): raise FstIndexError("State index out of range") # Makes copy of the shared_ptr, potentially extending the FST's lifetime. self._fst = ifst._fst self._aiter.reset(new fst.ArcIteratorClass(deref(self._fst), state)) # This just registers this class as a possible iterator. def __iter__(self): return self # Magic method used to get a Pythonic API out of the C++ API. def __next__(self): if self.done(): raise StopIteration result = self.value() self.next() return result cpdef bool done(self): """ done(self) Indicates whether the iterator is exhausted or not. Returns: True if the iterator is exhausted, False otherwise. """ return self._aiter.get().Done() cpdef uint32 flags(self): """ flags(self) Returns the current iterator behavioral flags. Returns: The current iterator behavioral flags as an integer. """ return self._aiter.get().Flags() cpdef void next(self): """ next(self) Advances the iterator. """ self._aiter.get().Next() cpdef size_t position(self): """ position(self) Returns the position of the iterator. Returns: The iterator's position, expressed as an integer. """ return self._aiter.get().Position() cpdef void reset(self): """ reset(self) Resets the iterator to the initial position. """ self._aiter.get().Reset() cpdef void seek(self, size_t a): """ seek(self, a) Advance the iterator to a new position. Args: a: The position to seek to. """ self._aiter.get().Seek(a) cpdef void set_flags(self, uint32 flags, uint32 mask): """ set_flags(self, flags, mask) Sets the current iterator behavioral flags. Args: flags: The properties to be set. mask: A mask to be applied to the `flags` argument before setting them. """ self._aiter.get().SetFlags(flags, mask) cpdef object value(self): """ value(self) Returns the current arc. """ return _init_Arc(self._aiter.get().Value()) cdef class MutableArcIterator(object): """ MutableArcIterator(ifst, state) This class is used for iterating over the arcs leaving some state of an FST, also permitting mutation of the current arc. """ def __repr__(self): return "<MutableArcIterator at 0x{:x}>".format(id(self)) def __init__(self, _MutableFst ifst, int64 state): if not ifst._fst.get().ValidStateId(state): raise FstIndexError("State index out of range") # Makes copy of the shared_ptr, potentially extending the FST's lifetime. self._mfst = ifst._mfst self._aiter.reset(new fst.MutableArcIteratorClass(ifst._mfst.get(), state)) cpdef bool done(self): """ done(self) Indicates whether the iterator is exhausted or not. Returns: True if the iterator is exhausted, False otherwise. """ return self._aiter.get().Done() cpdef uint32 flags(self): """ flags(self) Returns the current iterator behavioral flags. Returns: The current iterator behavioral flags as an integer. """ return self._aiter.get().Flags() cpdef void next(self): """ next(self) Advances the iterator. """ self._aiter.get().Next() cpdef size_t position(self): """ position(self) Returns the position of the iterator. Returns: The iterator's position, expressed as an integer. """ return self._aiter.get().Position() cpdef void reset(self): """ reset(self) Resets the iterator to the initial position. """ self._aiter.get().Reset() cpdef void seek(self, size_t a): """ seek(self, a) Advance the iterator to a new position. Args: a: The position to seek to. """ self._aiter.get().Seek(a) cpdef void set_flags(self, uint32 flags, uint32 mask): """ set_flags(self, flags, mask) Sets the current iterator behavioral flags. Args: flags: The properties to be set. mask: A mask to be applied to the `flags` argument before setting them. """ self._aiter.get().SetFlags(flags, mask) cpdef void set_value(self, Arc arc): """ set_value(self, arc) Replace the current arc with a new arc. Args: arc: The arc to replace the current arc with. """ self._aiter.get().SetValue(deref(arc._arc)) cpdef object value(self): """ value(self) Returns the current arc. """ return _init_Arc(self._aiter.get().Value()) ## StateIterator. cdef class StateIterator(object): """ StateIterator(ifst) This class is used for iterating over the states in an FST. """ def __repr__(self): return "<StateIterator at 0x{:x}>".format(id(self)) def __init__(self, _Fst ifst): # Makes copy of the shared_ptr, potentially extending the FST's lifetime. self._fst = ifst._fst self._siter.reset(new fst.StateIteratorClass(deref(self._fst))) # This just registers this class as a possible iterator. def __iter__(self): return self # Magic method used to get a Pythonic API out of the C++ API. def __next__(self): if self.done(): raise StopIteration cdef int64 result = self.value() self.next() return result cpdef bool done(self): """ done(self) Indicates whether the iterator is exhausted or not. Returns: True if the iterator is exhausted, False otherwise. """ return self._siter.get().Done() cpdef void next(self): """ next(self) Advances the iterator. """ self._siter.get().Next() cpdef void reset(self): """ reset(self) Resets the iterator to the initial position. """ self._siter.get().Reset() cpdef int64 value(self): """ value(self) Returns the current state index. """ return self._siter.get().Value() ## FST operations. cdef _Fst _map(_Fst ifst, float delta=fst.kDelta, map_type=b"identity", double power=1., weight=None): cdef fst.MapType map_type_enum if not fst.GetMapType(tostring(map_type), addr(map_type_enum)): raise FstArgError("Unknown map type: {!r}".format(map_type)) cdef fst.WeightClass wc = (_get_WeightClass_or_One(ifst.weight_type(), weight) if map_type_enum == fst.TIMES_MAPPER else _get_WeightClass_or_Zero(ifst.weight_type(), weight)) return _init_XFst(fst.Map(deref(ifst._fst), map_type_enum, delta, power, wc)) cpdef _Fst arcmap(_Fst ifst, float delta=fst.kDelta, map_type=b"identity", double power=1., weight=None): """ arcmap(ifst, delta=0.0009765625, map_type="identity", weight=None) Constructively applies a transform to all arcs and final states. This operation transforms each arc and final state in the input FST using one of the following: * identity: maps to self. * input_epsilon: replaces all input labels with epsilon. * invert: reciprocates all non-Zero weights. * float_power: raises all weights to a floating-point power. * output_epsilon: replaces all output labels with epsilon. * quantize: quantizes weights. * plus: adds a constant to all weights. * power: raises all weights to an integral power. * rmweight: replaces all non-Zero weights with 1. * superfinal: redirects final states to a new superfinal state. * times: right-multiplies a constant to all weights. * to_log: converts weights to the log semiring. * to_log64: converts weights to the log64 semiring. * to_standard: converts weights to the tropical ("standard") semiring. Args: ifst: The input FST. delta: Comparison/quantization delta (ignored unless `map_type` is `quantize`). map_type: A string matching a known mapping operation (see above). power: A positive scalar or integer power; ignored unless `map_type` is `float_power` or `power` (in which case it defaults to 1). weight: A Weight or weight string passed to the arc-mapper; ignored unless `map_type` is `plus` (in which case it defaults to semiring Zero) or `times` (in which case it defaults to semiring One). Returns: An FST with arcs and final states remapped. Raises: FstArgError: Unknown map type. See also: `statemap`. """ return _map(ifst, delta, map_type, power, weight) cpdef _MutableFst compose(_Fst ifst1, _Fst ifst2, compose_filter=b"auto", bool connect=True): """ compose(ifst1, ifst2, compose_filter="auto", connect=True) Constructively composes two FSTs. This operation computes the composition of two FSTs. If A transduces string x to y with weight a and B transduces y to z with weight b, then their composition transduces string x to z with weight a \otimes b. The output labels of the first transducer or the input labels of the second transducer must be sorted (or otherwise support appropriate matchers). Args: ifst1: The first input FST. ifst2: The second input FST. compose_filter: A string matching a known composition filter; one of: "alt_sequence", "auto", "match", "null", "sequence", "trivial". connect: Should output be trimmed? Returns: An FST. See also: `arcsort`. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst1.arc_type())) cdef unique_ptr[fst.ComposeOptions] opts opts.reset(new fst.ComposeOptions(connect, _get_compose_filter(tostring(compose_filter)))) fst.Compose(deref(ifst1._fst), deref(ifst2._fst), tfst.get(), deref(opts)) return _init_MutableFst(tfst.release()) cpdef _Fst convert(_Fst ifst, fst_type=None): """ convert(ifst, fst_type=None) Constructively converts an FST to a new internal representation. Args: ifst: The input FST. fst_type: A string indicating the FST type to convert to, or None if no conversion is desired. Returns: An equivalent Fst converted to the desired FST type. Raises: FstOpError: Conversion failed. """ cdef string fst_type_string = b"" if fst_type is None else tostring(fst_type) cdef unique_ptr[fst.FstClass] tfst tfst.reset(fst.Convert(deref(ifst._fst), fst_type_string)) # Script-land Convert returns a null pointer to signal failure. if tfst.get() == NULL: raise FstOpError("Conversion to {!r} failed".format(fst_type)) return _init_XFst(tfst.release()) cpdef _MutableFst determinize(_Fst ifst, float delta=fst.kShortestDelta, det_type=b"functional", int64 nstate=fst.kNoStateId, int64 subsequential_label=0, weight=None, bool increment_subsequential_label=False): """ determinize(ifst, delta=1e-6, det_type="functional", nstate=NO_STATE_ID, subsequential_label=0, weight=None, incremental_subsequential_label=False) Constructively determinizes a weighted FST. This operations creates an equivalent FST that has the property that no state has two transitions with the same input label. For this algorithm, epsilon transitions are treated as regular symbols (cf. `rmepsilon`). Args: ifst: The input FST. delta: Comparison/quantization delta. det_type: Type of determinization; one of: "functional" (input transducer is functional), "nonfunctional" (input transducer is not functional) and disambiguate" (input transducer is not functional but only keep the min of ambiguous outputs). nstate: State number threshold. subsequential_label: Input label of arc corresponding to residual final output when producing a subsequential transducer. weight: A Weight or weight string indicating the desired weight threshold below which paths are pruned; if omitted, no paths are pruned. increment_subsequential_label: Increment subsequential when creating several arcs for the residual final output at a given state. Returns: An equivalent deterministic FST. Raises: FstArgError: Unknown determinization type. See also: `disambiguate`, `rmepsilon`. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) # Threshold is set to semiring Zero (no pruning) if weight unspecified. cdef fst.WeightClass wc = _get_WeightClass_or_Zero(ifst.weight_type(), weight) cdef fst.DeterminizeType determinize_type_enum if not fst.GetDeterminizeType(tostring(det_type), addr(determinize_type_enum)): raise FstArgError("Unknown determinization type: {!r}".format(det_type)) cdef unique_ptr[fst.DeterminizeOptions] opts opts.reset(new fst.DeterminizeOptions(delta, wc, nstate, subsequential_label, determinize_type_enum, increment_subsequential_label)) fst.Determinize(deref(ifst._fst), tfst.get(), deref(opts)) return _init_MutableFst(tfst.release()) cpdef _MutableFst difference(_Fst ifst1, _Fst ifst2, compose_filter=b"auto", bool connect=True): """ difference(ifst1, ifst2, compose_filter="auto", connect=True) Constructively computes the difference of two FSTs. This operation computes the difference between two FSAs. Only strings that are in the first automaton but not in second are retained in the result. The first argument must be an acceptor; the second argument must be an unweighted, epsilon-free, deterministic acceptor. The output labels of the first transducer or the input labels of the second transducer must be sorted (or otherwise support appropriate matchers). Args: ifst1: The first input FST. ifst2: The second input FST. compose_filter: A string matching a known composition filter; one of: "alt_sequence", "auto", "match", "null", "sequence", "trivial". connect: Should the output FST be trimmed? Returns: An FST representing the difference of the FSTs. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst1.arc_type())) cdef unique_ptr[fst.ComposeOptions] opts opts.reset(new fst.ComposeOptions(connect, _get_compose_filter( tostring(compose_filter)))) fst.Difference(deref(ifst1._fst), deref(ifst2._fst), tfst.get(), deref(opts)) return _init_MutableFst(tfst.release()) cpdef _MutableFst disambiguate(_Fst ifst, float delta=fst.kDelta, int64 nstate=fst.kNoStateId, int64 subsequential_label=0, weight=None): """ disambiguate(ifst, delta=0.0009765625, nstate=NO_STATE_ID, subsequential_label=0, weight=None): Constructively disambiguates a weighted transducer. This operation disambiguates a weighted transducer. The result will be an equivalent FST that has the property that no two successful paths have the same input labeling. For this algorithm, epsilon transitions are treated as regular symbols (cf. `rmepsilon`). Args: ifst: The input FST. delta: Comparison/quantization delta. nstate: State number threshold. subsequential_label: Input label of arc corresponding to residual final output when producing a subsequential transducer. weight: A Weight or weight string indicating the desired weight threshold below which paths are pruned; if omitted, no paths are pruned. Returns: An equivalent disambiguated FST. See also: `determinize`, `rmepsilon`. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) # Threshold is set to semiring Zero (no pruning) if no weight is specified. cdef fst.WeightClass wc = _get_WeightClass_or_Zero(ifst.weight_type(), weight) cdef unique_ptr[fst.DisambiguateOptions] opts opts.reset(new fst.DisambiguateOptions(delta, wc, nstate, subsequential_label)) fst.Disambiguate(deref(ifst._fst), tfst.get(), deref(opts)) return _init_MutableFst(tfst.release()) cpdef _MutableFst epsnormalize(_Fst ifst, bool eps_norm_output=False): """ epsnormalize(ifst, eps_norm_output=False) Constructively epsilon-normalizes an FST. This operation creates an equivalent FST that is epsilon-normalized. An acceptor is epsilon-normalized if it it is epsilon-removed (cf. `rmepsilon`). A transducer is input epsilon-normalized if, in addition, along any path, all arcs with epsilon input labels follow all arcs with non-epsilon input labels. Output epsilon-normalized is defined similarly. The input FST must be functional. Args: ifst: The input FST. eps_norm_output: Should the FST be output epsilon-normalized? Returns: An equivalent epsilon-normalized FST. See also: `rmepsilon`. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) fst.EpsNormalize(deref(ifst._fst), tfst.get(), fst.EPS_NORM_OUTPUT if eps_norm_output else fst.EPS_NORM_INPUT) return _init_MutableFst(tfst.release()) cpdef bool equal(_Fst ifst1, _Fst ifst2, float delta=fst.kDelta): """ equal(ifst1, ifst2, delta=0.0009765625) Are two FSTs equal? This function tests whether two FSTs have the same states with the same numbering and the same transitions with the same labels and weights in the same order. Args: ifst1: The first input FST. ifst2: The second input FST. delta: Comparison/quantization delta. Returns: True if the FSTs satisfy the above condition, else False. See also: `equivalent`, `isomorphic`, `randequivalent`. """ return fst.Equal(deref(ifst1._fst), deref(ifst2._fst), delta) cpdef bool equivalent(_Fst ifst1, _Fst ifst2, float delta=fst.kDelta) except *: """ equivalent(ifst1, ifst2, delta=0.0009765625) Are the two acceptors equivalent? This operation tests whether two epsilon-free deterministic weighted acceptors are equivalent, that is if they accept the same strings with the same weights. Args: ifst1: The first input FST. ifst2: The second input FST. delta: Comparison/quantization delta. Returns: True if the FSTs satisfy the above condition, else False. See also: `equal`, `isomorphic`, `randequivalent`. """ return fst.Equivalent(deref(ifst1._fst), deref(ifst2._fst), delta) cpdef _MutableFst intersect(_Fst ifst1, _Fst ifst2, compose_filter=b"auto", bool connect=True): """ intersect(ifst1, ifst2, compose_filter="auto", connect=True) Constructively intersects two FSTs. This operation computes the intersection (Hadamard product) of two FSTs. Only strings that are in both automata are retained in the result. The two arguments must be acceptors. One of the arguments must be label-sorted (or otherwise support appropriate matchers). Args: ifst1: The first input FST. ifst2: The second input FST. compose_filter: A string matching a known composition filter; one of: "alt_sequence", "auto", "match", "null", "sequence", "trivial". connect: Should output be trimmed? Returns: An intersected FST. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst1.arc_type())) cdef unique_ptr[fst.ComposeOptions] opts opts.reset(new fst.ComposeOptions(connect, _get_compose_filter(tostring(compose_filter)))) fst.Intersect(deref(ifst1._fst), deref(ifst2._fst), tfst.get(), deref(opts)) return _init_MutableFst(tfst.release()) cpdef bool isomorphic(_Fst ifst1, _Fst ifst2, float delta=fst.kDelta): """ isomorphic(ifst1, ifst2, delta=0.0009765625) Are the two acceptors isomorphic? This operation determines if two transducers with a certain required determinism have the same states, irrespective of numbering, and the same transitions with the same labels and weights, irrespective of ordering. In other words, FSTs A, B are isomorphic if and only if the states of A can be renumbered and the transitions leaving each state reordered so the two are equal (according to the definition given in `equal`). Args: ifst1: The first input FST. ifst2: The second input FST. delta: Comparison/quantization delta. Returns: True if the two transducers satisfy the above condition, else False. See also: `equal`, `equivalent`, `randequivalent`. """ return fst.Isomorphic(deref(ifst1._fst), deref(ifst2._fst), delta) cpdef _MutableFst prune(_Fst ifst, float delta=fst.kDelta, int64 nstate=fst.kNoStateId, weight=None): """ prune(ifst, delta=0.0009765625, nstate=NO_STATE_ID, weight=None) Constructively removes paths with weights below a certain threshold. This operation deletes states and arcs in the input FST that do not belong to a successful path whose weight is no more (w.r.t the natural semiring order) than the threshold t \otimes-times the weight of the shortest path in the input FST. Weights must be commutative and have the path property. Args: ifst: The input FST. delta: Comparison/quantization delta. nstate: State number threshold. weight: A Weight or weight string indicating the desired weight threshold below which paths are pruned; if omitted, no paths are pruned. Returns: A pruned FST. See also: The destructive variant. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) cdef fst.WeightClass wc = _get_WeightClass_or_Zero(ifst.weight_type(), weight) fst.Prune(deref(ifst._fst), tfst.get(), wc, nstate, delta) return _init_MutableFst(tfst.release()) cpdef _MutableFst push(_Fst ifst, float delta=fst.kDelta, bool push_weights=False, bool push_labels=False, bool remove_common_affix=False, bool remove_total_weight=False, bool to_final=False): """ push(ifst, delta=0.0009765625, push_weights=False, push_labels=False, remove_common_affix=False, remove_total_weight=False, to_final=False) Constructively pushes weights/labels towards initial or final states. This operation produces an equivalent transducer by pushing the weights and/or the labels towards the initial state or toward the final states. When pushing weights towards the initial state, the sum of the weight of the outgoing transitions and final weight at any non-initial state is equal to 1 in the resulting machine. When pushing weights towards the final states, the sum of the weight of the incoming transitions at any state is equal to 1. Weights need to be left distributive when pushing towards the initial state and right distributive when pushing towards the final states. Pushing labels towards the initial state consists in minimizing at every state the length of the longest common prefix of the output labels of the outgoing paths. Pushing labels towards the final states consists in minimizing at every state the length of the longest common suffix of the output labels of the incoming paths. Args: ifst: The input FST. delta: Comparison/quantization delta. push_weights: Should weights be pushed? push_labels: Should labels be pushed? remove_common_affix: If pushing labels, should common prefix/suffix be removed? remove_total_weight: If pushing weights, should total weight be removed? to_final: Push towards final states? Returns: An equivalent pushed FST. See also: The destructive variant. """ # This is copied, almost verbatim, from ./fstpush.cc. cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) cdef uint32 flags = fst.GetPushFlags(push_weights, push_labels, remove_common_affix, remove_total_weight) fst.Push(deref(ifst._fst), tfst.get(), flags, fst.GetReweightType(to_final), delta) return _init_MutableFst(tfst.release()) cpdef bool randequivalent(_Fst ifst1, _Fst ifst2, int32 npath=1, float delta=fst.kDelta, time_t seed=0, select=b"uniform", int32 max_length=INT32_MAX) except *: """ randequivalent(ifst1, ifst2, npath=1, delta=0.0009765625, seed=0, select="uniform", max_length=2147483647) Are two acceptors stochastically equivalent? This operation tests whether two FSTs are equivalent by randomly generating paths alternatively in each of the two FSTs. For each randomly generated path, the algorithm computes for each of the two FSTs the sum of the weights of all the successful paths sharing the same input and output labels as the randomly generated path and checks that these two values are within `delta`. Args: ifst1: The first input FST. ifst2: The second input FST. npath: The number of random paths to generate. delta: Comparison/quantization delta. seed: An optional seed value for random path generation; if zero, the current time and process ID is used. select: A string matching a known random arc selection type; one of: "uniform", "log_prob", "fast_log_prob". max_length: The maximum length of each random path. Returns: True if the two transducers satisfy the above condition, else False. See also: `equal`, `equivalent`, `isomorphic`, `randgen`. """ cdef fst.RandArcSelection ras = _get_rand_arc_selection(tostring(select)) cdef unique_ptr[fst.RandGenOptions[fst.RandArcSelection]] opts # The three trailing options will be ignored by RandEquivalent. opts.reset(new fst.RandGenOptions[fst.RandArcSelection](ras, max_length, 1, False, False)) if seed == 0: seed = time(NULL) + getpid() return fst.RandEquivalent(deref(ifst1._fst), deref(ifst2._fst), npath, delta, seed, deref(opts)) cpdef _MutableFst randgen(_Fst ifst, int32 npath=1, time_t seed=0, select=b"uniform", int32 max_length=INT32_MAX, bool weighted=False, bool remove_total_weight=False): """ randgen(ifst, npath=1, seed=0, select="uniform", max_length=2147483647, weight=False, remove_total_weight=False) Randomly generate successful paths in an FST. This operation randomly generates a set of successful paths in the input FST. This relies on a mechanism for selecting arcs, specified using the `select` argument. The default selector, "uniform", randomly selects a transition using a uniform distribution. The "log_prob" selector randomly selects a transition w.r.t. the weights treated as negative log probabilities after normalizing for the total weight leaving the state. In all cases, finality is treated as a transition to a super-final state. Args: ifst: The input FST. npath: The number of random paths to generate. seed: An optional seed value for random path generation; if zero, the current time and process ID is used. select: A string matching a known random arc selection type; one of: "uniform", "log_prob", "fast_log_prob". max_length: The maximum length of each random path. weighted: Should the output be weighted by path count? remove_total_weight: Should the total weight be removed (ignored when `weighted` is False)? Returns: An FST containing one or more random paths. See also: `randequivalent`. """ cdef fst.RandArcSelection ras = _get_rand_arc_selection(tostring(select)) cdef unique_ptr[fst.RandGenOptions[fst.RandArcSelection]] opts opts.reset(new fst.RandGenOptions[fst.RandArcSelection](ras, max_length, npath, weighted, remove_total_weight)) cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) if seed == 0: seed = time(NULL) + getpid() fst.RandGen(deref(ifst._fst), tfst.get(), seed, deref(opts)) return _init_MutableFst(tfst.release()) cpdef _MutableFst replace(pairs, call_arc_labeling=b"input", return_arc_labeling=b"neither", bool epsilon_on_replace=False, int64 return_label=0): """ replace(pairs, call_arc_labeling="input", return_arc_labeling="neither", epsilon_on_replace=False, return_label=0) Recursively replaces arcs in the FST with other FST(s). This operation performs the dynamic replacement of arcs in one FST with another FST, allowing the definition of FSTs analogous to RTNs. It takes as input a set of pairs of a set of pairs formed by a non-terminal label and its corresponding FST, and a label identifying the root FST in that set. The resulting FST is obtained by taking the root FST and recursively replacing each arc having a nonterminal as output label by its corresponding FST. More precisely, an arc from state s to state d with (nonterminal) output label n in this FST is replaced by redirecting this "call" arc to the initial state of a copy F of the FST for n, and adding "return" arcs from each final state of F to d. Optional arguments control how the call and return arcs are labeled; by default, the only non-epsilon label is placed on the call arc. Args: pairs: An iterable of (nonterminal label, FST) pairs, where the former is an unsigned integer and the latter is an Fst instance. call_arc_labeling: A string indicating which call arc labels should be non-epsilon. One of: "input" (default), "output", "both", "neither". This value is set to "neither" if epsilon_on_replace is True. return_arc_labeling: A string indicating which return arc labels should be non-epsilon. One of: "input", "output", "both", "neither" (default). This value is set to "neither" if epsilon_on_replace is True. epsilon_on_replace: Should call and return arcs be epsilon arcs? If True, this effectively overrides call_arc_labeling and return_arc_labeling, setting both to "neither". return_label: The integer label for return arcs. Returns: An FST resulting from expanding the input RTN. """ cdef vector[fst.LabelFstClassPair] _pairs cdef int64 root_label cdef int64 label cdef _Fst ifst it = iter(pairs) (root_label, ifst) = next(it) _pairs.push_back(fst.LabelFstClassPair(root_label, ifst._fst.get())) cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) for (label, ifst) in it: _pairs.push_back(fst.LabelFstClassPair(label, ifst._fst.get())) cdef fst.ReplaceLabelType cal = _get_replace_label_type( tostring(call_arc_labeling), epsilon_on_replace) cdef fst.ReplaceLabelType ral = _get_replace_label_type( tostring(return_arc_labeling), epsilon_on_replace) cdef unique_ptr[fst.ReplaceOptions] opts opts.reset(new fst.ReplaceOptions(root_label, cal, ral, return_label)) fst.Replace(_pairs, tfst.get(), deref(opts)) return _init_MutableFst(tfst.release()) cpdef _MutableFst reverse(_Fst ifst, bool require_superinitial=True): """ reverse(ifst, require_superinitial=True) Constructively reverses an FST's transduction. This operation reverses an FST. If A transduces string x to y with weight a, then the reverse of A transduces the reverse of x to the reverse of y with weight a.Reverse(). (Typically, a = a.Reverse() and Arc = RevArc, e.g., TropicalWeight and LogWeight.) In general, e.g., when the weights only form a left or right semiring, the output arc type must match the input arc type. Args: ifst: The input FST. require_superinitial: Should a superinitial state be created? Returns: A reversed FST. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) fst.Reverse(deref(ifst._fst), tfst.get(), require_superinitial) return _init_MutableFst(tfst.release()) # Pure C++ helper for shortestdistance. cdef vector[fst.WeightClass] *_shortestdistance(_Fst ifst, float delta=fst.kShortestDelta, int64 nstate=fst.kNoStateId, queue_type=b"auto", bool reverse=False) except *: cdef unique_ptr[vector[fst.WeightClass]] distance distance.reset(new vector[fst.WeightClass]()) # For scoping reasons, these have to be declared here even though they may # not be used in all cases. cdef unique_ptr[fst.ShortestDistanceOptions] opts if reverse: # Only the simpler signature supports shortest distance to final states; # `nstate` and `queue_type` arguments are ignored. fst.ShortestDistance(deref(ifst._fst), distance.get(), True, delta) else: opts.reset(new fst.ShortestDistanceOptions( _get_queue_type(tostring(queue_type)), fst.ANY_ARC_FILTER, nstate, delta)) fst.ShortestDistance(deref(ifst._fst), distance.get(), deref(opts)) return distance.release() def shortestdistance(_Fst ifst, float delta=fst.kShortestDelta, int64 nstate=fst.kNoStateId, queue_type=b"auto", bool reverse=False): """ shortestdistance(ifst, delta=1e-6, nstate=NO_STATE_ID, queue_type="auto", reverse=False) Compute the shortest distance from the initial or final state. This operation computes the shortest distance from the initial state (when `reverse` is False) or from every state to the final state (when `reverse` is True). The shortest distance from p to q is the \otimes-sum of the weights of all the paths between p and q. The weights must be right (if `reverse` is False) or left (if `reverse` is True) distributive, and k-closed (i.e., 1 \otimes x \otimes x^2 \otimes ... \otimes x^{k + 1} = 1 \otimes x \otimes x^2 \otimes ... \otimes x^k; e.g., TropicalWeight). Args: ifst: The input FST. delta: Comparison/quantization delta. nstate: State number threshold (ignored if `reverse` is True). queue_type: A string matching a known queue type; one of: "auto", "fifo", "lifo", "shortest", "state", "top" (ignored if `reverse` is True). reverse: Should the reverse distance (from each state to the final state) be computed? Returns: A list of Weight objects representing the shortest distance for each state. """ cdef unique_ptr[vector[fst.WeightClass]] distance distance.reset(_shortestdistance(ifst, delta, nstate, queue_type, reverse)) cdef string weight_type = ifst.weight_type() return [Weight(weight_type, weight.ToString()) for weight in deref(distance)] cpdef _MutableFst shortestpath(_Fst ifst, float delta=fst.kShortestDelta, int32 nshortest=1, int64 nstate=fst.kNoStateId, queue_type=b"auto", bool unique=False, weight=None): """ shortestpath(ifst, delta=1e-6, nshortest=1, nstate=NO_STATE_ID, queue_type="auto", unique=False, weight=None) Construct an FST containing the shortest path(s) in the input FST. This operation produces an FST containing the n-shortest paths in the input FST. The n-shortest paths are the n-lowest weight paths w.r.t. the natural semiring order. The single path that can be read from the ith of at most n transitions leaving the initial state of the resulting FST is the ith shortest path. The weights need to be right distributive and have the path property. They also need to be left distributive as well for n-shortest with n > 1 (e.g., TropicalWeight). Args: ifst: The input FST. delta: Comparison/quantization delta. nshortest: The number of paths to return. nstate: State number threshold. queue_type: A string matching a known queue type; one of: "auto", "fifo", "lifo", "shortest", "state", "top". unique: Should the resulting FST only contain distinct paths? (Requires the input FST to be an acceptor; epsilons are treated as if they are regular symbols.) weight: A Weight or weight string indicating the desired weight threshold below which paths are pruned; if omitted, no paths are pruned. Returns: An FST containing the n-shortest paths. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) # Threshold is set to semiring Zero (no pruning) if no weight is specified. cdef fst.WeightClass wc = _get_WeightClass_or_Zero(ifst.weight_type(), weight) cdef unique_ptr[fst.ShortestPathOptions] opts opts.reset(new fst.ShortestPathOptions(_get_queue_type(tostring(queue_type)), nshortest, unique, delta, wc, nstate)) fst.ShortestPath(deref(ifst._fst), tfst.get(), deref(opts)) return _init_MutableFst(tfst.release()) cpdef _Fst statemap(_Fst ifst, map_type): """ state_map(ifst, map_type) Constructively applies a transform to all states. This operation transforms each state according to the requested map type. Note that currently, only one state-mapping operation is supported. Args: ifst: The input FST. map_type: A string matching a known mapping operation; one of: "arc_sum" (sum weights of identically-labeled multi-arcs), "arc_unique" (deletes non-unique identically-labeled multi-arcs). Returns: An FST with states remapped. Raises: FstArgError: Unknown map type. See also: `arcmap`. """ return _map(ifst, fst.kDelta, map_type, 1., None) cpdef _MutableFst synchronize(_Fst ifst): """ synchronize(ifst) Constructively synchronizes an FST. This operation synchronizes a transducer. The result will be an equivalent FST that has the property that during the traversal of a path, the delay is either zero or strictly increasing, where the delay is the difference between the number of non-epsilon output labels and input labels along the path. For the algorithm to terminate, the input transducer must have bounded delay, i.e., the delay of every cycle must be zero. Args: ifst: The input FST. Returns: An equivalent synchronized FST. """ cdef unique_ptr[fst.VectorFstClass] tfst tfst.reset(new fst.VectorFstClass(ifst.arc_type())) fst.Synchronize(deref(ifst._fst), tfst.get()) return _init_MutableFst(tfst.release()) ## Compiler. cdef class Compiler(object): """ Compiler(fst_type="vector", arc_type="standard", isymbols=None, osymbols=None, ssymbols=None, acceptor=False, keep_isymbols=False, keep_osymbols=False, keep_state_numbering=False, allow_negative_labels=False) Class used to compile FSTs from strings. This class is used to compile FSTs specified using the AT&T FSM library format described here: http://web.eecs.umich.edu/~radev/NLP-fall2015/resources/fsm_archive/fsm.5.html This is the same format used by the `fstcompile` executable. Compiler options (symbol tables, etc.) are set at construction time. compiler = fst.Compiler(isymbols=ascii_syms, osymbols=ascii_syms) Once constructed, Compiler instances behave like a file handle opened for writing: # /ba+/ print >> compiler, "0 1 50 50" print >> compiler, "1 2 49 49" print >> compiler, "2 2 49 49" print >> compiler, "2" The `compile` method returns an actual FST instance: sheep_machine = compiler.compile() Compilation flushes the internal buffer, so the compiler instance can be reused to compile new machines with the same symbol tables (etc.) Args: fst_type: A string indicating the container type for the compiled FST. arc_type: A string indicating the arc type for the compiled FST. isymbols: An optional SymbolTable used to label input symbols. osymbols: An optional SymbolTable used to label output symbols. ssymbols: An optional SymbolTable used to label states. acceptor: Should the FST be rendered in acceptor format if possible? keep_isymbols: Should the input symbol table be stored in the FST? keep_osymbols: Should the output symbol table be stored in the FST? keep_state_numbering: Should the state numbering be preserved? allow_negative_labels: Should negative labels be allowed? (Not recommended; may cause conflicts). """ def __cinit__(self, string fst_type=b"vector", string arc_type=b"standard", SymbolTable isymbols=None, SymbolTable osymbols=None, SymbolTable ssymbols=None, bool acceptor=False, bool keep_isymbols=False, bool keep_osymbols=False, bool keep_state_numbering=False, bool allow_negative_labels=False): self._sstrm.reset(new stringstream()) self._fst_type = tostring(fst_type) self._arc_type = tostring(arc_type) self._isymbols = NULL if isymbols is not None: self._isymbols = isymbols._table self._osymbols = NULL if osymbols is not None: self._osymbols = osymbols._table self._ssymbols = NULL if ssymbols is not None: self._ssymbols = ssymbols._table self._acceptor = acceptor self._keep_isymbols = keep_isymbols self._keep_osymbols = keep_osymbols self._keep_state_numbering = keep_state_numbering self._allow_negative_labels = allow_negative_labels cpdef _Fst compile(self): """ compile() Compiles the FST in the compiler string buffer. This method compiles the FST and returns the resulting machine. Returns: The FST described by the compiler string buffer. Raises: FstOpError: Compilation failed. """ cdef unique_ptr[fst.FstClass] tfst tfst.reset(fst.CompileFstInternal(deref(self._sstrm), b"<pywrapfst>", self._fst_type, self._arc_type, self._isymbols, self._osymbols, self._ssymbols, self._acceptor, self._keep_isymbols, self._keep_osymbols, self._keep_state_numbering, self._allow_negative_labels)) self._sstrm.reset(new stringstream()) if tfst.get() == NULL: raise FstOpError("Compilation failed") return _init_XFst(tfst.release()) cpdef void write(self, expression): """ write(expression) Writes a string into the compiler string buffer. This method adds a line to the compiler string buffer. It is normally invoked using the right shift operator, like so: compiler = fst.Compiler() print >> compiler, "0 0 49 49" print >> compiler, "0" Args: expression: A string expression to add to compiler string buffer. """ deref(self._sstrm) << tostring(expression) ## FarReader and FarWriter. cdef class FarReader(object): """ (No constructor.) FAR ("Fst ARchive") reader object. This class is used to read a FAR from disk. FARs contain one or more FSTs (of the same arc type) indexed by a unique string key. To construct a FarReader object, use the `open` class method. Attributes: arc_type: A string indicating the arc type. far_type: A string indicating the FAR type. """ def __init__(self): raise FstDeletedConstructorError( "Cannot construct {}".format(self.__class__.__name__)) def __repr__(self): return "<{} FarReader at 0x{:x}>".format(self.far_type(), id(self)) @classmethod def open(cls, *filenames): """ FarReader.open(*filenames) Creates a FarReader object. This class method creates a FarReader given the string location of one or more FAR files on disk. Args: *filenames: The string location of one or more input FAR files. Returns: A new FarReader instance. Raises: FstIOError: Read failed. """ filenames = [tostring(filename) for filename in filenames] cdef unique_ptr[fst.FarReaderClass] tfar tfar.reset(fst.FarReaderClass.Open(filenames)) if tfar.get() == NULL: raise FstIOError("Read failed: {!r}".format(filenames)) cdef FarReader result = FarReader.__new__(FarReader) result._reader.reset(tfar.release()) return result cpdef string arc_type(self): """ arc_type(self) Returns a string indicating the arc type. """ return self._reader.get().ArcType() cpdef bool done(self): """ done(self) Indicates whether the iterator is exhausted or not. Returns: True if the iterator is exhausted, False otherwise. """ return self._reader.get().Done() cpdef bool error(self): """ error(self) Indicates whether the FarReader has encountered an error. Returns: True if the FarReader is in an errorful state, False otherwise. """ return self._reader.get().Error() cpdef string far_type(self): return fst.GetFarTypeString(self._reader.get().Type()) cpdef bool find(self, key) except *: """ find(self, key) Sets the current position to the first entry greater than or equal to the key (a string) and indicates whether or not a match was found. Args: key: A string key. Returns: True if the key was found, False otherwise. """ return self._reader.get().Find(tostring(key)) cpdef _Fst get_fst(self): """ get_fst(self) Returns the FST at the current position. Returns: A copy of the FST at the current position. """ return _init_XFst(new fst.FstClass( deref(self._reader.get().GetFstClass()))) cpdef string get_key(self): """ get_key(self) Returns the string key at the current position. Returns: The string key at the current position. """ return self._reader.get().GetKey() cpdef void next(self): """ next(self) Advances the iterator. """ self._reader.get().Next() cpdef void reset(self): """ reset(self) Resets the iterator to the initial position. """ self._reader.get().Reset() def __getitem__(self, key): cdef string ckey = tostring(key) if self.get_key() == ckey or self._reader.get().Find(ckey): return self.get_fst() raise KeyError(key) cdef class FarWriter(object): """ (No constructor.) FAR ("Fst ARchive") writer object. This class is used to write FSTs (of the same arc type) to a FAR on disk. To construct a FarWriter, use the `create` class method. Note that the data is not guaranteed to flush to disk until the FarWriter is garbage-collected. If a FarWriter has been assigned to only one variable, then calling `del` on that variable should decrement the object's reference count from 1 to 0, triggering a flush to disk on the next GC cycle. Attributes: arc_type: A string indicating the arc type. far_type: A string indicating the FAR type. """ def __init__(self): raise FstDeletedConstructorError( "Cannot construct {}".format(self.__class__.__name__)) def __repr__(self): return "<{} FarWriter at 0x{:x}>".format(self.far_type(), id(self)) @classmethod def create(cls, filename, arc_type=b"standard", far_type=b"default"): """ FarWriter. Creates a FarWriter object. This class method creates a FarWriter given the desired output location, arc type, and FAR type. Args: filename: The string location for the output FAR files. arc_type: A string indicating the arc type. far_type: A string indicating the FAR type; one of: "fst", "stlist", "sttable", "sstable", "default". Returns: A new FarWriter instance. Raises: FstIOError: Read failed. """ cdef fst.FarType ft = fst.GetFarType(tostring(far_type)) cdef fst.FarWriterClass *tfar = fst.FarWriterClass.Create( tostring(filename), tostring(arc_type), ft) if tfar == NULL: raise FstIOError("Open failed: {!r}".format(filename)) cdef FarWriter result = FarWriter.__new__(FarWriter) result._writer.reset(tfar) return result # NB: Invoking this method may be dangerous: calling any other method on the # instance after this is invoked may result in a null dereference. cdef void close(self): self._writer.reset() cpdef void add(self, key, _Fst ifst) except *: """ add(self, key, ifst) Adds an FST to the FAR. This method adds an FST to the FAR which can be retrieved with the specified string key. Args: key: The string used to key the input FST. ifst: The FST to write to the FAR. Raises: FstArgError: Key out of order. FstOpError: Incompatible or invalid arc type. """ # Failure here results from passing an FST with a different arc type than # used by the FAR was initialized to use. if not self._writer.get().Add(tostring(key), deref(ifst._fst)): raise FstOpError("Incompatible or invalid arc type") # An error here usually indicates a key out of order. if self._writer.get().Error(): raise FstArgError("Key out of order") cpdef string arc_type(self): """ arc_type(self) Returns a string indicating the arc type. """ return self._writer.get().ArcType() cpdef bool error(self): """ error(self) Indicates whether the FarWriter has encountered an error. Returns: True if the FarWriter is in an errorful state, False otherwise. """ return self._writer.get().Error() cpdef string far_type(self): """ far_type(self) Returns a string indicating the FAR type. """ return fst.GetFarTypeString(self._writer.get().Type()) # Dictionary-like assignment. def __setitem__(self, key, _Fst fst): self.add(key, fst) ## Cleanup operations for module entrance and exit. # Masks fst_error_fatal flags while this module is running, returning to the # previous state upon module exit. _fst_error_fatal_old = fst.FLAGS_fst_error_fatal fst.FLAGS_fst_error_fatal = False @atexit.register def _reset_fst_error_fatal(): fst.FLAGS_fst_error_fatal = _fst_error_fatal_old
0
coqui_public_repos/inference-engine/third_party
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/config.guess
#! /bin/sh # Attempt to guess a canonical system name. # Copyright 1992-2017 Free Software Foundation, Inc. timestamp='2017-11-07' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <https://www.gnu.org/licenses/>. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # # Originally written by Per Bothner; maintained since 2000 by Ben Elliston. # # You can get the latest version of this script from: # https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess # # Please send patches to <config-patches@gnu.org>. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Options: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to <config-patches@gnu.org>." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright 1992-2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > $dummy.c ; for c in cc gcc c89 c99 ; do if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case "${UNAME_SYSTEM}" in Linux|GNU|GNU/*) # If the system lacks a compiler, then just pick glibc. # We could probably try harder. LIBC=gnu eval $set_cc_for_build cat <<-EOF > $dummy.c #include <features.h> #if defined(__UCLIBC__) LIBC=uclibc #elif defined(__dietlibc__) LIBC=dietlibc #else LIBC=gnu #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` ;; esac # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ /sbin/$sysctl 2>/dev/null || \ /usr/sbin/$sysctl 2>/dev/null || \ echo unknown)` case "${UNAME_MACHINE_ARCH}" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; earmv*) arch=`echo ${UNAME_MACHINE_ARCH} | sed -e 's,^e\(armv[0-9]\).*$,\1,'` endian=`echo ${UNAME_MACHINE_ARCH} | sed -ne 's,^.*\(eb\)$,\1,p'` machine=${arch}${endian}-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently (or will in the future) and ABI. case "${UNAME_MACHINE_ARCH}" in earm*) os=netbsdelf ;; arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # Determine ABI tags. case "${UNAME_MACHINE_ARCH}" in earm*) expr='s/^earmv[0-9]/-eabi/;s/eb$//' abi=`echo ${UNAME_MACHINE_ARCH} | sed -e "$expr"` ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "${UNAME_VERSION}" in Debian*) release='-gnu' ;; *) release=`echo ${UNAME_RELEASE} | sed -e 's/[-_].*//' | cut -d. -f1,2` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}${abi}" exit ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE} exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} exit ;; *:LibertyBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` echo ${UNAME_MACHINE_ARCH}-unknown-libertybsd${UNAME_RELEASE} exit ;; *:MidnightBSD:*:*) echo ${UNAME_MACHINE}-unknown-midnightbsd${UNAME_RELEASE} exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} exit ;; *:SolidBSD:*:*) echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} exit ;; macppc:MirBSD:*:*) echo powerpc-unknown-mirbsd${UNAME_RELEASE} exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} exit ;; *:Sortix:*:*) echo ${UNAME_MACHINE}-unknown-sortix exit ;; *:Redox:*:*) echo ${UNAME_MACHINE}-unknown-redox exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE=alpha ;; "EV4.5 (21064)") UNAME_MACHINE=alpha ;; "LCA4 (21066/21068)") UNAME_MACHINE=alpha ;; "EV5 (21164)") UNAME_MACHINE=alphaev5 ;; "EV5.6 (21164A)") UNAME_MACHINE=alphaev56 ;; "EV5.6 (21164PC)") UNAME_MACHINE=alphapca56 ;; "EV5.7 (21164PC)") UNAME_MACHINE=alphapca57 ;; "EV6 (21264)") UNAME_MACHINE=alphaev6 ;; "EV6.7 (21264A)") UNAME_MACHINE=alphaev67 ;; "EV6.8CB (21264C)") UNAME_MACHINE=alphaev68 ;; "EV6.8AL (21264B)") UNAME_MACHINE=alphaev68 ;; "EV6.8CX (21264D)") UNAME_MACHINE=alphaev68 ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE=alphaev69 ;; "EV7 (21364)") UNAME_MACHINE=alphaev7 ;; "EV7.9 (21364A)") UNAME_MACHINE=alphaev79 ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 exit $exitcode ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit ;; arm*:riscos:*:*|arm*:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) echo i386-pc-auroraux${UNAME_RELEASE} exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) eval $set_cc_for_build SUN_ARCH=i386 # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH=x86_64 fi fi echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = x && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include <stdio.h> /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`$dummy $dummyarg` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include <sys/systemcfg.h> main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/lslpp ] ; then IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31?) HP_ARCH=m68000 ;; 9000/[34]??) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH=hppa2.0n ;; 64) HP_ARCH=hppa2.0w ;; '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20 esac ;; esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include <stdlib.h> #include <unistd.h> int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS="" $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ ${HP_ARCH} = hppa2.0w ] then eval $set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH=hppa2.0w else HP_ARCH=hppa64 fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include <unistd.h> int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case ${UNAME_PROCESSOR} in amd64) UNAME_PROCESSOR=x86_64 ;; i386) UNAME_PROCESSOR=i586 ;; esac echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit ;; *:MINGW64*:*) echo ${UNAME_MACHINE}-pc-mingw64 exit ;; *:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit ;; *:MSYS*:*) echo ${UNAME_MACHINE}-pc-msys exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; *:Interix*:*) case ${UNAME_MACHINE} in x86) echo i586-pc-interix${UNAME_RELEASE} exit ;; authenticamd | genuineintel | EM64T) echo x86_64-unknown-interix${UNAME_RELEASE} exit ;; IA64) echo ia64-unknown-interix${UNAME_RELEASE} exit ;; esac ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit ;; aarch64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC=gnulibc1 ; fi echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arc:Linux:*:* | arceb:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arm*:Linux:*:*) eval $set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then echo ${UNAME_MACHINE}-unknown-linux-${LIBC} else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi else echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf fi fi exit ;; avr32*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; cris:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; crisv32:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; e2k:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; frv:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; hexagon:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:Linux:*:*) echo ${UNAME_MACHINE}-pc-linux-${LIBC} exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; k1om:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; mips:Linux:*:* | mips64:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=${UNAME_MACHINE}el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=${UNAME_MACHINE} #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } ;; mips64el:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; openrisc*:Linux:*:*) echo or1k-unknown-linux-${LIBC} exit ;; or32:Linux:*:* | or1k*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; padre:Linux:*:*) echo sparc-unknown-linux-${LIBC} exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-${LIBC} exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; *) echo hppa-unknown-linux-${LIBC} ;; esac exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-${LIBC} exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-${LIBC} exit ;; ppc64le:Linux:*:*) echo powerpc64le-unknown-linux-${LIBC} exit ;; ppcle:Linux:*:*) echo powerpcle-unknown-linux-${LIBC} exit ;; riscv32:Linux:*:* | riscv64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux-${LIBC} exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; tile*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; vax:Linux:*:*) echo ${UNAME_MACHINE}-dec-linux-${LIBC} exit ;; x86_64:Linux:*:*) echo ${UNAME_MACHINE}-pc-linux-${LIBC} exit ;; xtensa*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit ;; i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit ;; i*86:*:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name` echo ${UNAME_MACHINE}-pc-isc$UNAME_REL elif /bin/uname -X 2>/dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configure will decide that # this is a cross-build. echo i586-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says <Richard.M.Bartel@ccMail.Census.GOV> echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes <hewes@openmarket.com>. # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo ${UNAME_MACHINE}-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. echo i586-pc-haiku exit ;; x86_64:Haiku:*:*) echo x86_64-unknown-haiku exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} exit ;; SX-7:SUPER-UX:*:*) echo sx7-nec-superux${UNAME_RELEASE} exit ;; SX-8:SUPER-UX:*:*) echo sx8-nec-superux${UNAME_RELEASE} exit ;; SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux${UNAME_RELEASE} exit ;; SX-ACE:SUPER-UX:*:*) echo sxace-nec-superux${UNAME_RELEASE} exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown eval $set_cc_for_build if test "$UNAME_PROCESSOR" = unknown ; then UNAME_PROCESSOR=powerpc fi if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then case $UNAME_PROCESSOR in i386) UNAME_PROCESSOR=x86_64 ;; powerpc) UNAME_PROCESSOR=powerpc64 ;; esac fi # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_PPC >/dev/null then UNAME_PROCESSOR=powerpc fi fi elif test "$UNAME_PROCESSOR" = i386 ; then # Avoid executing cc on OS X 10.9, as it ships with a stub # that puts up a graphical alert prompting to install # developer tools. Any system running Mac OS X 10.7 or # later (Darwin 11 and later) is required to have a 64-bit # processor. This is not true of the ARM version of Darwin # that Apple uses in portable devices. UNAME_PROCESSOR=x86_64 fi echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = x86; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-*:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk${UNAME_RELEASE} exit ;; NSE-*:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; NSR-*:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; NSX-*:NONSTOP_KERNEL:*:*) echo nsx-tandem-nsk${UNAME_RELEASE} exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = 386; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE} | sed -e 's/ .*$//'` exit ;; i*86:rdos:*:*) echo ${UNAME_MACHINE}-pc-rdos exit ;; i*86:AROS:*:*) echo ${UNAME_MACHINE}-pc-aros exit ;; x86_64:VMkernel:*:*) echo ${UNAME_MACHINE}-unknown-esx exit ;; amd64:Isilon\ OneFS:*:*) echo x86_64-unknown-onefs exit ;; esac echo "$0: unable to guess system type" >&2 case "${UNAME_MACHINE}:${UNAME_SYSTEM}" in mips:Linux | mips64:Linux) # If we got here on MIPS GNU/Linux, output extra information. cat >&2 <<EOF NOTE: MIPS GNU/Linux systems require a C compiler to fully recognize the system type. Please install a C compiler and try again. EOF ;; esac cat >&2 <<EOF This script (version $timestamp), has failed to recognize the operating system you are using. If your script is old, overwrite *all* copies of config.guess and config.sub with the latest versions from: https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess and https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub If $0 has already been updated, send the following data and any information you think might be pertinent to config-patches@gnu.org to provide the necessary information to handle your system. config.guess timestamp = $timestamp uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-functions 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End:
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/extensions
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/extensions/far/print-strings.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Outputs as strings the string FSTs in a finite-state archive. #ifndef FST_EXTENSIONS_FAR_PRINT_STRINGS_H_ #define FST_EXTENSIONS_FAR_PRINT_STRINGS_H_ #include <iomanip> #include <string> #include <vector> #include <fst/flags.h> #include <fst/extensions/far/far.h> #include <fstream> #include <fst/shortest-distance.h> #include <fst/string.h> DECLARE_string(far_field_separator); namespace fst { template <class Arc> void FarPrintStrings(const std::vector<string> &ifilenames, FarEntryType entry_type, FarTokenType far_token_type, const string &begin_key, const string &end_key, bool print_key, bool print_weight, const string &symbols_fname, bool initial_symbols, int32 generate_filenames, const string &filename_prefix, const string &filename_suffix) { StringTokenType token_type; if (far_token_type == FTT_SYMBOL) { token_type = StringTokenType::SYMBOL; } else if (far_token_type == FTT_BYTE) { token_type = StringTokenType::BYTE; } else if (far_token_type == FTT_UTF8) { token_type = StringTokenType::UTF8; } else { FSTERROR() << "FarPrintStrings: Unknown token type"; return; } std::unique_ptr<const SymbolTable> syms; if (!symbols_fname.empty()) { // TODO(kbg): Allow negative flag? const SymbolTableTextOptions opts(true); syms.reset(SymbolTable::ReadText(symbols_fname, opts)); if (!syms) { LOG(ERROR) << "FarPrintStrings: Error reading symbol table " << symbols_fname; return; } } std::unique_ptr<FarReader<Arc>> far_reader(FarReader<Arc>::Open(ifilenames)); if (!far_reader) return; if (!begin_key.empty()) far_reader->Find(begin_key); string okey; int nrep = 0; for (int i = 1; !far_reader->Done(); far_reader->Next(), ++i) { const auto &key = far_reader->GetKey(); if (!end_key.empty() && end_key < key) break; if (okey == key) { ++nrep; } else { nrep = 0; } okey = key; const auto *fst = far_reader->GetFst(); if (i == 1 && initial_symbols && !syms && fst->InputSymbols()) syms.reset(fst->InputSymbols()->Copy()); string str; VLOG(2) << "Handling key: " << key; StringPrinter<Arc> string_printer(token_type, syms ? syms.get() : fst->InputSymbols()); string_printer(*fst, &str); if (entry_type == FET_LINE) { if (print_key) std::cout << key << FLAGS_far_field_separator[0]; std::cout << str; if (print_weight) std::cout << FLAGS_far_field_separator[0] << ShortestDistance(*fst); std::cout << std::endl; } else if (entry_type == FET_FILE) { std::stringstream sstrm; if (generate_filenames) { sstrm.fill('0'); sstrm << std::right << std::setw(generate_filenames) << i; } else { sstrm << key; if (nrep > 0) sstrm << "." << nrep; } string filename; filename = filename_prefix + sstrm.str() + filename_suffix; std::ofstream ostrm(filename); if (!ostrm) { LOG(ERROR) << "FarPrintStrings: Can't open file: " << filename; return; } ostrm << str; if (token_type == StringTokenType::SYMBOL) ostrm << "\n"; } } } } // namespace fst #endif // FST_EXTENSIONS_FAR_PRINT_STRINGS_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions/pdt/pdtscript.cc
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Definitions of 'scriptable' versions of pdt operations, that is, // those that can be called with FstClass-type arguments. // // See comments in nlp/fst/script/script-impl.h for how the registration // mechanism allows these to work with various arc types. #include <string> #include <vector> #include <fst/extensions/pdt/compose.h> #include <fst/extensions/pdt/expand.h> #include <fst/extensions/pdt/pdtscript.h> #include <fst/extensions/pdt/replace.h> #include <fst/extensions/pdt/reverse.h> #include <fst/extensions/pdt/shortest-path.h> #include <fst/script/script-impl.h> namespace fst { namespace script { void PdtCompose(const FstClass &ifst1, const FstClass &ifst2, const std::vector<LabelPair> &parens, MutableFstClass *ofst, const PdtComposeOptions &copts, bool left_pdt) { if (!internal::ArcTypesMatch(ifst1, ifst2, "PdtCompose") || !internal::ArcTypesMatch(ifst1, *ofst, "PdtCompose")) return; PdtComposeArgs args(ifst1, ifst2, parens, ofst, copts, left_pdt); Apply<Operation<PdtComposeArgs>>("PdtCompose", ifst1.ArcType(), &args); } void PdtExpand(const FstClass &ifst, const std::vector<LabelPair> &parens, MutableFstClass *ofst, const PdtExpandOptions &opts) { PdtExpandArgs args(ifst, parens, ofst, opts); Apply<Operation<PdtExpandArgs>>("PdtExpand", ifst.ArcType(), &args); } void PdtExpand(const FstClass &ifst, const std::vector<std::pair<int64, int64>> &parens, MutableFstClass *ofst, bool connect, bool keep_parentheses, const WeightClass &weight_threshold) { PdtExpand(ifst, parens, ofst, PdtExpandOptions(connect, keep_parentheses, weight_threshold)); } void PdtReplace(const std::vector<LabelFstClassPair> &pairs, MutableFstClass *ofst, std::vector<LabelPair> *parens, int64 root, PdtParserType parser_type, int64 start_paren_labels, const string &left_paren_prefix, const string &right_paren_prefix) { for (size_t i = 1; i < pairs.size(); ++i) { if (!internal::ArcTypesMatch(*pairs[i - 1].second, *pairs[i].second, "PdtReplace")) return; } if (!internal::ArcTypesMatch(*pairs[0].second, *ofst, "PdtReplace")) return; PdtReplaceArgs args(pairs, ofst, parens, root, parser_type, start_paren_labels, left_paren_prefix, right_paren_prefix); Apply<Operation<PdtReplaceArgs>>("PdtReplace", ofst->ArcType(), &args); } void PdtReverse(const FstClass &ifst, const std::vector<LabelPair> &parens, MutableFstClass *ofst) { PdtReverseArgs args(ifst, parens, ofst); Apply<Operation<PdtReverseArgs>>("PdtReverse", ifst.ArcType(), &args); } void PdtShortestPath(const FstClass &ifst, const std::vector<LabelPair> &parens, MutableFstClass *ofst, const PdtShortestPathOptions &opts) { PdtShortestPathArgs args(ifst, parens, ofst, opts); Apply<Operation<PdtShortestPathArgs>>("PdtShortestPath", ifst.ArcType(), &args); } void PrintPdtInfo(const FstClass &ifst, const std::vector<LabelPair> &parens) { PrintPdtInfoArgs args(ifst, parens); Apply<Operation<PrintPdtInfoArgs>>("PrintPdtInfo", ifst.ArcType(), &args); } // Register operations for common arc types. REGISTER_FST_PDT_OPERATIONS(StdArc); REGISTER_FST_PDT_OPERATIONS(LogArc); REGISTER_FST_PDT_OPERATIONS(Log64Arc); } // namespace script } // namespace fst
0
coqui_public_repos/STT/native_client/kenlm
coqui_public_repos/STT/native_client/kenlm/util/float_to_string.cc
#include "float_to_string.hh" #include "double-conversion/double-conversion.h" #include "double-conversion/utils.h" namespace util { namespace { const kenlm_double_conversion::DoubleToStringConverter kConverter(kenlm_double_conversion::DoubleToStringConverter::NO_FLAGS, "inf", "NaN", 'e', -6, 21, 6, 0); } // namespace char *ToString(double value, char *to) { kenlm_double_conversion::StringBuilder builder(to, ToStringBuf<double>::kBytes); kConverter.ToShortest(value, &builder); return &to[builder.position()]; } char *ToString(float value, char *to) { kenlm_double_conversion::StringBuilder builder(to, ToStringBuf<float>::kBytes); kConverter.ToShortestSingle(value, &builder); return &to[builder.position()]; } } // namespace util
0
coqui_public_repos/inference-engine
coqui_public_repos/inference-engine/src/alphabet.cc
#include <fstream> #include "alphabet.h" #include "ctcdecode/decoder_utils.h" #include "cereal/types/unordered_map.hpp" #include "cereal/archives/json.hpp" // std::getline, but handle newline conventions from multiple platforms instead // of just the platform this code was built for std::istream& getline_crossplatform(std::istream& is, std::string& t) { t.clear(); // The characters in the stream are read one-by-one using a std::streambuf. // That is faster than reading them one-by-one using the std::istream. // Code that uses streambuf this way must be guarded by a sentry object. // The sentry object performs various tasks, // such as thread synchronization and updating the stream state. std::istream::sentry se(is, true); std::streambuf* sb = is.rdbuf(); while (true) { int c = sb->sbumpc(); switch (c) { case '\n': return is; case '\r': if(sb->sgetc() == '\n') sb->sbumpc(); return is; case std::streambuf::traits_type::eof(): // Also handle the case when the last line has no line ending if(t.empty()) is.setstate(std::ios::eofbit); return is; default: t += (char)c; } } } int Alphabet::init(const char *config_file) { std::ifstream in(config_file, std::ios::in); if (!in) { return 1; } unsigned int label = 0; space_label_ = -2; for (std::string line; getline_crossplatform(in, line);) { if (line.size() == 2 && line[0] == '\\' && line[1] == '#') { line = '#'; } else if (line[0] == '#') { continue; } //TODO: we should probably do something more i18n-aware here if (line == " ") { space_label_ = label; } if (line.length() == 0) { continue; } label_to_str_[label] = line; str_to_label_[line] = label; ++label; } size_ = label; in.close(); return 0; } std::string Alphabet::Serialize() { std::stringstream out; { cereal::JSONOutputArchive arc(out, cereal::JSONOutputArchive::Options::NoIndent()); arc(size_, label_to_str_); } return out.str(); } int Alphabet::Deserialize(const char* buffer, const int buffer_size) { std::string input(buffer, buffer_size); std::stringstream stream(input); cereal::JSONInputArchive arc(stream); arc(size_, label_to_str_); for (auto it : label_to_str_) { str_to_label_[it.second] = it.first; if (it.second == " ") { space_label_ = it.first; } } return 0; } bool Alphabet::CanEncodeSingle(const std::string& input) const { auto it = str_to_label_.find(input); return it != str_to_label_.end(); } bool Alphabet::CanEncode(const std::string& input) const { for (auto cp : split_into_codepoints(input)) { if (!CanEncodeSingle(cp)) { return false; } } return true; } std::string Alphabet::DecodeSingle(unsigned int label) const { auto it = label_to_str_.find(label); if (it != label_to_str_.end()) { return it->second; } else { std::cerr << "Invalid label " << label << std::endl; abort(); } } unsigned int Alphabet::EncodeSingle(const std::string& string) const { auto it = str_to_label_.find(string); if (it != str_to_label_.end()) { return it->second; } else { std::cerr << "Invalid string " << string << std::endl; abort(); } } std::string Alphabet::Decode(const std::vector<unsigned int>& input) const { std::string word; for (auto ind : input) { word += DecodeSingle(ind); } return word; } std::string Alphabet::Decode(const unsigned int* input, int length) const { std::string word; for (int i = 0; i < length; ++i) { word += DecodeSingle(input[i]); } return word; } std::vector<unsigned int> Alphabet::Encode(const std::string& input) const { std::vector<unsigned int> result; for (auto cp : split_into_codepoints(input)) { result.push_back(EncodeSingle(cp)); } return result; } bool UTF8Alphabet::CanEncodeSingle(const std::string& input) const { return true; } bool UTF8Alphabet::CanEncode(const std::string& input) const { return true; } std::vector<unsigned int> UTF8Alphabet::Encode(const std::string& input) const { std::vector<unsigned int> result; for (auto byte_char : input) { std::string byte_str(1, byte_char); result.push_back(EncodeSingle(byte_str)); } return result; }
0
coqui_public_repos/STT
coqui_public_repos/STT/taskcluster/test-python_36_tflite_16k-win-amd64-prod-opt.yml
build: template_file: test-win-opt-base.tyml dependencies: - "win-amd64-tflite-opt" - "test-training_16k-linux-amd64-py36m-opt" test_model_task: "test-training_16k-linux-amd64-py36m-opt" system_setup: > ${system.sox_win} args: tests_cmdline: "${system.homedir.win}/DeepSpeech/ds/taskcluster/tc-python_tflite-tests-prod.sh 3.6.8:m 16k" metadata: name: "DeepSpeech Windows AMD64 TFLite Python v3.6 prod tests (16kHz)" description: "Testing DeepSpeech for Windows/AMD64 on Python v3.6 on prod model, TFLite, optimized version (16kHz)"
0
coqui_public_repos/STT-examples/net_framework/STTWPF
coqui_public_repos/STT-examples/net_framework/STTWPF/ViewModels/MainWindowViewModel.cs
using AsyncAwaitBestPractices.MVVM; using CSCore; using CSCore.CoreAudioAPI; using CSCore.SoundIn; using CSCore.Streams; using STTClient.Interfaces; using STTClient.Models; using GalaSoft.MvvmLight.CommandWpf; using Microsoft.Win32; using System; using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace STT.WPF.ViewModels { /// <summary> /// View model of the MainWindow View. /// </summary> public class MainWindowViewModel : BindableBase { #region Constants private const int SampleRate = 16000; private const string ScorerPath = "kenlm.scorer"; #endregion private readonly ISTT _sttClient; #region Commands /// <summary> /// Gets or sets the command that enables the external scorer. /// </summary> public IAsyncCommand EnableExternalScorerCommand { get; private set; } /// <summary> /// Gets or sets the command that runs inference using an audio file. /// </summary> public IAsyncCommand InferenceFromFileCommand { get; private set; } /// <summary> /// Gets or sets the command that opens a dialog to select an audio file. /// </summary> public RelayCommand SelectFileCommand { get; private set; } /// <summary> /// Gets or sets the command that starts to record. /// </summary> public RelayCommand StartRecordingCommand { get; private set; } /// <summary> /// Gets or sets the command that stops the recording and gets the result. /// </summary> public IAsyncCommand StopRecordingCommand { get; private set; } #endregion #region Streaming /// <summary> /// Stream used to feed data into the acoustic model. /// </summary> private STTStream _sttStream; /// <summary> /// Records the audio of the selected device. /// </summary> private WasapiCapture _audioCapture; /// <summary> /// Converts the device source into a wavesource. /// </summary> private SoundInSource _soundInSource; /// <summary> /// Target wave source.(16KHz Mono 16bit for STT) /// </summary> private IWaveSource _convertedSource; /// <summary> /// Queue that prevents feeding data to the inference engine if it is busy. /// </summary> private ConcurrentQueue<short[]> _bufferQueue = new ConcurrentQueue<short[]>(); private int _threadSafeBoolBackValue = 0; /// <summary> /// Lock to process items in the queue one at time. /// </summary> public bool StreamingIsBusy { get => (Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 1, 1) == 1); set { if (value) Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 1, 0); else Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 0, 1); } } #endregion #region ViewProperties private bool _enableStartRecord; /// <summary> /// Gets or sets record status to control the record command. /// </summary> public bool EnableStartRecord { get => _enableStartRecord; set => SetProperty(ref _enableStartRecord, value); } private bool _stopRecordStopRecord; /// <summary> /// Gets or sets record status to control stop command. /// </summary> public bool EnableStopRecord { get => _stopRecordStopRecord; set => SetProperty(ref _stopRecordStopRecord, value, onChanged: ()=> ((AsyncCommand)StopRecordingCommand).RaiseCanExecuteChanged()); } private MMDevice _selectedDevice; /// <summary> /// Gets or sets the selected recording device. /// </summary> public MMDevice SelectedDevice { get => _selectedDevice; set => SetProperty(ref _selectedDevice, value, onChanged: UpdateSelectedDevice); } private string _statusMessage; /// <summary> /// Gets or sets status message. /// </summary> public string StatusMessage { get => _statusMessage; set => SetProperty(ref _statusMessage, value); } private bool _externalScorerEnabled; /// <summary> /// Gets or sets the external scorer status. /// </summary> private bool ExternalScorerEnabled { get => _externalScorerEnabled; set => SetProperty(ref _externalScorerEnabled, value, onChanged: () => ((AsyncCommand)EnableExternalScorerCommand).RaiseCanExecuteChanged()); } private bool _isRunningInference; /// <summary> /// Gets or sets whenever the model is running inference. /// </summary> private bool IsRunningInference { get => _isRunningInference; set => SetProperty(ref _isRunningInference, value, onChanged: () => ((AsyncCommand)InferenceFromFileCommand).RaiseCanExecuteChanged()); } private string _transcription; /// <summary> /// Gets or sets the current transcription. /// </summary> public string Transcription { get => _transcription; set => SetProperty(ref _transcription, value); } private string _audioFilePaht; /// <summary> /// Gets or sets the selected audio file path. /// </summary> public string AudioFilePath { get => _audioFilePaht; set => SetProperty(ref _audioFilePaht, value); } private ObservableCollection<MMDevice> _deviceNames; /// <summary> /// Gets or sets the available recording devices. /// </summary> public ObservableCollection<MMDevice> AvailableRecordDevices { get => _deviceNames; set => SetProperty(ref _deviceNames, value); } #endregion #region Ctors public MainWindowViewModel(ISTT sttClient) { _sttClient = sttClient; EnableExternalScorerCommand = new AsyncCommand(()=>EnableExternalScorerAsync(ScorerPath), _ => !ExternalScorerEnabled); InferenceFromFileCommand = new AsyncCommand(ExecuteInferenceFromFileAsync, _ => !IsRunningInference); SelectFileCommand = new RelayCommand(SelectAudioFile); StartRecordingCommand = new RelayCommand(StartRecording, canExecute: CanExecuteStartRecording); StopRecordingCommand = new AsyncCommand(StopRecordingAsync, _ => EnableStopRecord); LoadAvailableCaptureDevices(); } #endregion /// <summary> /// Releases the current capture device and initializes the selected one. /// </summary> private void UpdateSelectedDevice() { ReleaseCapture(); InitializeAudioCapture(); } /// <summary> /// Releases the capture device. /// </summary> private void ReleaseCapture() { if (_audioCapture != null) { _audioCapture.DataAvailable -= Capture_DataAvailable; _audioCapture.Dispose(); } } /// <summary> /// Command usage to know when the recording can start. /// </summary> /// <returns>If the device is not null.</returns> private bool CanExecuteStartRecording() => SelectedDevice != null; /// <summary> /// Loads all the available audio capture devices. /// </summary> private void LoadAvailableCaptureDevices() { AvailableRecordDevices = new ObservableCollection<MMDevice>( MMDeviceEnumerator.EnumerateDevices(DataFlow.All, DeviceState.Active)); //we get only enabled devices EnableStartRecord = true; if (AvailableRecordDevices?.Count != 0) SelectedDevice = AvailableRecordDevices[0]; } /// <summary> /// Initializes the capture source. /// </summary> private void InitializeAudioCapture() { if (SelectedDevice != null) { _audioCapture = SelectedDevice.DataFlow == DataFlow.Capture ? new WasapiCapture() : new WasapiLoopbackCapture(); _audioCapture.Device = SelectedDevice; _audioCapture.Initialize(); _audioCapture.DataAvailable += Capture_DataAvailable; _soundInSource = new SoundInSource(_audioCapture) { FillWithZeros = false }; //create a source, that converts the data provided by the //soundInSource to required format _convertedSource = _soundInSource .ChangeSampleRate(SampleRate) // sample rate .ToSampleSource() .ToWaveSource(16); //bits per sample _convertedSource = _convertedSource.ToMono(); } } private void Capture_DataAvailable(object sender, DataAvailableEventArgs e) { //read data from the converedSource //important: don't use the e.Data here //the e.Data contains the raw data provided by the //soundInSource which won't have the stt required audio format byte[] buffer = new byte[_convertedSource.WaveFormat.BytesPerSecond / 2]; int read; //keep reading as long as we still get some data while ((read = _convertedSource.Read(buffer, 0, buffer.Length)) > 0) { short[] sdata = new short[(int)Math.Ceiling(Convert.ToDecimal(read / 2))]; Buffer.BlockCopy(buffer, 0, sdata, 0, read); _bufferQueue.Enqueue(sdata); Task.Run(() => OnNewData()); } } /// <summary> /// Starts processing data from the queue. /// </summary> private void OnNewData() { while (!StreamingIsBusy && !_bufferQueue.IsEmpty) { if (_bufferQueue.TryDequeue(out short[] buffer)) { StreamingIsBusy = true; _sttClient.FeedAudioContent(_sttStream, buffer, Convert.ToUInt32(buffer.Length)); StreamingIsBusy = false; } } } /// <summary> /// Enables the external scorer. /// </summary> /// <param name="scorerPath">External scorer path.</param> /// <returns>A Task to await.</returns> public async Task EnableExternalScorerAsync(string scorerPath) { try { StatusMessage = "Loading external scorer..."; await Task.Run(() => _sttClient.EnableExternalScorer(ScorerPath)); ExternalScorerEnabled = true; StatusMessage = "External scorer loaded."; } catch (Exception ex) { StatusMessage = ex.Message; } } /// <summary> /// Runs inference and sets the transcription of an audio file. /// </summary> /// <returns>A Task to await.</returns> public async Task ExecuteInferenceFromFileAsync() { try { IsRunningInference = true; Transcription = string.Empty; StatusMessage = "Running inference..."; Stopwatch watch = new Stopwatch(); var waveBuffer = new NAudio.Wave.WaveBuffer(File.ReadAllBytes(AudioFilePath)); using (var waveInfo = new NAudio.Wave.WaveFileReader(AudioFilePath)) { watch.Start(); string speechResult = await Task.Run(() => _sttClient.SpeechToText( waveBuffer.ShortBuffer, Convert.ToUInt32(waveBuffer.MaxSize / 2))); watch.Stop(); Transcription = $"Audio duration: {waveInfo.TotalTime.ToString()} {Environment.NewLine}" + $"Inference took: {watch.Elapsed.ToString()} {Environment.NewLine}" + $"Recognized text: {speechResult}"; } waveBuffer.Clear(); StatusMessage = string.Empty; } catch (Exception ex) { StatusMessage = ex.Message; } finally { IsRunningInference = false; } } /// <summary> /// Stops the recording and sets the transcription of the closed stream. /// </summary> /// <returns>A Task to await.</returns> private async Task StopRecordingAsync() { EnableStopRecord = false; _audioCapture.Stop(); while (!_bufferQueue.IsEmpty && StreamingIsBusy) //we wait for all the queued buffers to be processed { await Task.Delay(90); } Transcription = _sttClient.FinishStream(_sttStream); EnableStartRecord = true; } /// <summary> /// Creates a new stream and starts the recording. /// </summary> private void StartRecording() { _sttStream =_sttClient.CreateStream(); _audioCapture.Start(); EnableStartRecord = false; EnableStopRecord = true; } /// <summary> /// Opens a dialog to select an audio file. /// </summary> private void SelectAudioFile() { OpenFileDialog dialog = new OpenFileDialog { Filter = "wav Files |*.wav", Multiselect = false, Title = "Please select a wav file." }; if ((bool)dialog.ShowDialog()) { AudioFilePath = dialog.FileName; } } } }
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions/far/stlist.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // A generic (string,type) list file format. // // This is a stripped-down version of STTable that does not support the Find() // operation but that does support reading/writting from standard in/out. #ifndef FST_EXTENSIONS_FAR_STLIST_H_ #define FST_EXTENSIONS_FAR_STLIST_H_ #include <algorithm> #include <functional> #include <iostream> #include <memory> #include <queue> #include <string> #include <utility> #include <vector> #include <fstream> #include <fst/util.h> namespace fst { static constexpr int32_t kSTListMagicNumber = 5656924; static constexpr int32_t kSTListFileVersion = 1; // String-type list writing class for object of type T using a functor Writer. // The Writer functor must provide at least the following interface: // // struct Writer { // void operator()(std::ostream &, const T &) const; // }; template <class T, class Writer> class STListWriter { public: explicit STListWriter(const string &filename) : stream_(filename.empty() ? &std::cout : new std::ofstream( filename, std::ios_base::out | std::ios_base::binary)), error_(false) { WriteType(*stream_, kSTListMagicNumber); WriteType(*stream_, kSTListFileVersion); if (!stream_) { FSTERROR() << "STListWriter::STListWriter: Error writing to file: " << filename; error_ = true; } } static STListWriter<T, Writer> *Create(const string &filename) { return new STListWriter<T, Writer>(filename); } void Add(const string &key, const T &t) { if (key == "") { FSTERROR() << "STListWriter::Add: Key empty: " << key; error_ = true; } else if (key < last_key_) { FSTERROR() << "STListWriter::Add: Key out of order: " << key; error_ = true; } if (error_) return; last_key_ = key; WriteType(*stream_, key); entry_writer_(*stream_, t); } bool Error() const { return error_; } ~STListWriter() { WriteType(*stream_, string()); if (stream_ != &std::cout) delete stream_; } private: Writer entry_writer_; std::ostream *stream_; // Output stream. string last_key_; // Last key. bool error_; STListWriter(const STListWriter &) = delete; STListWriter &operator=(const STListWriter &) = delete; }; // String-type list reading class for object of type T using a functor Reader. // Reader must provide at least the following interface: // // struct Reader { // T *operator()(std::istream &) const; // }; template <class T, class Reader> class STListReader { public: explicit STListReader(const std::vector<string> &filenames) : sources_(filenames), error_(false) { streams_.resize(filenames.size(), 0); bool has_stdin = false; for (size_t i = 0; i < filenames.size(); ++i) { if (filenames[i].empty()) { if (!has_stdin) { streams_[i] = &std::cin; sources_[i] = "stdin"; has_stdin = true; } else { FSTERROR() << "STListReader::STListReader: Cannot read multiple " << "inputs from standard input"; error_ = true; return; } } else { streams_[i] = new std::ifstream( filenames[i], std::ios_base::in | std::ios_base::binary); } int32_t magic_number = 0; ReadType(*streams_[i], &magic_number); int32_t file_version = 0; ReadType(*streams_[i], &file_version); if (magic_number != kSTListMagicNumber) { FSTERROR() << "STListReader::STListReader: Wrong file type: " << filenames[i]; error_ = true; return; } if (file_version != kSTListFileVersion) { FSTERROR() << "STListReader::STListReader: Wrong file version: " << filenames[i]; error_ = true; return; } string key; ReadType(*streams_[i], &key); if (!key.empty()) heap_.push(std::make_pair(key, i)); if (!*streams_[i]) { FSTERROR() << "STListReader: Error reading file: " << sources_[i]; error_ = true; return; } } if (heap_.empty()) return; const auto current = heap_.top().second; entry_.reset(entry_reader_(*streams_[current])); if (!entry_ || !*streams_[current]) { FSTERROR() << "STListReader: Error reading entry for key " << heap_.top().first << ", file " << sources_[current]; error_ = true; } } ~STListReader() { for (auto &stream : streams_) { if (stream != &std::cin) delete stream; } } static STListReader<T, Reader> *Open(const string &filename) { std::vector<string> filenames; filenames.push_back(filename); return new STListReader<T, Reader>(filenames); } static STListReader<T, Reader> *Open(const std::vector<string> &filenames) { return new STListReader<T, Reader>(filenames); } void Reset() { FSTERROR() << "STListReader::Reset: Operation not supported"; error_ = true; } bool Find(const string &key) { FSTERROR() << "STListReader::Find: Operation not supported"; error_ = true; return false; } bool Done() const { return error_ || heap_.empty(); } void Next() { if (error_) return; auto current = heap_.top().second; string key; heap_.pop(); ReadType(*(streams_[current]), &key); if (!*streams_[current]) { FSTERROR() << "STListReader: Error reading file: " << sources_[current]; error_ = true; return; } if (!key.empty()) heap_.push(std::make_pair(key, current)); if (!heap_.empty()) { current = heap_.top().second; entry_.reset(entry_reader_(*streams_[current])); if (!entry_ || !*streams_[current]) { FSTERROR() << "STListReader: Error reading entry for key: " << heap_.top().first << ", file: " << sources_[current]; error_ = true; } } } const string &GetKey() const { return heap_.top().first; } const T *GetEntry() const { return entry_.get(); } bool Error() const { return error_; } private: Reader entry_reader_; // Read functor. std::vector<std::istream *> streams_; // Input streams. std::vector<string> sources_; // Corresponding filenames. std::priority_queue< std::pair<string, size_t>, std::vector<std::pair<string, size_t>>, std::greater<std::pair<string, size_t>>> heap_; // (Key, stream id) heap mutable std::unique_ptr<T> entry_; // The currently read entry. bool error_; STListReader(const STListReader &) = delete; STListReader &operator=(const STListReader &) = delete; }; // String-type list header reading function, templated on the entry header type. // The Header type must provide at least the following interface: // // struct Header { // void Read(std::istream &strm, const string &filename); // }; template <class Header> bool ReadSTListHeader(const string &filename, Header *header) { if (filename.empty()) { LOG(ERROR) << "ReadSTListHeader: Can't read header from standard input"; return false; } std::ifstream strm(filename, std::ios_base::in | std::ios_base::binary); if (!strm) { LOG(ERROR) << "ReadSTListHeader: Could not open file: " << filename; return false; } int32_t magic_number = 0; ReadType(strm, &magic_number); int32_t file_version = 0; ReadType(strm, &file_version); if (magic_number != kSTListMagicNumber) { LOG(ERROR) << "ReadSTListHeader: Wrong file type: " << filename; return false; } if (file_version != kSTListFileVersion) { LOG(ERROR) << "ReadSTListHeader: Wrong file version: " << filename; return false; } string key; ReadType(strm, &key); header->Read(strm, filename + ":" + key); if (!strm) { LOG(ERROR) << "ReadSTListHeader: Error reading file: " << filename; return false; } return true; } bool IsSTList(const string &filename); } // namespace fst #endif // FST_EXTENSIONS_FAR_STLIST_H_
0
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/replace.h
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. // // Functions and classes for the recursive replacement of FSTs. #ifndef FST_REPLACE_H_ #define FST_REPLACE_H_ #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <fst/log.h> #include <fst/cache.h> #include <fst/expanded-fst.h> #include <fst/fst-decl.h> // For optional argument declarations. #include <fst/fst.h> #include <fst/matcher.h> #include <fst/replace-util.h> #include <fst/state-table.h> #include <fst/test-properties.h> namespace fst { // Replace state tables have the form: // // template <class Arc, class P> // class ReplaceStateTable { // public: // using Label = typename Arc::Label Label; // using StateId = typename Arc::StateId; // // using PrefixId = P; // using StateTuple = ReplaceStateTuple<StateId, PrefixId>; // using StackPrefix = ReplaceStackPrefix<Label, StateId>; // // // Required constructor. // ReplaceStateTable( // const std::vector<std::pair<Label, const Fst<Arc> *>> &fst_list, // Label root); // // // Required copy constructor that does not copy state. // ReplaceStateTable(const ReplaceStateTable<Arc, PrefixId> &table); // // // Looks up state ID by tuple, adding it if it doesn't exist. // StateId FindState(const StateTuple &tuple); // // // Looks up state tuple by ID. // const StateTuple &Tuple(StateId id) const; // // // Lookus up prefix ID by stack prefix, adding it if it doesn't exist. // PrefixId FindPrefixId(const StackPrefix &stack_prefix); // // // Looks up stack prefix by ID. // const StackPrefix &GetStackPrefix(PrefixId id) const; // }; // Tuple that uniquely defines a state in replace. template <class S, class P> struct ReplaceStateTuple { using StateId = S; using PrefixId = P; ReplaceStateTuple(PrefixId prefix_id = -1, StateId fst_id = kNoStateId, StateId fst_state = kNoStateId) : prefix_id(prefix_id), fst_id(fst_id), fst_state(fst_state) {} PrefixId prefix_id; // Index in prefix table. StateId fst_id; // Current FST being walked. StateId fst_state; // Current state in FST being walked (not to be // confused with the thse StateId of the combined FST). }; // Equality of replace state tuples. template <class StateId, class PrefixId> inline bool operator==(const ReplaceStateTuple<StateId, PrefixId> &x, const ReplaceStateTuple<StateId, PrefixId> &y) { return x.prefix_id == y.prefix_id && x.fst_id == y.fst_id && x.fst_state == y.fst_state; } // Functor returning true for tuples corresponding to states in the root FST. template <class StateId, class PrefixId> class ReplaceRootSelector { public: bool operator()(const ReplaceStateTuple<StateId, PrefixId> &tuple) const { return tuple.prefix_id == 0; } }; // Functor for fingerprinting replace state tuples. template <class StateId, class PrefixId> class ReplaceFingerprint { public: explicit ReplaceFingerprint(const std::vector<uint64_t> *size_array) : size_array_(size_array) {} uint64_t operator()(const ReplaceStateTuple<StateId, PrefixId> &tuple) const { return tuple.prefix_id * size_array_->back() + size_array_->at(tuple.fst_id - 1) + tuple.fst_state; } private: const std::vector<uint64_t> *size_array_; }; // Useful when the fst_state uniquely define the tuple. template <class StateId, class PrefixId> class ReplaceFstStateFingerprint { public: uint64_t operator()(const ReplaceStateTuple<StateId, PrefixId> &tuple) const { return tuple.fst_state; } }; // A generic hash function for replace state tuples. template <typename S, typename P> class ReplaceHash { public: size_t operator()(const ReplaceStateTuple<S, P>& t) const { static constexpr size_t prime0 = 7853; static constexpr size_t prime1 = 7867; return t.prefix_id + t.fst_id * prime0 + t.fst_state * prime1; } }; // Container for stack prefix. template <class Label, class StateId> class ReplaceStackPrefix { public: struct PrefixTuple { PrefixTuple(Label fst_id = kNoLabel, StateId nextstate = kNoStateId) : fst_id(fst_id), nextstate(nextstate) {} Label fst_id; StateId nextstate; }; ReplaceStackPrefix() {} ReplaceStackPrefix(const ReplaceStackPrefix &other) : prefix_(other.prefix_) {} void Push(StateId fst_id, StateId nextstate) { prefix_.push_back(PrefixTuple(fst_id, nextstate)); } void Pop() { prefix_.pop_back(); } const PrefixTuple &Top() const { return prefix_[prefix_.size() - 1]; } size_t Depth() const { return prefix_.size(); } public: std::vector<PrefixTuple> prefix_; }; // Equality stack prefix classes. template <class Label, class StateId> inline bool operator==(const ReplaceStackPrefix<Label, StateId> &x, const ReplaceStackPrefix<Label, StateId> &y) { if (x.prefix_.size() != y.prefix_.size()) return false; for (size_t i = 0; i < x.prefix_.size(); ++i) { if (x.prefix_[i].fst_id != y.prefix_[i].fst_id || x.prefix_[i].nextstate != y.prefix_[i].nextstate) { return false; } } return true; } // Hash function for stack prefix to prefix id. template <class Label, class StateId> class ReplaceStackPrefixHash { public: size_t operator()(const ReplaceStackPrefix<Label, StateId> &prefix) const { size_t sum = 0; for (const auto &pair : prefix.prefix_) { static constexpr size_t prime = 7863; sum += pair.fst_id + pair.nextstate * prime; } return sum; } }; // Replace state tables. // A two-level state table for replace. Warning: calls CountStates to compute // the number of states of each component FST. template <class Arc, class P = std::ptrdiff_t> class VectorHashReplaceStateTable { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using PrefixId = P; using StateTuple = ReplaceStateTuple<StateId, PrefixId>; using StateTable = VectorHashStateTable<ReplaceStateTuple<StateId, PrefixId>, ReplaceRootSelector<StateId, PrefixId>, ReplaceFstStateFingerprint<StateId, PrefixId>, ReplaceFingerprint<StateId, PrefixId>>; using StackPrefix = ReplaceStackPrefix<Label, StateId>; using StackPrefixTable = CompactHashBiTable<PrefixId, StackPrefix, ReplaceStackPrefixHash<Label, StateId>>; VectorHashReplaceStateTable( const std::vector<std::pair<Label, const Fst<Arc> *>> &fst_list, Label root) : root_size_(0) { size_array_.push_back(0); for (const auto &fst_pair : fst_list) { if (fst_pair.first == root) { root_size_ = CountStates(*(fst_pair.second)); size_array_.push_back(size_array_.back()); } else { size_array_.push_back(size_array_.back() + CountStates(*(fst_pair.second))); } } state_table_.reset( new StateTable(new ReplaceRootSelector<StateId, PrefixId>, new ReplaceFstStateFingerprint<StateId, PrefixId>, new ReplaceFingerprint<StateId, PrefixId>(&size_array_), root_size_, root_size_ + size_array_.back())); } VectorHashReplaceStateTable( const VectorHashReplaceStateTable<Arc, PrefixId> &table) : root_size_(table.root_size_), size_array_(table.size_array_), prefix_table_(table.prefix_table_) { state_table_.reset( new StateTable(new ReplaceRootSelector<StateId, PrefixId>, new ReplaceFstStateFingerprint<StateId, PrefixId>, new ReplaceFingerprint<StateId, PrefixId>(&size_array_), root_size_, root_size_ + size_array_.back())); } StateId FindState(const StateTuple &tuple) { return state_table_->FindState(tuple); } const StateTuple &Tuple(StateId id) const { return state_table_->Tuple(id); } PrefixId FindPrefixId(const StackPrefix &prefix) { return prefix_table_.FindId(prefix); } const StackPrefix& GetStackPrefix(PrefixId id) const { return prefix_table_.FindEntry(id); } private: StateId root_size_; std::vector<uint64_t> size_array_; std::unique_ptr<StateTable> state_table_; StackPrefixTable prefix_table_; }; // Default replace state table. template <class Arc, class P /* = size_t */> class DefaultReplaceStateTable : public CompactHashStateTable<ReplaceStateTuple<typename Arc::StateId, P>, ReplaceHash<typename Arc::StateId, P>> { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using PrefixId = P; using StateTuple = ReplaceStateTuple<StateId, PrefixId>; using StateTable = CompactHashStateTable<StateTuple, ReplaceHash<StateId, PrefixId>>; using StackPrefix = ReplaceStackPrefix<Label, StateId>; using StackPrefixTable = CompactHashBiTable<PrefixId, StackPrefix, ReplaceStackPrefixHash<Label, StateId>>; using StateTable::FindState; using StateTable::Tuple; DefaultReplaceStateTable( const std::vector<std::pair<Label, const Fst<Arc> *>> &, Label) {} DefaultReplaceStateTable(const DefaultReplaceStateTable<Arc, PrefixId> &table) : StateTable(), prefix_table_(table.prefix_table_) {} PrefixId FindPrefixId(const StackPrefix &prefix) { return prefix_table_.FindId(prefix); } const StackPrefix &GetStackPrefix(PrefixId id) const { return prefix_table_.FindEntry(id); } private: StackPrefixTable prefix_table_; }; // By default ReplaceFst will copy the input label of the replace arc. // The call_label_type and return_label_type options specify how to manage // the labels of the call arc and the return arc of the replace FST template <class Arc, class StateTable = DefaultReplaceStateTable<Arc>, class CacheStore = DefaultCacheStore<Arc>> struct ReplaceFstOptions : CacheImplOptions<CacheStore> { using Label = typename Arc::Label; // Index of root rule for expansion. Label root; // How to label call arc. ReplaceLabelType call_label_type = REPLACE_LABEL_INPUT; // How to label return arc. ReplaceLabelType return_label_type = REPLACE_LABEL_NEITHER; // Specifies output label to put on call arc; if kNoLabel, use existing label // on call arc. Otherwise, use this field as the output label. Label call_output_label = kNoLabel; // Specifies label to put on return arc. Label return_label = 0; // Take ownership of input FSTs? bool take_ownership = false; // Pointer to optional pre-constructed state table. StateTable *state_table = nullptr; explicit ReplaceFstOptions(const CacheImplOptions<CacheStore> &opts, Label root = kNoLabel) : CacheImplOptions<CacheStore>(opts), root(root) {} explicit ReplaceFstOptions(const CacheOptions &opts, Label root = kNoLabel) : CacheImplOptions<CacheStore>(opts), root(root) {} // FIXME(kbg): There are too many constructors here. Come up with a consistent // position for call_output_label (probably the very end) so that it is // possible to express all the remaining constructors with a single // default-argument constructor. Also move clients off of the "backwards // compatibility" constructor, for good. explicit ReplaceFstOptions(Label root) : root(root) {} explicit ReplaceFstOptions(Label root, ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, Label return_label) : root(root), call_label_type(call_label_type), return_label_type(return_label_type), return_label(return_label) {} explicit ReplaceFstOptions(Label root, ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, Label call_output_label, Label return_label) : root(root), call_label_type(call_label_type), return_label_type(return_label_type), call_output_label(call_output_label), return_label(return_label) {} explicit ReplaceFstOptions(const ReplaceUtilOptions &opts) : ReplaceFstOptions(opts.root, opts.call_label_type, opts.return_label_type, opts.return_label) {} ReplaceFstOptions() : root(kNoLabel) {} // For backwards compatibility. ReplaceFstOptions(int64_t root, bool epsilon_replace_arc) : root(root), call_label_type(epsilon_replace_arc ? REPLACE_LABEL_NEITHER : REPLACE_LABEL_INPUT), call_output_label(epsilon_replace_arc ? 0 : kNoLabel) {} }; // Forward declaration. template <class Arc, class StateTable, class CacheStore> class ReplaceFstMatcher; template <class Arc> using FstList = std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>>; // Returns true if label type on arc results in epsilon input label. inline bool EpsilonOnInput(ReplaceLabelType label_type) { return label_type == REPLACE_LABEL_NEITHER || label_type == REPLACE_LABEL_OUTPUT; } // Returns true if label type on arc results in epsilon input label. inline bool EpsilonOnOutput(ReplaceLabelType label_type) { return label_type == REPLACE_LABEL_NEITHER || label_type == REPLACE_LABEL_INPUT; } // Returns true if for either the call or return arc ilabel != olabel. template <class Label> bool ReplaceTransducer(ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, Label call_output_label) { return call_label_type == REPLACE_LABEL_INPUT || call_label_type == REPLACE_LABEL_OUTPUT || (call_label_type == REPLACE_LABEL_BOTH && call_output_label != kNoLabel) || return_label_type == REPLACE_LABEL_INPUT || return_label_type == REPLACE_LABEL_OUTPUT; } template <class Arc> uint64_t ReplaceFstProperties(typename Arc::Label root_label, const FstList<Arc> &fst_list, ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, typename Arc::Label call_output_label, bool *sorted_and_non_empty) { using Label = typename Arc::Label; std::vector<uint64_t> inprops; bool all_ilabel_sorted = true; bool all_olabel_sorted = true; bool all_non_empty = true; // All nonterminals are negative? bool all_negative = true; // All nonterminals are positive and form a dense range containing 1? bool dense_range = true; Label root_fst_idx = 0; for (Label i = 0; i < fst_list.size(); ++i) { const auto label = fst_list[i].first; if (label >= 0) all_negative = false; if (label > fst_list.size() || label <= 0) dense_range = false; if (label == root_label) root_fst_idx = i; const auto *fst = fst_list[i].second; if (fst->Start() == kNoStateId) all_non_empty = false; if (!fst->Properties(kILabelSorted, false)) all_ilabel_sorted = false; if (!fst->Properties(kOLabelSorted, false)) all_olabel_sorted = false; inprops.push_back(fst->Properties(kCopyProperties, false)); } const auto props = ReplaceProperties( inprops, root_fst_idx, EpsilonOnInput(call_label_type), EpsilonOnInput(return_label_type), EpsilonOnOutput(call_label_type), EpsilonOnOutput(return_label_type), ReplaceTransducer(call_label_type, return_label_type, call_output_label), all_non_empty, all_ilabel_sorted, all_olabel_sorted, all_negative || dense_range); const bool sorted = props & (kILabelSorted | kOLabelSorted); *sorted_and_non_empty = all_non_empty && sorted; return props; } namespace internal { // The replace implementation class supports a dynamic expansion of a recursive // transition network represented as label/FST pairs with dynamic replacable // arcs. template <class Arc, class StateTable, class CacheStore> class ReplaceFstImpl : public CacheBaseImpl<typename CacheStore::State, CacheStore> { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using State = typename CacheStore::State; using CacheImpl = CacheBaseImpl<State, CacheStore>; using PrefixId = typename StateTable::PrefixId; using StateTuple = ReplaceStateTuple<StateId, PrefixId>; using StackPrefix = ReplaceStackPrefix<Label, StateId>; using NonTerminalHash = std::unordered_map<Label, Label>; using FstImpl<Arc>::SetType; using FstImpl<Arc>::SetProperties; using FstImpl<Arc>::WriteHeader; using FstImpl<Arc>::SetInputSymbols; using FstImpl<Arc>::SetOutputSymbols; using FstImpl<Arc>::InputSymbols; using FstImpl<Arc>::OutputSymbols; using CacheImpl::PushArc; using CacheImpl::HasArcs; using CacheImpl::HasFinal; using CacheImpl::HasStart; using CacheImpl::SetArcs; using CacheImpl::SetFinal; using CacheImpl::SetStart; friend class ReplaceFstMatcher<Arc, StateTable, CacheStore>; ReplaceFstImpl(const FstList<Arc> &fst_list, const ReplaceFstOptions<Arc, StateTable, CacheStore> &opts) : CacheImpl(opts), call_label_type_(opts.call_label_type), return_label_type_(opts.return_label_type), call_output_label_(opts.call_output_label), return_label_(opts.return_label), state_table_(opts.state_table ? opts.state_table : new StateTable(fst_list, opts.root)) { SetType("replace"); // If the label is epsilon, then all replace label options are equivalent, // so we set the label types to NEITHER for simplicity. if (call_output_label_ == 0) call_label_type_ = REPLACE_LABEL_NEITHER; if (return_label_ == 0) return_label_type_ = REPLACE_LABEL_NEITHER; if (!fst_list.empty()) { SetInputSymbols(fst_list[0].second->InputSymbols()); SetOutputSymbols(fst_list[0].second->OutputSymbols()); } fst_array_.push_back(nullptr); for (Label i = 0; i < fst_list.size(); ++i) { const auto label = fst_list[i].first; const auto *fst = fst_list[i].second; nonterminal_hash_[label] = fst_array_.size(); nonterminal_set_.insert(label); fst_array_.emplace_back(opts.take_ownership ? fst : fst->Copy()); if (i) { if (!CompatSymbols(InputSymbols(), fst->InputSymbols())) { FSTERROR() << "ReplaceFstImpl: Input symbols of FST " << i << " do not match input symbols of base FST (0th FST)"; SetProperties(kError, kError); } if (!CompatSymbols(OutputSymbols(), fst->OutputSymbols())) { FSTERROR() << "ReplaceFstImpl: Output symbols of FST " << i << " do not match output symbols of base FST (0th FST)"; SetProperties(kError, kError); } } } const auto nonterminal = nonterminal_hash_[opts.root]; if ((nonterminal == 0) && (fst_array_.size() > 1)) { FSTERROR() << "ReplaceFstImpl: No FST corresponding to root label " << opts.root << " in the input tuple vector"; SetProperties(kError, kError); } root_ = (nonterminal > 0) ? nonterminal : 1; bool all_non_empty_and_sorted = false; SetProperties(ReplaceFstProperties(opts.root, fst_list, call_label_type_, return_label_type_, call_output_label_, &all_non_empty_and_sorted)); // Enables optional caching as long as sorted and all non-empty. always_cache_ = !all_non_empty_and_sorted; VLOG(2) << "ReplaceFstImpl::ReplaceFstImpl: always_cache = " << (always_cache_ ? "true" : "false"); } ReplaceFstImpl(const ReplaceFstImpl &impl) : CacheImpl(impl), call_label_type_(impl.call_label_type_), return_label_type_(impl.return_label_type_), call_output_label_(impl.call_output_label_), return_label_(impl.return_label_), always_cache_(impl.always_cache_), state_table_(new StateTable(*(impl.state_table_))), nonterminal_set_(impl.nonterminal_set_), nonterminal_hash_(impl.nonterminal_hash_), root_(impl.root_) { SetType("replace"); SetProperties(impl.Properties(), kCopyProperties); SetInputSymbols(impl.InputSymbols()); SetOutputSymbols(impl.OutputSymbols()); fst_array_.reserve(impl.fst_array_.size()); fst_array_.emplace_back(nullptr); for (Label i = 1; i < impl.fst_array_.size(); ++i) { fst_array_.emplace_back(impl.fst_array_[i]->Copy(true)); } } // Computes the dependency graph of the replace class and returns // true if the dependencies are cyclic. Cyclic dependencies will result // in an un-expandable FST. bool CyclicDependencies() const { const ReplaceUtilOptions opts(root_); ReplaceUtil<Arc> replace_util(fst_array_, nonterminal_hash_, opts); return replace_util.CyclicDependencies(); } StateId Start() { if (!HasStart()) { if (fst_array_.size() == 1) { SetStart(kNoStateId); return kNoStateId; } else { const auto fst_start = fst_array_[root_]->Start(); if (fst_start == kNoStateId) return kNoStateId; const auto prefix = GetPrefixId(StackPrefix()); const auto start = state_table_->FindState(StateTuple(prefix, root_, fst_start)); SetStart(start); return start; } } else { return CacheImpl::Start(); } } Weight Final(StateId s) { if (HasFinal(s)) return CacheImpl::Final(s); const auto &tuple = state_table_->Tuple(s); auto weight = Weight::Zero(); if (tuple.prefix_id == 0) { const auto fst_state = tuple.fst_state; weight = fst_array_[tuple.fst_id]->Final(fst_state); } if (always_cache_ || HasArcs(s)) SetFinal(s, weight); return weight; } size_t NumArcs(StateId s) { if (HasArcs(s)) { return CacheImpl::NumArcs(s); } else if (always_cache_) { // If always caching, expands and caches state. Expand(s); return CacheImpl::NumArcs(s); } else { // Otherwise computes the number of arcs without expanding. const auto tuple = state_table_->Tuple(s); if (tuple.fst_state == kNoStateId) return 0; auto num_arcs = fst_array_[tuple.fst_id]->NumArcs(tuple.fst_state); if (ComputeFinalArc(tuple, nullptr)) ++num_arcs; return num_arcs; } } // Returns whether a given label is a non-terminal. bool IsNonTerminal(Label label) const { if (label < *nonterminal_set_.begin() || label > *nonterminal_set_.rbegin()) { return false; } else { return nonterminal_hash_.count(label); } // TODO(allauzen): be smarter and take advantage of all_dense or // all_negative. Also use this in ComputeArc. This would require changes to // Replace so that recursing into an empty FST lead to a non co-accessible // state instead of deleting the arc as done currently. The current use // correct, since labels are sorted if all_non_empty is true. } size_t NumInputEpsilons(StateId s) { if (HasArcs(s)) { return CacheImpl::NumInputEpsilons(s); } else if (always_cache_ || !Properties(kILabelSorted)) { // If always caching or if the number of input epsilons is too expensive // to compute without caching (i.e., not ilabel-sorted), then expands and // caches state. Expand(s); return CacheImpl::NumInputEpsilons(s); } else { // Otherwise, computes the number of input epsilons without caching. const auto tuple = state_table_->Tuple(s); if (tuple.fst_state == kNoStateId) return 0; size_t num = 0; if (!EpsilonOnInput(call_label_type_)) { // If EpsilonOnInput(c) is false, all input epsilon arcs // are also input epsilons arcs in the underlying machine. num = fst_array_[tuple.fst_id]->NumInputEpsilons(tuple.fst_state); } else { // Otherwise, one need to consider that all non-terminal arcs // in the underlying machine also become input epsilon arc. ArcIterator<Fst<Arc>> aiter(*fst_array_[tuple.fst_id], tuple.fst_state); for (; !aiter.Done() && ((aiter.Value().ilabel == 0) || IsNonTerminal(aiter.Value().olabel)); aiter.Next()) { ++num; } } if (EpsilonOnInput(return_label_type_) && ComputeFinalArc(tuple, nullptr)) { ++num; } return num; } } size_t NumOutputEpsilons(StateId s) { if (HasArcs(s)) { return CacheImpl::NumOutputEpsilons(s); } else if (always_cache_ || !Properties(kOLabelSorted)) { // If always caching or if the number of output epsilons is too expensive // to compute without caching (i.e., not olabel-sorted), then expands and // caches state. Expand(s); return CacheImpl::NumOutputEpsilons(s); } else { // Otherwise, computes the number of output epsilons without caching. const auto tuple = state_table_->Tuple(s); if (tuple.fst_state == kNoStateId) return 0; size_t num = 0; if (!EpsilonOnOutput(call_label_type_)) { // If EpsilonOnOutput(c) is false, all output epsilon arcs are also // output epsilons arcs in the underlying machine. num = fst_array_[tuple.fst_id]->NumOutputEpsilons(tuple.fst_state); } else { // Otherwise, one need to consider that all non-terminal arcs in the // underlying machine also become output epsilon arc. ArcIterator<Fst<Arc>> aiter(*fst_array_[tuple.fst_id], tuple.fst_state); for (; !aiter.Done() && ((aiter.Value().olabel == 0) || IsNonTerminal(aiter.Value().olabel)); aiter.Next()) { ++num; } } if (EpsilonOnOutput(return_label_type_) && ComputeFinalArc(tuple, nullptr)) { ++num; } return num; } } uint64_t Properties() const override { return Properties(kFstProperties); } // Sets error if found, and returns other FST impl properties. uint64_t Properties(uint64_t mask) const override { if (mask & kError) { for (Label i = 1; i < fst_array_.size(); ++i) { if (fst_array_[i]->Properties(kError, false)) { SetProperties(kError, kError); } } } return FstImpl<Arc>::Properties(mask); } // Returns the base arc iterator, and if arcs have not been computed yet, // extends and recurses for new arcs. void InitArcIterator(StateId s, ArcIteratorData<Arc> *data) { if (!HasArcs(s)) Expand(s); CacheImpl::InitArcIterator(s, data); // TODO(allauzen): Set behaviour of generic iterator. // Warning: ArcIterator<ReplaceFst<A>>::InitCache() relies on current // behaviour. } // Extends current state (walk arcs one level deep). void Expand(StateId s) { const auto tuple = state_table_->Tuple(s); if (tuple.fst_state == kNoStateId) { // Local FST is empty. SetArcs(s); return; } ArcIterator<Fst<Arc>> aiter(*fst_array_[tuple.fst_id], tuple.fst_state); Arc arc; // Creates a final arc when needed. if (ComputeFinalArc(tuple, &arc)) PushArc(s, arc); // Expands all arcs leaving the state. for (; !aiter.Done(); aiter.Next()) { if (ComputeArc(tuple, aiter.Value(), &arc)) PushArc(s, arc); } SetArcs(s); } void Expand(StateId s, const StateTuple &tuple, const ArcIteratorData<Arc> &data) { if (tuple.fst_state == kNoStateId) { // Local FST is empty. SetArcs(s); return; } ArcIterator<Fst<Arc>> aiter(data); Arc arc; // Creates a final arc when needed. if (ComputeFinalArc(tuple, &arc)) AddArc(s, arc); // Expands all arcs leaving the state. for (; !aiter.Done(); aiter.Next()) { if (ComputeArc(tuple, aiter.Value(), &arc)) AddArc(s, arc); } SetArcs(s); } // If acpp is null, only returns true if a final arcp is required, but does // not actually compute it. bool ComputeFinalArc(const StateTuple &tuple, Arc *arcp, uint32_t flags = kArcValueFlags) { const auto fst_state = tuple.fst_state; if (fst_state == kNoStateId) return false; // If state is final, pops the stack. if (fst_array_[tuple.fst_id]->Final(fst_state) != Weight::Zero() && tuple.prefix_id) { if (arcp) { arcp->ilabel = (EpsilonOnInput(return_label_type_)) ? 0 : return_label_; arcp->olabel = (EpsilonOnOutput(return_label_type_)) ? 0 : return_label_; if (flags & kArcNextStateValue) { const auto &stack = state_table_->GetStackPrefix(tuple.prefix_id); const auto prefix_id = PopPrefix(stack); const auto &top = stack.Top(); arcp->nextstate = state_table_->FindState( StateTuple(prefix_id, top.fst_id, top.nextstate)); } if (flags & kArcWeightValue) { arcp->weight = fst_array_[tuple.fst_id]->Final(fst_state); } } return true; } else { return false; } } // Computes an arc in the FST corresponding to one in the underlying machine. // Returns false if the underlying arc corresponds to no arc in the resulting // FST. bool ComputeArc(const StateTuple &tuple, const Arc &arc, Arc *arcp, uint32_t flags = kArcValueFlags) { if (!EpsilonOnInput(call_label_type_) && (flags == (flags & (kArcILabelValue | kArcWeightValue)))) { *arcp = arc; return true; } if (arc.olabel == 0 || arc.olabel < *nonterminal_set_.begin() || arc.olabel > *nonterminal_set_.rbegin()) { // Expands local FST. const auto nextstate = flags & kArcNextStateValue ? state_table_->FindState( StateTuple(tuple.prefix_id, tuple.fst_id, arc.nextstate)) : kNoStateId; *arcp = Arc(arc.ilabel, arc.olabel, arc.weight, nextstate); } else { // Checks for non-terminal. const auto it = nonterminal_hash_.find(arc.olabel); if (it != nonterminal_hash_.end()) { // Recurses into non-terminal. const auto nonterminal = it->second; const auto nt_prefix = PushPrefix(state_table_->GetStackPrefix(tuple.prefix_id), tuple.fst_id, arc.nextstate); // If the start state is valid, replace; othewise, the arc is implicitly // deleted. const auto nt_start = fst_array_[nonterminal]->Start(); if (nt_start != kNoStateId) { const auto nt_nextstate = flags & kArcNextStateValue ? state_table_->FindState(StateTuple( nt_prefix, nonterminal, nt_start)) : kNoStateId; const auto ilabel = (EpsilonOnInput(call_label_type_)) ? 0 : arc.ilabel; const auto olabel = (EpsilonOnOutput(call_label_type_)) ? 0 : ((call_output_label_ == kNoLabel) ? arc.olabel : call_output_label_); *arcp = Arc(ilabel, olabel, arc.weight, nt_nextstate); } else { return false; } } else { const auto nextstate = flags & kArcNextStateValue ? state_table_->FindState( StateTuple(tuple.prefix_id, tuple.fst_id, arc.nextstate)) : kNoStateId; *arcp = Arc(arc.ilabel, arc.olabel, arc.weight, nextstate); } } return true; } // Returns the arc iterator flags supported by this FST. uint32_t ArcIteratorFlags() const { uint32_t flags = kArcValueFlags; if (!always_cache_) flags |= kArcNoCache; return flags; } StateTable *GetStateTable() const { return state_table_.get(); } const Fst<Arc> *GetFst(Label fst_id) const { return fst_array_[fst_id].get(); } Label GetFstId(Label nonterminal) const { const auto it = nonterminal_hash_.find(nonterminal); if (it == nonterminal_hash_.end()) { FSTERROR() << "ReplaceFstImpl::GetFstId: Nonterminal not found: " << nonterminal; } return it->second; } // Returns true if label type on call arc results in epsilon input label. bool EpsilonOnCallInput() { return EpsilonOnInput(call_label_type_); } private: // The unique index into stack prefix table. PrefixId GetPrefixId(const StackPrefix &prefix) { return state_table_->FindPrefixId(prefix); } // The prefix ID after a stack pop. PrefixId PopPrefix(StackPrefix prefix) { prefix.Pop(); return GetPrefixId(prefix); } // The prefix ID after a stack push. PrefixId PushPrefix(StackPrefix prefix, Label fst_id, StateId nextstate) { prefix.Push(fst_id, nextstate); return GetPrefixId(prefix); } // Runtime options ReplaceLabelType call_label_type_; // How to label call arc. ReplaceLabelType return_label_type_; // How to label return arc. int64_t call_output_label_; // Specifies output label to put on call arc int64_t return_label_; // Specifies label to put on return arc. bool always_cache_; // Disable optional caching of arc iterator? // State table. std::unique_ptr<StateTable> state_table_; // Replace components. std::set<Label> nonterminal_set_; NonTerminalHash nonterminal_hash_; std::vector<std::unique_ptr<const Fst<Arc>>> fst_array_; Label root_; }; } // namespace internal // // ReplaceFst supports dynamic replacement of arcs in one FST with another FST. // This replacement is recursive. ReplaceFst can be used to support a variety of // delayed constructions such as recursive // transition networks, union, or closure. It is constructed with an array of // FST(s). One FST represents the root (or topology) machine. The root FST // refers to other FSTs by recursively replacing arcs labeled as non-terminals // with the matching non-terminal FST. Currently the ReplaceFst uses the output // symbols of the arcs to determine whether the arc is a non-terminal arc or // not. A non-terminal can be any label that is not a non-zero terminal label in // the output alphabet. // // Note that the constructor uses a vector of pairs. These correspond to the // tuple of non-terminal Label and corresponding FST. For example to implement // the closure operation we need 2 FSTs. The first root FST is a single // self-loop arc on the start state. // // The ReplaceFst class supports an optionally caching arc iterator. // // The ReplaceFst needs to be built such that it is known to be ilabel- or // olabel-sorted (see usage below). // // Observe that Matcher<Fst<A>> will use the optionally caching arc iterator // when available (the FST is ilabel-sorted and matching on the input, or the // FST is olabel -orted and matching on the output). In order to obtain the // most efficient behaviour, it is recommended to set call_label_type to // REPLACE_LABEL_INPUT or REPLACE_LABEL_BOTH and return_label_type to // REPLACE_LABEL_OUTPUT or REPLACE_LABEL_NEITHER. This means that the call arc // does not have epsilon on the input side and the return arc has epsilon on the // input side) and matching on the input side. // // This class attaches interface to implementation and handles reference // counting, delegating most methods to ImplToFst. template <class A, class T /* = DefaultReplaceStateTable<A> */, class CacheStore /* = DefaultCacheStore<A> */> class ReplaceFst : public ImplToFst<internal::ReplaceFstImpl<A, T, CacheStore>> { public: using Arc = A; using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using StateTable = T; using Store = CacheStore; using State = typename CacheStore::State; using Impl = internal::ReplaceFstImpl<Arc, StateTable, CacheStore>; using CacheImpl = internal::CacheBaseImpl<State, CacheStore>; using ImplToFst<Impl>::Properties; friend class ArcIterator<ReplaceFst<Arc, StateTable, CacheStore>>; friend class StateIterator<ReplaceFst<Arc, StateTable, CacheStore>>; friend class ReplaceFstMatcher<Arc, StateTable, CacheStore>; ReplaceFst(const std::vector<std::pair<Label, const Fst<Arc> *>> &fst_array, Label root) : ImplToFst<Impl>(std::make_shared<Impl>( fst_array, ReplaceFstOptions<Arc, StateTable, CacheStore>(root))) {} ReplaceFst(const std::vector<std::pair<Label, const Fst<Arc> *>> &fst_array, const ReplaceFstOptions<Arc, StateTable, CacheStore> &opts) : ImplToFst<Impl>(std::make_shared<Impl>(fst_array, opts)) {} // See Fst<>::Copy() for doc. ReplaceFst(const ReplaceFst<Arc, StateTable, CacheStore> &fst, bool safe = false) : ImplToFst<Impl>(fst, safe) {} // Get a copy of this ReplaceFst. See Fst<>::Copy() for further doc. ReplaceFst<Arc, StateTable, CacheStore> *Copy( bool safe = false) const override { return new ReplaceFst<Arc, StateTable, CacheStore>(*this, safe); } inline void InitStateIterator(StateIteratorData<Arc> *data) const override; void InitArcIterator(StateId s, ArcIteratorData<Arc> *data) const override { GetMutableImpl()->InitArcIterator(s, data); } MatcherBase<Arc> *InitMatcher(MatchType match_type) const override { if ((GetImpl()->ArcIteratorFlags() & kArcNoCache) && ((match_type == MATCH_INPUT && Properties(kILabelSorted, false)) || (match_type == MATCH_OUTPUT && Properties(kOLabelSorted, false)))) { return new ReplaceFstMatcher<Arc, StateTable, CacheStore> (this, match_type); } else { VLOG(2) << "Not using replace matcher"; return nullptr; } } bool CyclicDependencies() const { return GetImpl()->CyclicDependencies(); } const StateTable &GetStateTable() const { return *GetImpl()->GetStateTable(); } const Fst<Arc> &GetFst(Label nonterminal) const { return *GetImpl()->GetFst(GetImpl()->GetFstId(nonterminal)); } private: using ImplToFst<Impl>::GetImpl; using ImplToFst<Impl>::GetMutableImpl; ReplaceFst &operator=(const ReplaceFst &) = delete; }; // Specialization for ReplaceFst. template <class Arc, class StateTable, class CacheStore> class StateIterator<ReplaceFst<Arc, StateTable, CacheStore>> : public CacheStateIterator<ReplaceFst<Arc, StateTable, CacheStore>> { public: explicit StateIterator(const ReplaceFst<Arc, StateTable, CacheStore> &fst) : CacheStateIterator<ReplaceFst<Arc, StateTable, CacheStore>>( fst, fst.GetMutableImpl()) {} }; // Specialization for ReplaceFst, implementing optional caching. It is be used // as follows: // // ReplaceFst<A> replace; // ArcIterator<ReplaceFst<A>> aiter(replace, s); // // Note: ArcIterator< Fst<A>> is always a caching arc iterator. // aiter.SetFlags(kArcNoCache, kArcNoCache); // // Uses the arc iterator, no arc will be cached, no state will be expanded. // // Arc flags can be used to decide which component of the arc need to be // computed. // aiter.SetFlags(kArcILabelValue, kArcValueFlags); // // Wants the ilabel for this arc. // aiter.Value(); // Does not compute the destination state. // aiter.Next(); // aiter.SetFlags(kArcNextStateValue, kArcNextStateValue); // // Wants the ilabel and next state for this arc. // aiter.Value(); // Does compute the destination state and inserts it // // in the replace state table. // // No additional arcs have been cached at this point. template <class Arc, class StateTable, class CacheStore> class ArcIterator<ReplaceFst<Arc, StateTable, CacheStore>> { public: using StateId = typename Arc::StateId; using StateTuple = typename StateTable::StateTuple; ArcIterator(const ReplaceFst<Arc, StateTable, CacheStore> &fst, StateId s) : fst_(fst), s_(s), pos_(0), offset_(0), flags_(kArcValueFlags), arcs_(nullptr), data_flags_(0), final_flags_(0) { cache_data_.ref_count = nullptr; local_data_.ref_count = nullptr; // If FST does not support optional caching, forces caching. if (!(fst_.GetImpl()->ArcIteratorFlags() & kArcNoCache) && !(fst_.GetImpl()->HasArcs(s_))) { fst_.GetMutableImpl()->Expand(s_); } // If state is already cached, use cached arcs array. if (fst_.GetImpl()->HasArcs(s_)) { (fst_.GetImpl()) ->internal::template CacheBaseImpl< typename CacheStore::State, CacheStore>::InitArcIterator(s_, &cache_data_); num_arcs_ = cache_data_.narcs; arcs_ = cache_data_.arcs; // arcs_ is a pointer to the cached arcs. data_flags_ = kArcValueFlags; // All the arc member values are valid. } else { // Otherwise delay decision until Value() is called. tuple_ = fst_.GetImpl()->GetStateTable()->Tuple(s_); if (tuple_.fst_state == kNoStateId) { num_arcs_ = 0; } else { // The decision to cache or not to cache has been defered until Value() // or // SetFlags() is called. However, the arc iterator is set up now to be // ready for non-caching in order to keep the Value() method simple and // efficient. const auto *rfst = fst_.GetImpl()->GetFst(tuple_.fst_id); rfst->InitArcIterator(tuple_.fst_state, &local_data_); // arcs_ is a pointer to the arcs in the underlying machine. arcs_ = local_data_.arcs; // Computes the final arc (but not its destination state) if a final arc // is required. bool has_final_arc = fst_.GetMutableImpl()->ComputeFinalArc( tuple_, &final_arc_, kArcValueFlags & ~kArcNextStateValue); // Sets the arc value flags that hold for final_arc_. final_flags_ = kArcValueFlags & ~kArcNextStateValue; // Computes the number of arcs. num_arcs_ = local_data_.narcs; if (has_final_arc) ++num_arcs_; // Sets the offset between the underlying arc positions and the // positions // in the arc iterator. offset_ = num_arcs_ - local_data_.narcs; // Defers the decision to cache or not until Value() or SetFlags() is // called. data_flags_ = 0; } } } ~ArcIterator() { if (cache_data_.ref_count) --(*cache_data_.ref_count); if (local_data_.ref_count) --(*local_data_.ref_count); } void ExpandAndCache() const { // TODO(allauzen): revisit this. // fst_.GetImpl()->Expand(s_, tuple_, local_data_); // (fst_.GetImpl())->CacheImpl<A>*>::InitArcIterator(s_, // &cache_data_); // fst_.InitArcIterator(s_, &cache_data_); // Expand and cache state. arcs_ = cache_data_.arcs; // arcs_ is a pointer to the cached arcs. data_flags_ = kArcValueFlags; // All the arc member values are valid. offset_ = 0; // No offset. } void Init() { if (flags_ & kArcNoCache) { // If caching is disabled // arcs_ is a pointer to the arcs in the underlying machine. arcs_ = local_data_.arcs; // Sets the arcs value flags that hold for arcs_. data_flags_ = kArcWeightValue; if (!fst_.GetMutableImpl()->EpsilonOnCallInput()) { data_flags_ |= kArcILabelValue; } // Sets the offset between the underlying arc positions and the positions // in the arc iterator. offset_ = num_arcs_ - local_data_.narcs; } else { ExpandAndCache(); } } bool Done() const { return pos_ >= num_arcs_; } const Arc &Value() const { // If data_flags_ is 0, non-caching was not requested. if (!data_flags_) { // TODO(allauzen): Revisit this. if (flags_ & kArcNoCache) { // Should never happen. FSTERROR() << "ReplaceFst: Inconsistent arc iterator flags"; } ExpandAndCache(); } if (pos_ - offset_ >= 0) { // The requested arc is not the final arc. const auto &arc = arcs_[pos_ - offset_]; if ((data_flags_ & flags_) == (flags_ & kArcValueFlags)) { // If the value flags match the recquired value flags then returns the // arc. return arc; } else { // Otherwise, compute the corresponding arc on-the-fly. fst_.GetMutableImpl()->ComputeArc(tuple_, arc, &arc_, flags_ & kArcValueFlags); return arc_; } } else { // The requested arc is the final arc. if ((final_flags_ & flags_) != (flags_ & kArcValueFlags)) { // If the arc value flags that hold for the final arc do not match the // requested value flags, then // final_arc_ needs to be updated. fst_.GetMutableImpl()->ComputeFinalArc(tuple_, &final_arc_, flags_ & kArcValueFlags); final_flags_ = flags_ & kArcValueFlags; } return final_arc_; } } void Next() { ++pos_; } size_t Position() const { return pos_; } void Reset() { pos_ = 0; } void Seek(size_t pos) { pos_ = pos; } uint32_t Flags() const { return flags_; } void SetFlags(uint32_t flags, uint32_t mask) { // Updates the flags taking into account what flags are supported // by the FST. flags_ &= ~mask; flags_ |= (flags & fst_.GetImpl()->ArcIteratorFlags()); // If non-caching is not requested (and caching has not already been // performed), then flush data_flags_ to request caching during the next // call to Value(). if (!(flags_ & kArcNoCache) && data_flags_ != kArcValueFlags) { if (!fst_.GetImpl()->HasArcs(s_)) data_flags_ = 0; } // If data_flags_ has been flushed but non-caching is requested before // calling Value(), then set up the iterator for non-caching. if ((flags & kArcNoCache) && (!data_flags_)) Init(); } private: const ReplaceFst<Arc, StateTable, CacheStore> &fst_; // Reference to the FST. StateId s_; // State in the FST. mutable StateTuple tuple_; // Tuple corresponding to state_. std::ptrdiff_t pos_; // Current position. mutable std::ptrdiff_t offset_; // Offset between position in iterator and in arcs_. std::ptrdiff_t num_arcs_; // Number of arcs at state_. uint32_t flags_; // Behavorial flags for the arc iterator mutable Arc arc_; // Memory to temporarily store computed arcs. mutable ArcIteratorData<Arc> cache_data_; // Arc iterator data in cache. mutable ArcIteratorData<Arc> local_data_; // Arc iterator data in local FST. mutable const Arc *arcs_; // Array of arcs. mutable uint32_t data_flags_; // Arc value flags valid for data in arcs_. mutable Arc final_arc_; // Final arc (when required). mutable uint32_t final_flags_; // Arc value flags valid for final_arc_. ArcIterator(const ArcIterator &) = delete; ArcIterator &operator=(const ArcIterator &) = delete; }; template <class Arc, class StateTable, class CacheStore> class ReplaceFstMatcher : public MatcherBase<Arc> { public: using Label = typename Arc::Label; using StateId = typename Arc::StateId; using Weight = typename Arc::Weight; using FST = ReplaceFst<Arc, StateTable, CacheStore>; using LocalMatcher = MultiEpsMatcher<Matcher<Fst<Arc>>>; using StateTuple = typename StateTable::StateTuple; // This makes a copy of the FST. ReplaceFstMatcher(const ReplaceFst<Arc, StateTable, CacheStore> &fst, MatchType match_type) : owned_fst_(fst.Copy()), fst_(*owned_fst_), impl_(fst_.GetMutableImpl()), s_(fst::kNoStateId), match_type_(match_type), current_loop_(false), final_arc_(false), loop_(kNoLabel, 0, Weight::One(), kNoStateId) { if (match_type_ == fst::MATCH_OUTPUT) { std::swap(loop_.ilabel, loop_.olabel); } InitMatchers(); } // This doesn't copy the FST. ReplaceFstMatcher(const ReplaceFst<Arc, StateTable, CacheStore> *fst, MatchType match_type) : fst_(*fst), impl_(fst_.GetMutableImpl()), s_(fst::kNoStateId), match_type_(match_type), current_loop_(false), final_arc_(false), loop_(kNoLabel, 0, Weight::One(), kNoStateId) { if (match_type_ == fst::MATCH_OUTPUT) { std::swap(loop_.ilabel, loop_.olabel); } InitMatchers(); } // This makes a copy of the FST. ReplaceFstMatcher( const ReplaceFstMatcher<Arc, StateTable, CacheStore> &matcher, bool safe = false) : owned_fst_(matcher.fst_.Copy(safe)), fst_(*owned_fst_), impl_(fst_.GetMutableImpl()), s_(fst::kNoStateId), match_type_(matcher.match_type_), current_loop_(false), final_arc_(false), loop_(fst::kNoLabel, 0, Weight::One(), fst::kNoStateId) { if (match_type_ == fst::MATCH_OUTPUT) { std::swap(loop_.ilabel, loop_.olabel); } InitMatchers(); } // Creates a local matcher for each component FST in the RTN. LocalMatcher is // a multi-epsilon wrapper matcher. MultiEpsilonMatcher is used to match each // non-terminal arc, since these non-terminal // turn into epsilons on recursion. void InitMatchers() { const auto &fst_array = impl_->fst_array_; matcher_.resize(fst_array.size()); for (Label i = 0; i < fst_array.size(); ++i) { if (fst_array[i]) { matcher_[i].reset( new LocalMatcher(*fst_array[i], match_type_, kMultiEpsList)); auto it = impl_->nonterminal_set_.begin(); for (; it != impl_->nonterminal_set_.end(); ++it) { matcher_[i]->AddMultiEpsLabel(*it); } } } } ReplaceFstMatcher<Arc, StateTable, CacheStore> *Copy( bool safe = false) const override { return new ReplaceFstMatcher<Arc, StateTable, CacheStore>(*this, safe); } MatchType Type(bool test) const override { if (match_type_ == MATCH_NONE) return match_type_; const auto true_prop = match_type_ == MATCH_INPUT ? kILabelSorted : kOLabelSorted; const auto false_prop = match_type_ == MATCH_INPUT ? kNotILabelSorted : kNotOLabelSorted; const auto props = fst_.Properties(true_prop | false_prop, test); if (props & true_prop) { return match_type_; } else if (props & false_prop) { return MATCH_NONE; } else { return MATCH_UNKNOWN; } } const Fst<Arc> &GetFst() const override { return fst_; } uint64_t Properties(uint64_t props) const override { return props; } // Sets the state from which our matching happens. void SetState(StateId s) final { if (s_ == s) return; s_ = s; tuple_ = impl_->GetStateTable()->Tuple(s_); if (tuple_.fst_state == kNoStateId) { done_ = true; return; } // Gets current matcher, used for non-epsilon matching. current_matcher_ = matcher_[tuple_.fst_id].get(); current_matcher_->SetState(tuple_.fst_state); loop_.nextstate = s_; final_arc_ = false; } // Searches for label from previous set state. If label == 0, first // hallucinate an epsilon loop; otherwise use the underlying matcher to // search for the label or epsilons. Note since the ReplaceFst recursion // on non-terminal arcs causes epsilon transitions to be created we use // MultiEpsilonMatcher to search for possible matches of non-terminals. If the // component FST // reaches a final state we also need to add the exiting final arc. bool Find(Label label) final { bool found = false; label_ = label; if (label_ == 0 || label_ == kNoLabel) { // Computes loop directly, avoiding Replace::ComputeArc. if (label_ == 0) { current_loop_ = true; found = true; } // Searches for matching multi-epsilons. final_arc_ = impl_->ComputeFinalArc(tuple_, nullptr); found = current_matcher_->Find(kNoLabel) || final_arc_ || found; } else { // Searches on a sub machine directly using sub machine matcher. found = current_matcher_->Find(label_); } return found; } bool Done() const final { return !current_loop_ && !final_arc_ && current_matcher_->Done(); } const Arc &Value() const final { if (current_loop_) return loop_; if (final_arc_) { impl_->ComputeFinalArc(tuple_, &arc_); return arc_; } const auto &component_arc = current_matcher_->Value(); impl_->ComputeArc(tuple_, component_arc, &arc_); return arc_; } void Next() final { if (current_loop_) { current_loop_ = false; return; } if (final_arc_) { final_arc_ = false; return; } current_matcher_->Next(); } std::ptrdiff_t Priority(StateId s) final { return fst_.NumArcs(s); } private: std::unique_ptr<const ReplaceFst<Arc, StateTable, CacheStore>> owned_fst_; const ReplaceFst<Arc, StateTable, CacheStore> &fst_; internal::ReplaceFstImpl<Arc, StateTable, CacheStore> *impl_; LocalMatcher *current_matcher_; std::vector<std::unique_ptr<LocalMatcher>> matcher_; StateId s_; // Current state. Label label_; // Current label. MatchType match_type_; // Supplied by caller. mutable bool done_; mutable bool current_loop_; // Current arc is the implicit loop. mutable bool final_arc_; // Current arc for exiting recursion. mutable StateTuple tuple_; // Tuple corresponding to state_. mutable Arc arc_; Arc loop_; ReplaceFstMatcher &operator=(const ReplaceFstMatcher &) = delete; }; template <class Arc, class StateTable, class CacheStore> inline void ReplaceFst<Arc, StateTable, CacheStore>::InitStateIterator( StateIteratorData<Arc> *data) const { data->base = new StateIterator<ReplaceFst<Arc, StateTable, CacheStore>>(*this); } using StdReplaceFst = ReplaceFst<StdArc>; // Recursively replaces arcs in the root FSTs with other FSTs. // This version writes the result of replacement to an output MutableFst. // // Replace supports replacement of arcs in one Fst with another FST. This // replacement is recursive. Replace takes an array of FST(s). One FST // represents the root (or topology) machine. The root FST refers to other FSTs // by recursively replacing arcs labeled as non-terminals with the matching // non-terminal FST. Currently Replace uses the output symbols of the arcs to // determine whether the arc is a non-terminal arc or not. A non-terminal can be // any label that is not a non-zero terminal label in the output alphabet. // // Note that input argument is a vector of pairs. These correspond to the tuple // of non-terminal Label and corresponding FST. template <class Arc> void Replace(const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>> &ifst_array, MutableFst<Arc> *ofst, ReplaceFstOptions<Arc> opts = ReplaceFstOptions<Arc>()) { opts.gc = true; opts.gc_limit = 0; // Caches only the last state for fastest copy. *ofst = ReplaceFst<Arc>(ifst_array, opts); } template <class Arc> void Replace(const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>> &ifst_array, MutableFst<Arc> *ofst, const ReplaceUtilOptions &opts) { Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(opts)); } // For backwards compatibility. template <class Arc> void Replace(const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>> &ifst_array, MutableFst<Arc> *ofst, typename Arc::Label root, bool epsilon_on_replace) { Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(root, epsilon_on_replace)); } template <class Arc> void Replace(const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>> &ifst_array, MutableFst<Arc> *ofst, typename Arc::Label root) { Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(root)); } } // namespace fst #endif // FST_REPLACE_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/bin/Makefile.in
# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @HAVE_BIN_TRUE@bin_PROGRAMS = fstarcsort$(EXEEXT) fstclosure$(EXEEXT) \ @HAVE_BIN_TRUE@ fstcompile$(EXEEXT) fstcompose$(EXEEXT) \ @HAVE_BIN_TRUE@ fstconcat$(EXEEXT) fstconnect$(EXEEXT) \ @HAVE_BIN_TRUE@ fstconvert$(EXEEXT) fstdeterminize$(EXEEXT) \ @HAVE_BIN_TRUE@ fstdifference$(EXEEXT) fstdisambiguate$(EXEEXT) \ @HAVE_BIN_TRUE@ fstdraw$(EXEEXT) fstencode$(EXEEXT) \ @HAVE_BIN_TRUE@ fstepsnormalize$(EXEEXT) fstequal$(EXEEXT) \ @HAVE_BIN_TRUE@ fstequivalent$(EXEEXT) fstinfo$(EXEEXT) \ @HAVE_BIN_TRUE@ fstintersect$(EXEEXT) fstinvert$(EXEEXT) \ @HAVE_BIN_TRUE@ fstisomorphic$(EXEEXT) fstmap$(EXEEXT) \ @HAVE_BIN_TRUE@ fstminimize$(EXEEXT) fstprint$(EXEEXT) \ @HAVE_BIN_TRUE@ fstproject$(EXEEXT) fstprune$(EXEEXT) \ @HAVE_BIN_TRUE@ fstpush$(EXEEXT) fstrandgen$(EXEEXT) \ @HAVE_BIN_TRUE@ fstrelabel$(EXEEXT) fstreplace$(EXEEXT) \ @HAVE_BIN_TRUE@ fstreverse$(EXEEXT) fstreweight$(EXEEXT) \ @HAVE_BIN_TRUE@ fstrmepsilon$(EXEEXT) \ @HAVE_BIN_TRUE@ fstshortestdistance$(EXEEXT) \ @HAVE_BIN_TRUE@ fstshortestpath$(EXEEXT) fstsymbols$(EXEEXT) \ @HAVE_BIN_TRUE@ fstsynchronize$(EXEEXT) fsttopsort$(EXEEXT) \ @HAVE_BIN_TRUE@ fstunion$(EXEEXT) subdir = src/bin ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_python_devel.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/include/fst/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(bindir)" PROGRAMS = $(bin_PROGRAMS) am__fstarcsort_SOURCES_DIST = fstarcsort.cc fstarcsort-main.cc @HAVE_BIN_TRUE@am_fstarcsort_OBJECTS = fstarcsort.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstarcsort-main.$(OBJEXT) fstarcsort_OBJECTS = $(am_fstarcsort_OBJECTS) fstarcsort_LDADD = $(LDADD) am__DEPENDENCIES_1 = fstarcsort_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am__fstclosure_SOURCES_DIST = fstclosure.cc fstclosure-main.cc @HAVE_BIN_TRUE@am_fstclosure_OBJECTS = fstclosure.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstclosure-main.$(OBJEXT) fstclosure_OBJECTS = $(am_fstclosure_OBJECTS) fstclosure_LDADD = $(LDADD) fstclosure_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstcompile_SOURCES_DIST = fstcompile.cc fstcompile-main.cc @HAVE_BIN_TRUE@am_fstcompile_OBJECTS = fstcompile.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstcompile-main.$(OBJEXT) fstcompile_OBJECTS = $(am_fstcompile_OBJECTS) fstcompile_LDADD = $(LDADD) fstcompile_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstcompose_SOURCES_DIST = fstcompose.cc fstcompose-main.cc @HAVE_BIN_TRUE@am_fstcompose_OBJECTS = fstcompose.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstcompose-main.$(OBJEXT) fstcompose_OBJECTS = $(am_fstcompose_OBJECTS) fstcompose_LDADD = $(LDADD) fstcompose_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstconcat_SOURCES_DIST = fstconcat.cc fstconcat-main.cc @HAVE_BIN_TRUE@am_fstconcat_OBJECTS = fstconcat.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstconcat-main.$(OBJEXT) fstconcat_OBJECTS = $(am_fstconcat_OBJECTS) fstconcat_LDADD = $(LDADD) fstconcat_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstconnect_SOURCES_DIST = fstconnect.cc fstconnect-main.cc @HAVE_BIN_TRUE@am_fstconnect_OBJECTS = fstconnect.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstconnect-main.$(OBJEXT) fstconnect_OBJECTS = $(am_fstconnect_OBJECTS) fstconnect_LDADD = $(LDADD) fstconnect_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstconvert_SOURCES_DIST = fstconvert.cc fstconvert-main.cc @HAVE_BIN_TRUE@am_fstconvert_OBJECTS = fstconvert.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstconvert-main.$(OBJEXT) fstconvert_OBJECTS = $(am_fstconvert_OBJECTS) fstconvert_LDADD = $(LDADD) fstconvert_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstdeterminize_SOURCES_DIST = fstdeterminize.cc \ fstdeterminize-main.cc @HAVE_BIN_TRUE@am_fstdeterminize_OBJECTS = fstdeterminize.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstdeterminize-main.$(OBJEXT) fstdeterminize_OBJECTS = $(am_fstdeterminize_OBJECTS) fstdeterminize_LDADD = $(LDADD) fstdeterminize_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fstdifference_SOURCES_DIST = fstdifference.cc \ fstdifference-main.cc @HAVE_BIN_TRUE@am_fstdifference_OBJECTS = fstdifference.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstdifference-main.$(OBJEXT) fstdifference_OBJECTS = $(am_fstdifference_OBJECTS) fstdifference_LDADD = $(LDADD) fstdifference_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fstdisambiguate_SOURCES_DIST = fstdisambiguate.cc \ fstdisambiguate-main.cc @HAVE_BIN_TRUE@am_fstdisambiguate_OBJECTS = fstdisambiguate.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstdisambiguate-main.$(OBJEXT) fstdisambiguate_OBJECTS = $(am_fstdisambiguate_OBJECTS) fstdisambiguate_LDADD = $(LDADD) fstdisambiguate_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fstdraw_SOURCES_DIST = fstdraw.cc fstdraw-main.cc @HAVE_BIN_TRUE@am_fstdraw_OBJECTS = fstdraw.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstdraw-main.$(OBJEXT) fstdraw_OBJECTS = $(am_fstdraw_OBJECTS) fstdraw_LDADD = $(LDADD) fstdraw_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstencode_SOURCES_DIST = fstencode.cc fstencode-main.cc @HAVE_BIN_TRUE@am_fstencode_OBJECTS = fstencode.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstencode-main.$(OBJEXT) fstencode_OBJECTS = $(am_fstencode_OBJECTS) fstencode_LDADD = $(LDADD) fstencode_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstepsnormalize_SOURCES_DIST = fstepsnormalize.cc \ fstepsnormalize-main.cc @HAVE_BIN_TRUE@am_fstepsnormalize_OBJECTS = fstepsnormalize.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstepsnormalize-main.$(OBJEXT) fstepsnormalize_OBJECTS = $(am_fstepsnormalize_OBJECTS) fstepsnormalize_LDADD = $(LDADD) fstepsnormalize_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fstequal_SOURCES_DIST = fstequal.cc fstequal-main.cc @HAVE_BIN_TRUE@am_fstequal_OBJECTS = fstequal.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstequal-main.$(OBJEXT) fstequal_OBJECTS = $(am_fstequal_OBJECTS) fstequal_LDADD = $(LDADD) fstequal_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstequivalent_SOURCES_DIST = fstequivalent.cc \ fstequivalent-main.cc @HAVE_BIN_TRUE@am_fstequivalent_OBJECTS = fstequivalent.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstequivalent-main.$(OBJEXT) fstequivalent_OBJECTS = $(am_fstequivalent_OBJECTS) fstequivalent_LDADD = $(LDADD) fstequivalent_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fstinfo_SOURCES_DIST = fstinfo.cc fstinfo-main.cc @HAVE_BIN_TRUE@am_fstinfo_OBJECTS = fstinfo.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstinfo-main.$(OBJEXT) fstinfo_OBJECTS = $(am_fstinfo_OBJECTS) fstinfo_LDADD = $(LDADD) fstinfo_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstintersect_SOURCES_DIST = fstintersect.cc fstintersect-main.cc @HAVE_BIN_TRUE@am_fstintersect_OBJECTS = fstintersect.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstintersect-main.$(OBJEXT) fstintersect_OBJECTS = $(am_fstintersect_OBJECTS) fstintersect_LDADD = $(LDADD) fstintersect_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstinvert_SOURCES_DIST = fstinvert.cc fstinvert-main.cc @HAVE_BIN_TRUE@am_fstinvert_OBJECTS = fstinvert.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstinvert-main.$(OBJEXT) fstinvert_OBJECTS = $(am_fstinvert_OBJECTS) fstinvert_LDADD = $(LDADD) fstinvert_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstisomorphic_SOURCES_DIST = fstisomorphic.cc \ fstisomorphic-main.cc @HAVE_BIN_TRUE@am_fstisomorphic_OBJECTS = fstisomorphic.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstisomorphic-main.$(OBJEXT) fstisomorphic_OBJECTS = $(am_fstisomorphic_OBJECTS) fstisomorphic_LDADD = $(LDADD) fstisomorphic_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fstmap_SOURCES_DIST = fstmap.cc fstmap-main.cc @HAVE_BIN_TRUE@am_fstmap_OBJECTS = fstmap.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstmap-main.$(OBJEXT) fstmap_OBJECTS = $(am_fstmap_OBJECTS) fstmap_LDADD = $(LDADD) fstmap_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstminimize_SOURCES_DIST = fstminimize.cc fstminimize-main.cc @HAVE_BIN_TRUE@am_fstminimize_OBJECTS = fstminimize.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstminimize-main.$(OBJEXT) fstminimize_OBJECTS = $(am_fstminimize_OBJECTS) fstminimize_LDADD = $(LDADD) fstminimize_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstprint_SOURCES_DIST = fstprint.cc fstprint-main.cc @HAVE_BIN_TRUE@am_fstprint_OBJECTS = fstprint.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstprint-main.$(OBJEXT) fstprint_OBJECTS = $(am_fstprint_OBJECTS) fstprint_LDADD = $(LDADD) fstprint_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstproject_SOURCES_DIST = fstproject.cc fstproject-main.cc @HAVE_BIN_TRUE@am_fstproject_OBJECTS = fstproject.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstproject-main.$(OBJEXT) fstproject_OBJECTS = $(am_fstproject_OBJECTS) fstproject_LDADD = $(LDADD) fstproject_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstprune_SOURCES_DIST = fstprune.cc fstprune-main.cc @HAVE_BIN_TRUE@am_fstprune_OBJECTS = fstprune.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstprune-main.$(OBJEXT) fstprune_OBJECTS = $(am_fstprune_OBJECTS) fstprune_LDADD = $(LDADD) fstprune_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstpush_SOURCES_DIST = fstpush.cc fstpush-main.cc @HAVE_BIN_TRUE@am_fstpush_OBJECTS = fstpush.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstpush-main.$(OBJEXT) fstpush_OBJECTS = $(am_fstpush_OBJECTS) fstpush_LDADD = $(LDADD) fstpush_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstrandgen_SOURCES_DIST = fstrandgen.cc fstrandgen-main.cc @HAVE_BIN_TRUE@am_fstrandgen_OBJECTS = fstrandgen.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstrandgen-main.$(OBJEXT) fstrandgen_OBJECTS = $(am_fstrandgen_OBJECTS) fstrandgen_LDADD = $(LDADD) fstrandgen_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstrelabel_SOURCES_DIST = fstrelabel.cc fstrelabel-main.cc @HAVE_BIN_TRUE@am_fstrelabel_OBJECTS = fstrelabel.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstrelabel-main.$(OBJEXT) fstrelabel_OBJECTS = $(am_fstrelabel_OBJECTS) fstrelabel_LDADD = $(LDADD) fstrelabel_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstreplace_SOURCES_DIST = fstreplace.cc fstreplace-main.cc @HAVE_BIN_TRUE@am_fstreplace_OBJECTS = fstreplace.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstreplace-main.$(OBJEXT) fstreplace_OBJECTS = $(am_fstreplace_OBJECTS) fstreplace_LDADD = $(LDADD) fstreplace_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstreverse_SOURCES_DIST = fstreverse.cc fstreverse-main.cc @HAVE_BIN_TRUE@am_fstreverse_OBJECTS = fstreverse.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstreverse-main.$(OBJEXT) fstreverse_OBJECTS = $(am_fstreverse_OBJECTS) fstreverse_LDADD = $(LDADD) fstreverse_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstreweight_SOURCES_DIST = fstreweight.cc fstreweight-main.cc @HAVE_BIN_TRUE@am_fstreweight_OBJECTS = fstreweight.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstreweight-main.$(OBJEXT) fstreweight_OBJECTS = $(am_fstreweight_OBJECTS) fstreweight_LDADD = $(LDADD) fstreweight_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstrmepsilon_SOURCES_DIST = fstrmepsilon.cc fstrmepsilon-main.cc @HAVE_BIN_TRUE@am_fstrmepsilon_OBJECTS = fstrmepsilon.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstrmepsilon-main.$(OBJEXT) fstrmepsilon_OBJECTS = $(am_fstrmepsilon_OBJECTS) fstrmepsilon_LDADD = $(LDADD) fstrmepsilon_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstshortestdistance_SOURCES_DIST = fstshortestdistance.cc \ fstshortestdistance-main.cc @HAVE_BIN_TRUE@am_fstshortestdistance_OBJECTS = \ @HAVE_BIN_TRUE@ fstshortestdistance.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstshortestdistance-main.$(OBJEXT) fstshortestdistance_OBJECTS = $(am_fstshortestdistance_OBJECTS) fstshortestdistance_LDADD = $(LDADD) fstshortestdistance_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fstshortestpath_SOURCES_DIST = fstshortestpath.cc \ fstshortestpath-main.cc @HAVE_BIN_TRUE@am_fstshortestpath_OBJECTS = fstshortestpath.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstshortestpath-main.$(OBJEXT) fstshortestpath_OBJECTS = $(am_fstshortestpath_OBJECTS) fstshortestpath_LDADD = $(LDADD) fstshortestpath_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fstsymbols_SOURCES_DIST = fstsymbols.cc fstsymbols-main.cc @HAVE_BIN_TRUE@am_fstsymbols_OBJECTS = fstsymbols.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstsymbols-main.$(OBJEXT) fstsymbols_OBJECTS = $(am_fstsymbols_OBJECTS) fstsymbols_LDADD = $(LDADD) fstsymbols_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstsynchronize_SOURCES_DIST = fstsynchronize.cc \ fstsynchronize-main.cc @HAVE_BIN_TRUE@am_fstsynchronize_OBJECTS = fstsynchronize.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstsynchronize-main.$(OBJEXT) fstsynchronize_OBJECTS = $(am_fstsynchronize_OBJECTS) fstsynchronize_LDADD = $(LDADD) fstsynchronize_DEPENDENCIES = ../script/libfstscript.la \ ../lib/libfst.la $(am__DEPENDENCIES_1) am__fsttopsort_SOURCES_DIST = fsttopsort.cc fsttopsort-main.cc @HAVE_BIN_TRUE@am_fsttopsort_OBJECTS = fsttopsort.$(OBJEXT) \ @HAVE_BIN_TRUE@ fsttopsort-main.$(OBJEXT) fsttopsort_OBJECTS = $(am_fsttopsort_OBJECTS) fsttopsort_LDADD = $(LDADD) fsttopsort_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) am__fstunion_SOURCES_DIST = fstunion.cc fstunion-main.cc @HAVE_BIN_TRUE@am_fstunion_OBJECTS = fstunion.$(OBJEXT) \ @HAVE_BIN_TRUE@ fstunion-main.$(OBJEXT) fstunion_OBJECTS = $(am_fstunion_OBJECTS) fstunion_LDADD = $(LDADD) fstunion_DEPENDENCIES = ../script/libfstscript.la ../lib/libfst.la \ $(am__DEPENDENCIES_1) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(fstarcsort_SOURCES) $(fstclosure_SOURCES) \ $(fstcompile_SOURCES) $(fstcompose_SOURCES) \ $(fstconcat_SOURCES) $(fstconnect_SOURCES) \ $(fstconvert_SOURCES) $(fstdeterminize_SOURCES) \ $(fstdifference_SOURCES) $(fstdisambiguate_SOURCES) \ $(fstdraw_SOURCES) $(fstencode_SOURCES) \ $(fstepsnormalize_SOURCES) $(fstequal_SOURCES) \ $(fstequivalent_SOURCES) $(fstinfo_SOURCES) \ $(fstintersect_SOURCES) $(fstinvert_SOURCES) \ $(fstisomorphic_SOURCES) $(fstmap_SOURCES) \ $(fstminimize_SOURCES) $(fstprint_SOURCES) \ $(fstproject_SOURCES) $(fstprune_SOURCES) $(fstpush_SOURCES) \ $(fstrandgen_SOURCES) $(fstrelabel_SOURCES) \ $(fstreplace_SOURCES) $(fstreverse_SOURCES) \ $(fstreweight_SOURCES) $(fstrmepsilon_SOURCES) \ $(fstshortestdistance_SOURCES) $(fstshortestpath_SOURCES) \ $(fstsymbols_SOURCES) $(fstsynchronize_SOURCES) \ $(fsttopsort_SOURCES) $(fstunion_SOURCES) DIST_SOURCES = $(am__fstarcsort_SOURCES_DIST) \ $(am__fstclosure_SOURCES_DIST) $(am__fstcompile_SOURCES_DIST) \ $(am__fstcompose_SOURCES_DIST) $(am__fstconcat_SOURCES_DIST) \ $(am__fstconnect_SOURCES_DIST) $(am__fstconvert_SOURCES_DIST) \ $(am__fstdeterminize_SOURCES_DIST) \ $(am__fstdifference_SOURCES_DIST) \ $(am__fstdisambiguate_SOURCES_DIST) \ $(am__fstdraw_SOURCES_DIST) $(am__fstencode_SOURCES_DIST) \ $(am__fstepsnormalize_SOURCES_DIST) \ $(am__fstequal_SOURCES_DIST) $(am__fstequivalent_SOURCES_DIST) \ $(am__fstinfo_SOURCES_DIST) $(am__fstintersect_SOURCES_DIST) \ $(am__fstinvert_SOURCES_DIST) \ $(am__fstisomorphic_SOURCES_DIST) $(am__fstmap_SOURCES_DIST) \ $(am__fstminimize_SOURCES_DIST) $(am__fstprint_SOURCES_DIST) \ $(am__fstproject_SOURCES_DIST) $(am__fstprune_SOURCES_DIST) \ $(am__fstpush_SOURCES_DIST) $(am__fstrandgen_SOURCES_DIST) \ $(am__fstrelabel_SOURCES_DIST) $(am__fstreplace_SOURCES_DIST) \ $(am__fstreverse_SOURCES_DIST) $(am__fstreweight_SOURCES_DIST) \ $(am__fstrmepsilon_SOURCES_DIST) \ $(am__fstshortestdistance_SOURCES_DIST) \ $(am__fstshortestpath_SOURCES_DIST) \ $(am__fstsymbols_SOURCES_DIST) \ $(am__fstsynchronize_SOURCES_DIST) \ $(am__fsttopsort_SOURCES_DIST) $(am__fstunion_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DL_LIBS = @DL_LIBS@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PYTHON = @PYTHON@ PYTHON_CPPFLAGS = @PYTHON_CPPFLAGS@ PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ PYTHON_EXTRA_LDFLAGS = @PYTHON_EXTRA_LDFLAGS@ PYTHON_EXTRA_LIBS = @PYTHON_EXTRA_LIBS@ PYTHON_LDFLAGS = @PYTHON_LDFLAGS@ PYTHON_PLATFORM = @PYTHON_PLATFORM@ PYTHON_PREFIX = @PYTHON_PREFIX@ PYTHON_SITE_PKG = @PYTHON_SITE_PKG@ PYTHON_VERSION = @PYTHON_VERSION@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ libfstdir = @libfstdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ pkgpyexecdir = @pkgpyexecdir@ pkgpythondir = @pkgpythondir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ pyexecdir = @pyexecdir@ pythondir = @pythondir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = -I$(srcdir)/../include -I$(srcdir)/../script $(ICU_FLAGS) LDADD = ../script/libfstscript.la ../lib/libfst.la -lm $(DL_LIBS) @HAVE_BIN_TRUE@fstarcsort_SOURCES = fstarcsort.cc fstarcsort-main.cc @HAVE_BIN_TRUE@fstclosure_SOURCES = fstclosure.cc fstclosure-main.cc @HAVE_BIN_TRUE@fstcompile_SOURCES = fstcompile.cc fstcompile-main.cc @HAVE_BIN_TRUE@fstcompose_SOURCES = fstcompose.cc fstcompose-main.cc @HAVE_BIN_TRUE@fstconcat_SOURCES = fstconcat.cc fstconcat-main.cc @HAVE_BIN_TRUE@fstconnect_SOURCES = fstconnect.cc fstconnect-main.cc @HAVE_BIN_TRUE@fstconvert_SOURCES = fstconvert.cc fstconvert-main.cc @HAVE_BIN_TRUE@fstdeterminize_SOURCES = fstdeterminize.cc fstdeterminize-main.cc @HAVE_BIN_TRUE@fstdifference_SOURCES = fstdifference.cc fstdifference-main.cc @HAVE_BIN_TRUE@fstdisambiguate_SOURCES = fstdisambiguate.cc fstdisambiguate-main.cc @HAVE_BIN_TRUE@fstdraw_SOURCES = fstdraw.cc fstdraw-main.cc @HAVE_BIN_TRUE@fstencode_SOURCES = fstencode.cc fstencode-main.cc @HAVE_BIN_TRUE@fstepsnormalize_SOURCES = fstepsnormalize.cc fstepsnormalize-main.cc @HAVE_BIN_TRUE@fstequal_SOURCES = fstequal.cc fstequal-main.cc @HAVE_BIN_TRUE@fstequivalent_SOURCES = fstequivalent.cc fstequivalent-main.cc @HAVE_BIN_TRUE@fstinfo_SOURCES = fstinfo.cc fstinfo-main.cc @HAVE_BIN_TRUE@fstintersect_SOURCES = fstintersect.cc fstintersect-main.cc @HAVE_BIN_TRUE@fstinvert_SOURCES = fstinvert.cc fstinvert-main.cc @HAVE_BIN_TRUE@fstisomorphic_SOURCES = fstisomorphic.cc fstisomorphic-main.cc @HAVE_BIN_TRUE@fstmap_SOURCES = fstmap.cc fstmap-main.cc @HAVE_BIN_TRUE@fstminimize_SOURCES = fstminimize.cc fstminimize-main.cc @HAVE_BIN_TRUE@fstprint_SOURCES = fstprint.cc fstprint-main.cc @HAVE_BIN_TRUE@fstproject_SOURCES = fstproject.cc fstproject-main.cc @HAVE_BIN_TRUE@fstprune_SOURCES = fstprune.cc fstprune-main.cc @HAVE_BIN_TRUE@fstpush_SOURCES = fstpush.cc fstpush-main.cc @HAVE_BIN_TRUE@fstrandgen_SOURCES = fstrandgen.cc fstrandgen-main.cc @HAVE_BIN_TRUE@fstrelabel_SOURCES = fstrelabel.cc fstrelabel-main.cc @HAVE_BIN_TRUE@fstreplace_SOURCES = fstreplace.cc fstreplace-main.cc @HAVE_BIN_TRUE@fstreverse_SOURCES = fstreverse.cc fstreverse-main.cc @HAVE_BIN_TRUE@fstreweight_SOURCES = fstreweight.cc fstreweight-main.cc @HAVE_BIN_TRUE@fstrmepsilon_SOURCES = fstrmepsilon.cc fstrmepsilon-main.cc @HAVE_BIN_TRUE@fstshortestdistance_SOURCES = fstshortestdistance.cc fstshortestdistance-main.cc @HAVE_BIN_TRUE@fstshortestpath_SOURCES = fstshortestpath.cc fstshortestpath-main.cc @HAVE_BIN_TRUE@fstsymbols_SOURCES = fstsymbols.cc fstsymbols-main.cc @HAVE_BIN_TRUE@fstsynchronize_SOURCES = fstsynchronize.cc fstsynchronize-main.cc @HAVE_BIN_TRUE@fsttopsort_SOURCES = fsttopsort.cc fsttopsort-main.cc @HAVE_BIN_TRUE@fstunion_SOURCES = fstunion.cc fstunion-main.cc all: all-am .SUFFIXES: .SUFFIXES: .cc .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/bin/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/bin/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list fstarcsort$(EXEEXT): $(fstarcsort_OBJECTS) $(fstarcsort_DEPENDENCIES) $(EXTRA_fstarcsort_DEPENDENCIES) @rm -f fstarcsort$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstarcsort_OBJECTS) $(fstarcsort_LDADD) $(LIBS) fstclosure$(EXEEXT): $(fstclosure_OBJECTS) $(fstclosure_DEPENDENCIES) $(EXTRA_fstclosure_DEPENDENCIES) @rm -f fstclosure$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstclosure_OBJECTS) $(fstclosure_LDADD) $(LIBS) fstcompile$(EXEEXT): $(fstcompile_OBJECTS) $(fstcompile_DEPENDENCIES) $(EXTRA_fstcompile_DEPENDENCIES) @rm -f fstcompile$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstcompile_OBJECTS) $(fstcompile_LDADD) $(LIBS) fstcompose$(EXEEXT): $(fstcompose_OBJECTS) $(fstcompose_DEPENDENCIES) $(EXTRA_fstcompose_DEPENDENCIES) @rm -f fstcompose$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstcompose_OBJECTS) $(fstcompose_LDADD) $(LIBS) fstconcat$(EXEEXT): $(fstconcat_OBJECTS) $(fstconcat_DEPENDENCIES) $(EXTRA_fstconcat_DEPENDENCIES) @rm -f fstconcat$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstconcat_OBJECTS) $(fstconcat_LDADD) $(LIBS) fstconnect$(EXEEXT): $(fstconnect_OBJECTS) $(fstconnect_DEPENDENCIES) $(EXTRA_fstconnect_DEPENDENCIES) @rm -f fstconnect$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstconnect_OBJECTS) $(fstconnect_LDADD) $(LIBS) fstconvert$(EXEEXT): $(fstconvert_OBJECTS) $(fstconvert_DEPENDENCIES) $(EXTRA_fstconvert_DEPENDENCIES) @rm -f fstconvert$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstconvert_OBJECTS) $(fstconvert_LDADD) $(LIBS) fstdeterminize$(EXEEXT): $(fstdeterminize_OBJECTS) $(fstdeterminize_DEPENDENCIES) $(EXTRA_fstdeterminize_DEPENDENCIES) @rm -f fstdeterminize$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstdeterminize_OBJECTS) $(fstdeterminize_LDADD) $(LIBS) fstdifference$(EXEEXT): $(fstdifference_OBJECTS) $(fstdifference_DEPENDENCIES) $(EXTRA_fstdifference_DEPENDENCIES) @rm -f fstdifference$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstdifference_OBJECTS) $(fstdifference_LDADD) $(LIBS) fstdisambiguate$(EXEEXT): $(fstdisambiguate_OBJECTS) $(fstdisambiguate_DEPENDENCIES) $(EXTRA_fstdisambiguate_DEPENDENCIES) @rm -f fstdisambiguate$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstdisambiguate_OBJECTS) $(fstdisambiguate_LDADD) $(LIBS) fstdraw$(EXEEXT): $(fstdraw_OBJECTS) $(fstdraw_DEPENDENCIES) $(EXTRA_fstdraw_DEPENDENCIES) @rm -f fstdraw$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstdraw_OBJECTS) $(fstdraw_LDADD) $(LIBS) fstencode$(EXEEXT): $(fstencode_OBJECTS) $(fstencode_DEPENDENCIES) $(EXTRA_fstencode_DEPENDENCIES) @rm -f fstencode$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstencode_OBJECTS) $(fstencode_LDADD) $(LIBS) fstepsnormalize$(EXEEXT): $(fstepsnormalize_OBJECTS) $(fstepsnormalize_DEPENDENCIES) $(EXTRA_fstepsnormalize_DEPENDENCIES) @rm -f fstepsnormalize$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstepsnormalize_OBJECTS) $(fstepsnormalize_LDADD) $(LIBS) fstequal$(EXEEXT): $(fstequal_OBJECTS) $(fstequal_DEPENDENCIES) $(EXTRA_fstequal_DEPENDENCIES) @rm -f fstequal$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstequal_OBJECTS) $(fstequal_LDADD) $(LIBS) fstequivalent$(EXEEXT): $(fstequivalent_OBJECTS) $(fstequivalent_DEPENDENCIES) $(EXTRA_fstequivalent_DEPENDENCIES) @rm -f fstequivalent$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstequivalent_OBJECTS) $(fstequivalent_LDADD) $(LIBS) fstinfo$(EXEEXT): $(fstinfo_OBJECTS) $(fstinfo_DEPENDENCIES) $(EXTRA_fstinfo_DEPENDENCIES) @rm -f fstinfo$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstinfo_OBJECTS) $(fstinfo_LDADD) $(LIBS) fstintersect$(EXEEXT): $(fstintersect_OBJECTS) $(fstintersect_DEPENDENCIES) $(EXTRA_fstintersect_DEPENDENCIES) @rm -f fstintersect$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstintersect_OBJECTS) $(fstintersect_LDADD) $(LIBS) fstinvert$(EXEEXT): $(fstinvert_OBJECTS) $(fstinvert_DEPENDENCIES) $(EXTRA_fstinvert_DEPENDENCIES) @rm -f fstinvert$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstinvert_OBJECTS) $(fstinvert_LDADD) $(LIBS) fstisomorphic$(EXEEXT): $(fstisomorphic_OBJECTS) $(fstisomorphic_DEPENDENCIES) $(EXTRA_fstisomorphic_DEPENDENCIES) @rm -f fstisomorphic$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstisomorphic_OBJECTS) $(fstisomorphic_LDADD) $(LIBS) fstmap$(EXEEXT): $(fstmap_OBJECTS) $(fstmap_DEPENDENCIES) $(EXTRA_fstmap_DEPENDENCIES) @rm -f fstmap$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstmap_OBJECTS) $(fstmap_LDADD) $(LIBS) fstminimize$(EXEEXT): $(fstminimize_OBJECTS) $(fstminimize_DEPENDENCIES) $(EXTRA_fstminimize_DEPENDENCIES) @rm -f fstminimize$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstminimize_OBJECTS) $(fstminimize_LDADD) $(LIBS) fstprint$(EXEEXT): $(fstprint_OBJECTS) $(fstprint_DEPENDENCIES) $(EXTRA_fstprint_DEPENDENCIES) @rm -f fstprint$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstprint_OBJECTS) $(fstprint_LDADD) $(LIBS) fstproject$(EXEEXT): $(fstproject_OBJECTS) $(fstproject_DEPENDENCIES) $(EXTRA_fstproject_DEPENDENCIES) @rm -f fstproject$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstproject_OBJECTS) $(fstproject_LDADD) $(LIBS) fstprune$(EXEEXT): $(fstprune_OBJECTS) $(fstprune_DEPENDENCIES) $(EXTRA_fstprune_DEPENDENCIES) @rm -f fstprune$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstprune_OBJECTS) $(fstprune_LDADD) $(LIBS) fstpush$(EXEEXT): $(fstpush_OBJECTS) $(fstpush_DEPENDENCIES) $(EXTRA_fstpush_DEPENDENCIES) @rm -f fstpush$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstpush_OBJECTS) $(fstpush_LDADD) $(LIBS) fstrandgen$(EXEEXT): $(fstrandgen_OBJECTS) $(fstrandgen_DEPENDENCIES) $(EXTRA_fstrandgen_DEPENDENCIES) @rm -f fstrandgen$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstrandgen_OBJECTS) $(fstrandgen_LDADD) $(LIBS) fstrelabel$(EXEEXT): $(fstrelabel_OBJECTS) $(fstrelabel_DEPENDENCIES) $(EXTRA_fstrelabel_DEPENDENCIES) @rm -f fstrelabel$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstrelabel_OBJECTS) $(fstrelabel_LDADD) $(LIBS) fstreplace$(EXEEXT): $(fstreplace_OBJECTS) $(fstreplace_DEPENDENCIES) $(EXTRA_fstreplace_DEPENDENCIES) @rm -f fstreplace$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstreplace_OBJECTS) $(fstreplace_LDADD) $(LIBS) fstreverse$(EXEEXT): $(fstreverse_OBJECTS) $(fstreverse_DEPENDENCIES) $(EXTRA_fstreverse_DEPENDENCIES) @rm -f fstreverse$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstreverse_OBJECTS) $(fstreverse_LDADD) $(LIBS) fstreweight$(EXEEXT): $(fstreweight_OBJECTS) $(fstreweight_DEPENDENCIES) $(EXTRA_fstreweight_DEPENDENCIES) @rm -f fstreweight$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstreweight_OBJECTS) $(fstreweight_LDADD) $(LIBS) fstrmepsilon$(EXEEXT): $(fstrmepsilon_OBJECTS) $(fstrmepsilon_DEPENDENCIES) $(EXTRA_fstrmepsilon_DEPENDENCIES) @rm -f fstrmepsilon$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstrmepsilon_OBJECTS) $(fstrmepsilon_LDADD) $(LIBS) fstshortestdistance$(EXEEXT): $(fstshortestdistance_OBJECTS) $(fstshortestdistance_DEPENDENCIES) $(EXTRA_fstshortestdistance_DEPENDENCIES) @rm -f fstshortestdistance$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstshortestdistance_OBJECTS) $(fstshortestdistance_LDADD) $(LIBS) fstshortestpath$(EXEEXT): $(fstshortestpath_OBJECTS) $(fstshortestpath_DEPENDENCIES) $(EXTRA_fstshortestpath_DEPENDENCIES) @rm -f fstshortestpath$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstshortestpath_OBJECTS) $(fstshortestpath_LDADD) $(LIBS) fstsymbols$(EXEEXT): $(fstsymbols_OBJECTS) $(fstsymbols_DEPENDENCIES) $(EXTRA_fstsymbols_DEPENDENCIES) @rm -f fstsymbols$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstsymbols_OBJECTS) $(fstsymbols_LDADD) $(LIBS) fstsynchronize$(EXEEXT): $(fstsynchronize_OBJECTS) $(fstsynchronize_DEPENDENCIES) $(EXTRA_fstsynchronize_DEPENDENCIES) @rm -f fstsynchronize$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstsynchronize_OBJECTS) $(fstsynchronize_LDADD) $(LIBS) fsttopsort$(EXEEXT): $(fsttopsort_OBJECTS) $(fsttopsort_DEPENDENCIES) $(EXTRA_fsttopsort_DEPENDENCIES) @rm -f fsttopsort$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fsttopsort_OBJECTS) $(fsttopsort_LDADD) $(LIBS) fstunion$(EXEEXT): $(fstunion_OBJECTS) $(fstunion_DEPENDENCIES) $(EXTRA_fstunion_DEPENDENCIES) @rm -f fstunion$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fstunion_OBJECTS) $(fstunion_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstarcsort-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstarcsort.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstclosure-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstclosure.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstcompile-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstcompile.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstcompose-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstcompose.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstconcat-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstconcat.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstconnect-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstconnect.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstconvert-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstconvert.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstdeterminize-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstdeterminize.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstdifference-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstdifference.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstdisambiguate-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstdisambiguate.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstdraw-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstdraw.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstencode-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstencode.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstepsnormalize-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstepsnormalize.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstequal-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstequal.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstequivalent-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstequivalent.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstinfo-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstinfo.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstintersect-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstintersect.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstinvert-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstinvert.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstisomorphic-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstisomorphic.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstmap-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstmap.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstminimize-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstminimize.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstprint-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstprint.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstproject-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstproject.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstprune-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstprune.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstpush-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstpush.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstrandgen-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstrandgen.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstrelabel-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstrelabel.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstreplace-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstreplace.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstreverse-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstreverse.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstreweight-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstreweight.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstrmepsilon-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstrmepsilon.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstshortestdistance-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstshortestdistance.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstshortestpath-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstshortestpath.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstsymbols-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstsymbols.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstsynchronize-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstsynchronize.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fsttopsort-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fsttopsort.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstunion-main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstunion.Po@am__quote@ .cc.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cc.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cc.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(PROGRAMS) installdirs: for dir in "$(DESTDIR)$(bindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-binPROGRAMS \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-binPROGRAMS .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/compat.h
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_LIB_COMPAT_H_ #define FST_LIB_COMPAT_H_ #include <climits> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> // Makes copy constructor and operator= private // Deprecated: now just use =delete. #define DISALLOW_COPY_AND_ASSIGN(type) \ type(const type&); \ void operator=(const type&) #if defined(__GNUC__) || defined(__clang__) #define OPENFST_DEPRECATED(message) __attribute__((deprecated(message))) #elif defined(_MSC_VER) #define OPENFST_DEPRECATED(message) __declspec(deprecated(message)) #else #define OPENFST_DEPRECATED(message) #endif #include <fst/config.h> #include <fst/types.h> #include <fst/lock.h> #include <fst/flags.h> #include <fst/log.h> #include <fst/icu.h> using std::string; void FailedNewHandler(); namespace fst { // Downcasting. template<typename To, typename From> inline To down_cast(From* f) { return static_cast<To>(f); } // Bitcasting. template <class Dest, class Source> inline Dest bit_cast(const Source &source) { static_assert(sizeof(Dest) == sizeof(Source), "Bitcasting unsafe for specified types"); Dest dest; memcpy(&dest, &source, sizeof(dest)); return dest; } // Check sums class CheckSummer { public: CheckSummer() : count_(0) { check_sum_.resize(kCheckSumLength, '\0'); } void Reset() { count_ = 0; for (int i = 0; i < kCheckSumLength; ++i) check_sum_[i] = '\0'; } void Update(void const *data, int size) { const char *p = reinterpret_cast<const char *>(data); for (int i = 0; i < size; ++i) { check_sum_[(count_++) % kCheckSumLength] ^= p[i]; } } void Update(string const &data) { for (int i = 0; i < data.size(); ++i) { check_sum_[(count_++) % kCheckSumLength] ^= data[i]; } } string Digest() { return check_sum_; } private: static const int kCheckSumLength = 32; int count_; string check_sum_; CheckSummer(const CheckSummer &) = delete; CheckSummer &operator=(const CheckSummer &) = delete; }; } // namespace fst #endif // FST_LIB_COMPAT_H_
0
coqui_public_repos/STT/native_client
coqui_public_repos/STT/native_client/ctcdecode/output.h
#ifndef OUTPUT_H_ #define OUTPUT_H_ #include <vector> /* Struct for the beam search output, containing the tokens based on the vocabulary indices, and the timesteps * for each token in the beam search output */ struct Output { double confidence; std::vector<unsigned int> tokens; std::vector<unsigned int> timesteps; std::vector<std::vector<std::pair<int, double>>> probs; }; struct FlashlightOutput { double aggregate_score; double acoustic_model_score; double language_model_score; std::vector<std::string> words; std::vector<int> tokens; }; #endif // OUTPUT_H_
0
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/test/Makefile.in
# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = fst_test$(EXEEXT) weight_test$(EXEEXT) \ algo_test_log$(EXEEXT) algo_test_tropical$(EXEEXT) \ algo_test_minmax$(EXEEXT) algo_test_lexicographic$(EXEEXT) \ algo_test_power$(EXEEXT) subdir = src/test ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_python_devel.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h \ $(top_builddir)/src/include/fst/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__objects_1 = algo_test_lexicographic-algo_test.$(OBJEXT) am_algo_test_lexicographic_OBJECTS = $(am__objects_1) algo_test_lexicographic_OBJECTS = \ $(am_algo_test_lexicographic_OBJECTS) algo_test_lexicographic_LDADD = $(LDADD) am__DEPENDENCIES_1 = algo_test_lexicographic_DEPENDENCIES = ../lib/libfst.la \ $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am__objects_2 = algo_test_log-algo_test.$(OBJEXT) am_algo_test_log_OBJECTS = $(am__objects_2) algo_test_log_OBJECTS = $(am_algo_test_log_OBJECTS) algo_test_log_LDADD = $(LDADD) algo_test_log_DEPENDENCIES = ../lib/libfst.la $(am__DEPENDENCIES_1) am__objects_3 = algo_test_minmax-algo_test.$(OBJEXT) am_algo_test_minmax_OBJECTS = $(am__objects_3) algo_test_minmax_OBJECTS = $(am_algo_test_minmax_OBJECTS) algo_test_minmax_LDADD = $(LDADD) algo_test_minmax_DEPENDENCIES = ../lib/libfst.la $(am__DEPENDENCIES_1) am__objects_4 = algo_test_power-algo_test.$(OBJEXT) am_algo_test_power_OBJECTS = $(am__objects_4) algo_test_power_OBJECTS = $(am_algo_test_power_OBJECTS) algo_test_power_LDADD = $(LDADD) algo_test_power_DEPENDENCIES = ../lib/libfst.la $(am__DEPENDENCIES_1) am__objects_5 = algo_test_tropical-algo_test.$(OBJEXT) am_algo_test_tropical_OBJECTS = $(am__objects_5) algo_test_tropical_OBJECTS = $(am_algo_test_tropical_OBJECTS) algo_test_tropical_LDADD = $(LDADD) algo_test_tropical_DEPENDENCIES = ../lib/libfst.la \ $(am__DEPENDENCIES_1) am_fst_test_OBJECTS = fst_test.$(OBJEXT) fst_test_OBJECTS = $(am_fst_test_OBJECTS) fst_test_LDADD = $(LDADD) fst_test_DEPENDENCIES = ../lib/libfst.la $(am__DEPENDENCIES_1) am_weight_test_OBJECTS = weight_test.$(OBJEXT) weight_test_OBJECTS = $(am_weight_test_OBJECTS) weight_test_LDADD = $(LDADD) weight_test_DEPENDENCIES = ../lib/libfst.la $(am__DEPENDENCIES_1) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(algo_test_lexicographic_SOURCES) $(algo_test_log_SOURCES) \ $(algo_test_minmax_SOURCES) $(algo_test_power_SOURCES) \ $(algo_test_tropical_SOURCES) $(fst_test_SOURCES) \ $(weight_test_SOURCES) DIST_SOURCES = $(algo_test_lexicographic_SOURCES) \ $(algo_test_log_SOURCES) $(algo_test_minmax_SOURCES) \ $(algo_test_power_SOURCES) $(algo_test_tropical_SOURCES) \ $(fst_test_SOURCES) $(weight_test_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp \ $(top_srcdir)/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DL_LIBS = @DL_LIBS@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PYTHON = @PYTHON@ PYTHON_CPPFLAGS = @PYTHON_CPPFLAGS@ PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ PYTHON_EXTRA_LDFLAGS = @PYTHON_EXTRA_LDFLAGS@ PYTHON_EXTRA_LIBS = @PYTHON_EXTRA_LIBS@ PYTHON_LDFLAGS = @PYTHON_LDFLAGS@ PYTHON_PLATFORM = @PYTHON_PLATFORM@ PYTHON_PREFIX = @PYTHON_PREFIX@ PYTHON_SITE_PKG = @PYTHON_SITE_PKG@ PYTHON_VERSION = @PYTHON_VERSION@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ libfstdir = @libfstdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ pkgpyexecdir = @pkgpyexecdir@ pkgpythondir = @pkgpythondir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ pyexecdir = @pyexecdir@ pythondir = @pythondir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = -I$(srcdir)/../include $(ICU_CPPFLAGS) LDADD = ../lib/libfst.la -lm $(DL_LIBS) fst_test_SOURCES = fst_test.cc weight_test_SOURCES = weight_test.cc algo_test_SOURCES = algo_test.cc algo_test_log_SOURCES = $(algo_test_SOURCES) algo_test_log_CPPFLAGS = -DTEST_LOG $(AM_CPPFLAGS) algo_test_tropical_SOURCES = $(algo_test_SOURCES) algo_test_tropical_CPPFLAGS = -DTEST_TROPICAL $(AM_CPPFLAGS) algo_test_minmax_SOURCES = $(algo_test_SOURCES) algo_test_minmax_CPPFLAGS = -DTEST_MINMAX $(AM_CPPFLAGS) algo_test_lexicographic_SOURCES = $(algo_test_SOURCES) algo_test_lexicographic_CPPFLAGS = -DTEST_LEXICOGRAPHIC $(AM_CPPFLAGS) algo_test_power_SOURCES = $(algo_test_SOURCES) algo_test_power_CPPFLAGS = -DTEST_POWER $(AM_CPPFLAGS) TESTS = $(check_PROGRAMS) all: all-am .SUFFIXES: .SUFFIXES: .cc .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/test/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list algo_test_lexicographic$(EXEEXT): $(algo_test_lexicographic_OBJECTS) $(algo_test_lexicographic_DEPENDENCIES) $(EXTRA_algo_test_lexicographic_DEPENDENCIES) @rm -f algo_test_lexicographic$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(algo_test_lexicographic_OBJECTS) $(algo_test_lexicographic_LDADD) $(LIBS) algo_test_log$(EXEEXT): $(algo_test_log_OBJECTS) $(algo_test_log_DEPENDENCIES) $(EXTRA_algo_test_log_DEPENDENCIES) @rm -f algo_test_log$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(algo_test_log_OBJECTS) $(algo_test_log_LDADD) $(LIBS) algo_test_minmax$(EXEEXT): $(algo_test_minmax_OBJECTS) $(algo_test_minmax_DEPENDENCIES) $(EXTRA_algo_test_minmax_DEPENDENCIES) @rm -f algo_test_minmax$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(algo_test_minmax_OBJECTS) $(algo_test_minmax_LDADD) $(LIBS) algo_test_power$(EXEEXT): $(algo_test_power_OBJECTS) $(algo_test_power_DEPENDENCIES) $(EXTRA_algo_test_power_DEPENDENCIES) @rm -f algo_test_power$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(algo_test_power_OBJECTS) $(algo_test_power_LDADD) $(LIBS) algo_test_tropical$(EXEEXT): $(algo_test_tropical_OBJECTS) $(algo_test_tropical_DEPENDENCIES) $(EXTRA_algo_test_tropical_DEPENDENCIES) @rm -f algo_test_tropical$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(algo_test_tropical_OBJECTS) $(algo_test_tropical_LDADD) $(LIBS) fst_test$(EXEEXT): $(fst_test_OBJECTS) $(fst_test_DEPENDENCIES) $(EXTRA_fst_test_DEPENDENCIES) @rm -f fst_test$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(fst_test_OBJECTS) $(fst_test_LDADD) $(LIBS) weight_test$(EXEEXT): $(weight_test_OBJECTS) $(weight_test_DEPENDENCIES) $(EXTRA_weight_test_DEPENDENCIES) @rm -f weight_test$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(weight_test_OBJECTS) $(weight_test_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/algo_test_lexicographic-algo_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/algo_test_log-algo_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/algo_test_minmax-algo_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/algo_test_power-algo_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/algo_test_tropical-algo_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fst_test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/weight_test.Po@am__quote@ .cc.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cc.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cc.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< algo_test_lexicographic-algo_test.o: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_lexicographic_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_lexicographic-algo_test.o -MD -MP -MF $(DEPDIR)/algo_test_lexicographic-algo_test.Tpo -c -o algo_test_lexicographic-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_lexicographic-algo_test.Tpo $(DEPDIR)/algo_test_lexicographic-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_lexicographic-algo_test.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_lexicographic_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_lexicographic-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc algo_test_lexicographic-algo_test.obj: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_lexicographic_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_lexicographic-algo_test.obj -MD -MP -MF $(DEPDIR)/algo_test_lexicographic-algo_test.Tpo -c -o algo_test_lexicographic-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_lexicographic-algo_test.Tpo $(DEPDIR)/algo_test_lexicographic-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_lexicographic-algo_test.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_lexicographic_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_lexicographic-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` algo_test_log-algo_test.o: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_log_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_log-algo_test.o -MD -MP -MF $(DEPDIR)/algo_test_log-algo_test.Tpo -c -o algo_test_log-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_log-algo_test.Tpo $(DEPDIR)/algo_test_log-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_log-algo_test.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_log_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_log-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc algo_test_log-algo_test.obj: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_log_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_log-algo_test.obj -MD -MP -MF $(DEPDIR)/algo_test_log-algo_test.Tpo -c -o algo_test_log-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_log-algo_test.Tpo $(DEPDIR)/algo_test_log-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_log-algo_test.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_log_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_log-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` algo_test_minmax-algo_test.o: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_minmax_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_minmax-algo_test.o -MD -MP -MF $(DEPDIR)/algo_test_minmax-algo_test.Tpo -c -o algo_test_minmax-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_minmax-algo_test.Tpo $(DEPDIR)/algo_test_minmax-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_minmax-algo_test.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_minmax_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_minmax-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc algo_test_minmax-algo_test.obj: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_minmax_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_minmax-algo_test.obj -MD -MP -MF $(DEPDIR)/algo_test_minmax-algo_test.Tpo -c -o algo_test_minmax-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_minmax-algo_test.Tpo $(DEPDIR)/algo_test_minmax-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_minmax-algo_test.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_minmax_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_minmax-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` algo_test_power-algo_test.o: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_power_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_power-algo_test.o -MD -MP -MF $(DEPDIR)/algo_test_power-algo_test.Tpo -c -o algo_test_power-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_power-algo_test.Tpo $(DEPDIR)/algo_test_power-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_power-algo_test.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_power_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_power-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc algo_test_power-algo_test.obj: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_power_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_power-algo_test.obj -MD -MP -MF $(DEPDIR)/algo_test_power-algo_test.Tpo -c -o algo_test_power-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_power-algo_test.Tpo $(DEPDIR)/algo_test_power-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_power-algo_test.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_power_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_power-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` algo_test_tropical-algo_test.o: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_tropical_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_tropical-algo_test.o -MD -MP -MF $(DEPDIR)/algo_test_tropical-algo_test.Tpo -c -o algo_test_tropical-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_tropical-algo_test.Tpo $(DEPDIR)/algo_test_tropical-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_tropical-algo_test.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_tropical_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_tropical-algo_test.o `test -f 'algo_test.cc' || echo '$(srcdir)/'`algo_test.cc algo_test_tropical-algo_test.obj: algo_test.cc @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_tropical_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT algo_test_tropical-algo_test.obj -MD -MP -MF $(DEPDIR)/algo_test_tropical-algo_test.Tpo -c -o algo_test_tropical-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/algo_test_tropical-algo_test.Tpo $(DEPDIR)/algo_test_tropical-algo_test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='algo_test.cc' object='algo_test_tropical-algo_test.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(algo_test_tropical_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o algo_test_tropical-algo_test.obj `if test -f 'algo_test.cc'; then $(CYGPATH_W) 'algo_test.cc'; else $(CYGPATH_W) '$(srcdir)/algo_test.cc'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? fst_test.log: fst_test$(EXEEXT) @p='fst_test$(EXEEXT)'; \ b='fst_test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) weight_test.log: weight_test$(EXEEXT) @p='weight_test$(EXEEXT)'; \ b='weight_test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) algo_test_log.log: algo_test_log$(EXEEXT) @p='algo_test_log$(EXEEXT)'; \ b='algo_test_log'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) algo_test_tropical.log: algo_test_tropical$(EXEEXT) @p='algo_test_tropical$(EXEEXT)'; \ b='algo_test_tropical'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) algo_test_minmax.log: algo_test_minmax$(EXEEXT) @p='algo_test_minmax$(EXEEXT)'; \ b='algo_test_minmax'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) algo_test_lexicographic.log: algo_test_lexicographic$(EXEEXT) @p='algo_test_lexicographic$(EXEEXT)'; \ b='algo_test_lexicographic'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) algo_test_power.log: algo_test_power$(EXEEXT) @p='algo_test_power$(EXEEXT)'; \ b='algo_test_power'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
0
coqui_public_repos/STT/native_client/kenlm/lm
coqui_public_repos/STT/native_client/kenlm/lm/wrappers/nplm.hh
#ifndef LM_WRAPPERS_NPLM_H #define LM_WRAPPERS_NPLM_H #include "../facade.hh" #include "../max_order.hh" #include "../../util/string_piece.hh" #include <boost/thread/tss.hpp> #include <boost/scoped_ptr.hpp> /* Wrapper to NPLM "by Ashish Vaswani, with contributions from David Chiang * and Victoria Fossum." * http://nlg.isi.edu/software/nplm/ */ namespace nplm { class vocabulary; class neuralLM; } // namespace nplm namespace lm { namespace np { class Vocabulary : public base::Vocabulary { public: Vocabulary(const nplm::vocabulary &vocab); ~Vocabulary(); WordIndex Index(const std::string &str) const; // TODO: lobby them to support StringPiece WordIndex Index(const StringPiece &str) const { return Index(std::string(str.data(), str.size())); } lm::WordIndex NullWord() const { return null_word_; } private: const nplm::vocabulary &vocab_; const lm::WordIndex null_word_; }; // Sorry for imposing my limitations on your code. #define NPLM_MAX_ORDER 7 struct State { WordIndex words[NPLM_MAX_ORDER - 1]; }; class Backend; class Model : public lm::base::ModelFacade<Model, State, Vocabulary> { private: typedef lm::base::ModelFacade<Model, State, Vocabulary> P; public: // Does this look like an NPLM? static bool Recognize(const std::string &file); explicit Model(const std::string &file, std::size_t cache_size = 1 << 20); ~Model(); FullScoreReturn FullScore(const State &from, const WordIndex new_word, State &out_state) const; FullScoreReturn FullScoreForgotState(const WordIndex *context_rbegin, const WordIndex *context_rend, const WordIndex new_word, State &out_state) const; private: boost::scoped_ptr<nplm::neuralLM> base_instance_; mutable boost::thread_specific_ptr<Backend> backend_; Vocabulary vocab_; lm::WordIndex null_word_; const std::size_t cache_size_; }; } // namespace np } // namespace lm #endif // LM_WRAPPERS_NPLM_H
0
coqui_public_repos/STT-models/romanian/itml
coqui_public_repos/STT-models/romanian/itml/v0.1.0/LICENSE
GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <https://www.gnu.org/licenses/>.
0