diff --git a/python/cmusphinx/arpalm.py b/python/cmusphinx/arpalm.py index ce217496..d41ac5e0 100644 --- a/python/cmusphinx/arpalm.py +++ b/python/cmusphinx/arpalm.py @@ -52,7 +52,7 @@ def tokenize(): for x in spam.strip().split(): yield x def fail(msg): - raise RuntimeError, msg + raise RuntimeError(msg) t = tokenize() if t.next() != '{': fail("Expected {") @@ -143,7 +143,7 @@ def normalize(self): Normalize probabilities. """ for c in self.classes: - t = sum(self.classes[c].itervalues()) + t = sum(self.classes[c].values()) if t != 0: for w in self.classes[c]: self.classes[c][w] /= t @@ -228,7 +228,7 @@ def read(self, path): # Read unigrams and create word id list spam = fh.readline().rstrip() if spam != "\\1-grams:": - raise Exception, "1-grams marker not found" + raise Exception("1-grams marker not found") # ID to word mapping self.widmap = [] wordid = 0 @@ -268,7 +268,7 @@ def read(self, path): ng = tuple(spam[1:]) b = 0.0 else: - raise RuntimeError, "Found %d-gram in %d-gram section" % (len(spam)-1, n) + raise RuntimeError("Found %d-gram in %d-gram section" % (len(spam)-1, n)) # N-Gram info self.ngrams[n-1][ngramid,:] = p, b self.ngmap[n-1][ng] = ngramid @@ -307,8 +307,7 @@ def save(self, path): fh.write("ngram %d=%d\n" % (n, self.ng_counts[n])) for n in range(1, self.n+1): fh.write("\n\\%d-grams:\n" % n) - ngrams = self.ngmap[n-1].keys() - ngrams.sort() + ngrams = sorted(self.ngmap[n-1].keys()) if '' in self.ngmap[n-1]: ngid = self.ngmap[n-1][''] score, bowt = self.ngrams[n-1][ngid] @@ -356,7 +355,7 @@ def mgrams(self, m): @return: Iterator over N-Grams @rtype: generator(NGram) """ - for ng, ngid in self.ngmap[m].iteritems(): + for ng, ngid in self.ngmap[m].items(): if isinstance(ng, str): ng = (ng,) yield self.NGram(ng, *self.ngrams[m][ngid,:]) @@ -418,7 +417,7 @@ def prob(self, *syms): # Use return self.ngrams[0][self.ngmap[0]['']][0] else: - raise IndexError, "Unknown unigram %s" % syms[0] + raise IndexError("Unknown unigram %s" % syms[0]) else: # Forward N-gram (since syms is reversed) fsyms = tuple(reversed(syms)) @@ -478,7 +477,7 @@ def adapt_rescale(self, unigram, vocab=None): # Rescaled total probabilities newtprob = numpy.zeros(self.ngrams[n-1].shape[0], 'd') # For each N-gram, accumulate and rescale - for ng,idx in self.ngmap[n].iteritems(): + for ng,idx in self.ngmap[n].items(): h = ng[0:-1] if n == 1: # Quirk of unigrams h = h[0] @@ -491,7 +490,7 @@ def adapt_rescale(self, unigram, vocab=None): self.ngrams[n][idx,0] = numpy.log(prob) # Now renormalize everything norm = tprob / newtprob - for ng,idx in self.ngmap[n].iteritems(): + for ng,idx in self.ngmap[n].items(): h = ng[0:-1] if n == 1: # Quirk of unigrams h = h[0] diff --git a/python/cmusphinx/cluster_mixw.py b/python/cmusphinx/cluster_mixw.py index de0c3d85..c62f4c56 100644 --- a/python/cmusphinx/cluster_mixw.py +++ b/python/cmusphinx/cluster_mixw.py @@ -9,27 +9,27 @@ # are met: # # 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. +# notice, this list of conditions and the following disclaimer. # # 2. 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. # -# This work was supported in part by funding from the Defense Advanced -# Research Projects Agency and the National Science Foundation of the +# This work was supported in part by funding from the Defense Advanced +# Research Projects Agency and the National Science Foundation of the # United States of America, and the CMU Sphinx Speech Consortium. # -# THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND -# ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND +# ANY EXPRESSED 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 CARNEGIE MELLON UNIVERSITY # NOR ITS EMPLOYEES 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 +# 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. # # ==================================================================== @@ -93,14 +93,13 @@ def prunetree(tree, nleaves): for branch in subtree: subtree2, centroid2 = branch newleafnodes.append((subtree2, centroid2)) - print "Number of leafnodes", len(newleafnodes) + print("Number of leafnodes", len(newleafnodes)) leafnodes = newleafnodes # Now flatten out the leafnodes to their component distributions for i, leaf in enumerate(leafnodes): subtree, centroid = leaf - senones = list(leaves(leaf)) # Sort senones for each leafnode - senones.sort() + senones = sorted(leaves(leaf)) leafnodes[i] = (senones, centroid) # Sort leafnodes by senone ID leafnodes.sort(lambda x,y: cmp(x[0][0],y[0][0])) @@ -214,7 +213,7 @@ def cluster_merged(mixw, dfunc=multi_js): q = centroids[best] # Merge these two newcentroid = (p + q) * 0.5 - print "Merging", i, best, dist[best], len(centroids) + print("Merging", i, best, dist[best], len(centroids)) newtree = ((trees[i], p), (trees[best], q)) centroids[i] = newcentroid trees[i] = newtree @@ -287,12 +286,12 @@ def write_senmgau(outfile, tree, mixw, nclust): big = clusters[0] del clusters[0:1] clusters.extend((big[0][0], big[0][1])) - print "cluster sizes:", [len(leaves(x)) for x in clusters] + print("cluster sizes:", [len(leaves(x)) for x in clusters]) mixwmap = numpy.zeros(len(mixw), 'int32') for i, c in enumerate(clusters): for mixwid in leaves(c): mixwmap[mixwid] = i - print "writing %d senone mappings" % len(mixwmap) + print("writing %d senone mappings" % len(mixwmap)) s3senmgau.open(outfile, "wb").write_mapping(mixwmap) if __name__ == '__main__': diff --git a/python/cmusphinx/cmllr.py b/python/cmusphinx/cmllr.py index abe1da68..bb3a2cdc 100755 --- a/python/cmusphinx/cmllr.py +++ b/python/cmusphinx/cmllr.py @@ -51,7 +51,7 @@ def estimate_cmllr(stats, inmean, invar, mdef): cofact = np.zeros(ndim+1) # Beta B = 0 - print 'Get statistics & sum it' + print('Get statistics & sum it') # CD only : just sum over all CD densities for j in range(mdef.n_ci_sen, inmean.n_mgau): # print 'state = %i' % j @@ -102,7 +102,7 @@ def estimate_cmllr(stats, inmean, invar, mdef): cofact = get_cofact(A,i) # Get alpha alpha = get_alpha(Ginv,K[i],B,cofact) - print "alpha : %f" % alpha + print("alpha : %f" % alpha) W = np.zeros(ndim+1) tvec = alpha * cofact + K[i] W = np.dot(Ginv,tvec) @@ -112,7 +112,7 @@ def estimate_cmllr(stats, inmean, invar, mdef): A[i,:] = W[0:ndim] bias[i] = W[ndim] else: - print 'NOT updating row %i, iter %i,( %f > %f )' % ( i , niter, like_old, like_new ) + print('NOT updating row %i, iter %i,( %f > %f )' % ( i , niter, like_old, like_new )) #to preserve compatibility with write_mllr Wi = np.c_[bias,A] Ws.append(Wi) @@ -142,7 +142,7 @@ def get_alpha(Ginv,K,B,cofact): d = b * b - 4 * a * c if ( d < 0 ) : #solutions must be real - print 'Warning : determinant < 0' + print('Warning : determinant < 0') d = 0 d = math.sqrt(d) alpha1 = (- b + d ) / ( 2 * a ) diff --git a/python/cmusphinx/corpus.py b/python/cmusphinx/corpus.py index f026d386..0d6d7680 100644 --- a/python/cmusphinx/corpus.py +++ b/python/cmusphinx/corpus.py @@ -125,12 +125,12 @@ def __init__(self, corpus, part=1, npart=1): if npart > 1: pass else: - for k, v in corpus.resources.iteritems(): + for k, v in corpus.resources.items(): self.iters[k] = iter(v) def next(self): utt = {} - for k,v in self.iters.iteritems(): + for k,v in self.iters.items(): utt[k] = v.next() return utt diff --git a/python/cmusphinx/dict_spd.py b/python/cmusphinx/dict_spd.py index c501d139..11d81ea6 100755 --- a/python/cmusphinx/dict_spd.py +++ b/python/cmusphinx/dict_spd.py @@ -19,7 +19,7 @@ if __name__ == "__main__": if len(sys.argv) < 3: - print>>sys.stderr, "Usage: %s INDICT FALIGNOUT [OUTDICT]" % sys.argv[0] + print("Usage: %s INDICT FALIGNOUT [OUTDICT]" % sys.argv[0], file=sys.stderr) sys.exit(1) indict = s3dict.open(sys.argv[1]) counts = defaultdict(int) @@ -37,7 +37,7 @@ for w in words: alts = sum(1 for x in indict.alts(w)) if alts == 1: - print>>outfh, "%s\t\t%s" % (w, " ".join(indict[w])) + print("%s\t\t%s" % (w, " ".join(indict[w])), file=outfh) else: bestalt = None bestcount = 0 @@ -50,7 +50,7 @@ bestcount = counts[wstr] bestalt = wstr if bestalt == None: - print>>outfh, "%s\t\t%s" % (w, " ".join(indict[w])) + print("%s\t\t%s" % (w, " ".join(indict[w])), file=outfh) else: - print>>outfh, "%s\t\t%s" % (w, " ".join(indict[bestalt])) + print("%s\t\t%s" % (w, " ".join(indict[bestalt])), file=outfh) diff --git a/python/cmusphinx/fstutils.py b/python/cmusphinx/fstutils.py index 8bf02600..308a0850 100644 --- a/python/cmusphinx/fstutils.py +++ b/python/cmusphinx/fstutils.py @@ -158,7 +158,7 @@ def add_ngram_arcs(fst, symtab, lm, n, sidtab): while tuple(ng.words[spos:]) not in sidtab: spos += 1 if spos == n: - raise RuntimeError, "Unable to find suffix N-gram for", ng.wids + raise RuntimeError("Unable to find suffix N-gram for").with_traceback(ng.wids) dest = sidtab[tuple(ng.words[spos:])] fst.AddArc(src, openfst.StdArc(wsym, wsym, -ng.log_prob, dest)) #print "Adding %d-gram arc %d => %d %s/%.4f" % (n, src, dest, ng.words[n-1], -ng.log_prob) @@ -270,7 +270,7 @@ def normalize(self): Normalize probabilities. """ for c in self.classes: - t = sum(self.classes[c].itervalues()) + t = sum(self.classes[c].values()) if t != 0: for w in self.classes[c]: self.classes[c][w] /= t @@ -300,7 +300,7 @@ def build_classfst(probdef, isyms=None): fst.AddArc(st, label, label, 0, st) for c in probdef.classes: clabel = symtab.AddSymbol(c) - for word, prob in probdef.classes[c].iteritems(): + for word, prob in probdef.classes[c].items(): wlabel = symtab.AddSymbol(word) fst.AddArc(st, wlabel, clabel, -math.log(prob), st) fst.SetOutputSymbols(symtab) diff --git a/python/cmusphinx/htkmfc.py b/python/cmusphinx/htkmfc.py index 81dcb33f..4f78071e 100644 --- a/python/cmusphinx/htkmfc.py +++ b/python/cmusphinx/htkmfc.py @@ -50,7 +50,7 @@ def open(f, mode=None, veclen=13): elif mode in ('w', 'wb'): return HTKFeat_write(f, veclen) else: - raise Exception, "mode must be 'r', 'rb', 'w', or 'wb'" + raise Exception("mode must be 'r', 'rb', 'w', or 'wb'") class HTKFeat_read(object): "Read HTK format feature files" diff --git a/python/cmusphinx/lat2dot.py b/python/cmusphinx/lat2dot.py index e793b6bb..85d826b2 100755 --- a/python/cmusphinx/lat2dot.py +++ b/python/cmusphinx/lat2dot.py @@ -19,12 +19,12 @@ def lattice_s3(latfile): items = line.strip().split(" ") if mode == "node": if items[1] != "": - print items[0] + " [label = \"" + items[1] + " " + items[2] + " " + items[3] + " " + items[4] + "\"];" + print(items[0] + " [label = \"" + items[1] + " " + items[2] + " " + items[3] + " " + items[4] + "\"];") else: - print "node " + items[0] + ";" + print("node " + items[0] + ";") if mode == "edge": - print items[0] + " -> " + items[1] + " [label = \"" + items[2] + "\"];" - print "}" + print(items[0] + " -> " + items[1] + " [label = \"" + items[2] + "\"];") + print("}") def create_map(items): dct = {} @@ -38,24 +38,24 @@ def lattice_htk_wordnode(latfile): items = line.strip().split() if items[0].startswith("I="): dct = create_map(items) - if dct.has_key("W"): - print dct["J"] + " [label = \"" + dct[W] + "\"];" + if "W" in dct: + print(dct["J"] + " [label = \"" + dct[W] + "\"];") if items[0].startswith("J="): dct = create_map(items) - if dct.has_key("W"): - print dct["S"] + " -> " + dct["E"] + " [label = \"" + dct["W"] + "," + dct["a"] + "," + dct["l"] + "\"];" + if "W" in dct: + print(dct["S"] + " -> " + dct["E"] + " [label = \"" + dct["W"] + "," + dct["a"] + "," + dct["l"] + "\"];") else: - print dct["S"] + " -> " + dct["E"] + " [label = \"" + dct["a"] + "," + dct["l"] + "\"];" - print "}" + print(dct["S"] + " -> " + dct["E"] + " [label = \"" + dct["a"] + "," + dct["l"] + "\"];") + print("}") if __name__ == '__main__': latfilename = sys.argv[1] latfile = open(latfilename, "r") - print """ + print(""" digraph lattice { rankdir=LR; - """ + """) if latfilename.endswith("slf"): lattice_htk_wordnode(latfile) diff --git a/python/cmusphinx/lat2fsg.py b/python/cmusphinx/lat2fsg.py index 2cdcfa97..cd1e79af 100644 --- a/python/cmusphinx/lat2fsg.py +++ b/python/cmusphinx/lat2fsg.py @@ -259,5 +259,5 @@ def lat2flat(latfile, fsgfile, lmfst): for spam in file(ctlfile): latfile = os.path.join(latdir, spam.strip() + ".slf") fsgfile = os.path.join(latdir, spam.strip() + opts.outext) - print spam, + print(spam, end=' ') ofst = lat2fsg_posterior(latfile, fsgfile, opts.prune, errfst) diff --git a/python/cmusphinx/lat_rescore.py b/python/cmusphinx/lat_rescore.py index f851d9b6..cdd8cd46 100644 --- a/python/cmusphinx/lat_rescore.py +++ b/python/cmusphinx/lat_rescore.py @@ -34,4 +34,4 @@ def lat_rescore(latfile, lmfst): for spam in file(ctlfile): latfile = os.path.join(latdir, spam.strip() + ".lat.gz") words, score = lat_rescore(latfile, lm) - print " ".join(words), "(%s %f)" % (spam.strip(), score) + print(" ".join(words), "(%s %f)" % (spam.strip(), score)) diff --git a/python/cmusphinx/lat_rescore_fst.py b/python/cmusphinx/lat_rescore_fst.py index 3226bb8a..4580e0e5 100644 --- a/python/cmusphinx/lat_rescore_fst.py +++ b/python/cmusphinx/lat_rescore_fst.py @@ -77,4 +77,4 @@ def lat_rescore(dag, lmfst, lw=9.5): except IOError: dag = lattice.Dag(htk_file=os.path.join(latdir, spam.strip() + ".slf")) words, score = lat_rescore(dag, lmfst, opts.lw) - print " ".join(words), "(%s %f)" % (spam.strip(), score) + print(" ".join(words), "(%s %f)" % (spam.strip(), score)) diff --git a/python/cmusphinx/lattice.py b/python/cmusphinx/lattice.py index 7314abfa..825904db 100644 --- a/python/cmusphinx/lattice.py +++ b/python/cmusphinx/lattice.py @@ -258,7 +258,7 @@ def dag2htk(self, htkfile, lm=None): # Ensure some header fields are there if 'VERSION' not in self.header: self.header['VERSION'] = '1.0' - for k,v in self.header.iteritems(): + for k,v in self.header.items(): # Skip Sphinx stuff if k[0] == '-': continue @@ -309,7 +309,7 @@ def dag2fst(self, fstfile, symfile=None, altpron=False): fh.write("%d 0" % idmap[self.end]) fh.close() if symfile: - for k, v in symmap.iteritems(): + for k, v in symmap.items(): sfh.write("%s %d\n" % (k, v)) sfh.close() @@ -394,7 +394,7 @@ def dag2sphinx(self, outfile, logbase=1.0003): fh = open(outfile, "w") fh.write("# getcwd: %s\n" % self.getcwd) fh.write("# -logbase %e\n" % logbase) - for arg, val in self.header.iteritems(): + for arg, val in self.header.items(): if arg != '-logbase': fh.write("# %s %s\n" % (arg,val)) fh.write("#\n") diff --git a/python/cmusphinx/lattice_conv.py b/python/cmusphinx/lattice_conv.py index 075d682b..9f8a2aa0 100755 --- a/python/cmusphinx/lattice_conv.py +++ b/python/cmusphinx/lattice_conv.py @@ -218,52 +218,51 @@ def write_lat(lm, filler, filelist, filecount, fileoffset, denlatdir, numlatdir, alignfile = "%s/%s.wdseg" % (numlatdir, fileid) latfile = "%s/%s.lat.gz" % (denlatdir, fileid) - print "process sent: %s" % fileid + print("process sent: %s" % fileid) - print "\t load numerator lattice %s ... " % alignfile + print("\t load numerator lattice %s ... " % alignfile) try: numlat = load_numlat(alignfile) except IOError: - print "\t can't open numerator lattice %s to read" % alignfile + print("\t can't open numerator lattice %s to read" % alignfile) continue - print "\t load denominator lattice %s ..." % latfile + print("\t load denominator lattice %s ..." % latfile) try: den_wordseg = load_denlat(latfile) except IOError: - print "\t can't open denominator lattice %s to read" % latfile + print("\t can't open denominator lattice %s to read" % latfile) continue - print "\t convert numerator lattice ..." - numkeys = numlat.keys() - numkeys.sort() + print("\t convert numerator lattice ...") + numkeys = sorted(numlat.keys()) conv_numlat = conv_lat_format(numkeys, numlat, filler, lm) - print "\t convert denominator lattice ..." - denkeys = den_wordseg.keys() + print("\t convert denominator lattice ...") + denkeys = list(den_wordseg.keys()) denkeys.sort() denlat = conv_lat_format(denkeys, den_wordseg, filler, lm) - print"\t add numerator lattice into denominator lattice ..." + print("\t add numerator lattice into denominator lattice ...") conv_denlat = add_numlat_into_denlat(conv_numlat, denlat) numlatfile = "%s/%s.numlat" % (outdir, fileid) denlatfile = "%s/%s.denlat" % (outdir, fileid) - print "\t write numerator lattice to %s ..." % numlatfile + print("\t write numerator lattice to %s ..." % numlatfile) try: output_lattice(conv_numlat, len(conv_numlat), numlatfile) except IOErro: - print "\t can't write numerator lattice to %s" % numlatfile + print("\t can't write numerator lattice to %s" % numlatfile) continue - print "\t write denominator lattice to %s ...\n" % denlatfile + print("\t write denominator lattice to %s ...\n" % denlatfile) try: output_lattice(conv_denlat, len(conv_numlat), denlatfile) except IOError: - print "\t can't write denominator lattice to %s" % denlatfile + print("\t can't write denominator lattice to %s" % denlatfile) - print "ALL DONE\n" + print("ALL DONE\n") @@ -276,7 +275,7 @@ def write_lat(lm, filler, filelist, filecount, fileoffset, denlatdir, numlatdir, command = '' for argv in sys.argv: command += argv + ' ' - print "%s\n" % command + print("%s\n" % command) lmfile, fillerfile, filelist, filecount, fileoffset, denlatdir, numlatdir, outdir = sys.argv[1:] diff --git a/python/cmusphinx/lattice_error.py b/python/cmusphinx/lattice_error.py index 9a2c71d8..b8180fba 100644 --- a/python/cmusphinx/lattice_error.py +++ b/python/cmusphinx/lattice_error.py @@ -34,14 +34,14 @@ l.posterior_prune(-prune) err, bt = l.minimum_error(r) maxlen = [max([len(y) for y in x]) for x in bt] - print " ".join(["%*s" % (m, x[0]) for m, x in izip(maxlen, bt)]) - print " ".join(["%*s" % (m, x[1]) for m, x in izip(maxlen, bt)]) + print(" ".join(["%*s" % (m, x[0]) for m, x in izip(maxlen, bt)])) + print(" ".join(["%*s" % (m, x[1]) for m, x in izip(maxlen, bt)])) if nw: - print "Error: %.2f%%" % (float(err) / nw * 100) + print("Error: %.2f%%" % (float(err) / nw * 100)) else: - print "Error: %.2f%%" % 0 - print + print("Error: %.2f%%" % 0) + print() wordcount += nw errcount += err -print "TOTAL Error: %.2f%%" % (float(errcount) / wordcount * 100) +print("TOTAL Error: %.2f%%" % (float(errcount) / wordcount * 100)) diff --git a/python/cmusphinx/lattice_error_fst.py b/python/cmusphinx/lattice_error_fst.py index 2a90ac42..1f45576f 100644 --- a/python/cmusphinx/lattice_error_fst.py +++ b/python/cmusphinx/lattice_error_fst.py @@ -165,14 +165,14 @@ def __init__(self, isyms, osyms): nwords = len(r) - 2 refid = '(%s)' % refid c = '(%s)' % c - print " ".join(["%*s" % (m, x[0]) for m, x in izip(maxlen, bt)]), refid - print " ".join(["%*s" % (m, x[1]) for m, x in izip(maxlen, bt)]), c + print(" ".join(["%*s" % (m, x[0]) for m, x in izip(maxlen, bt)]), refid) + print(" ".join(["%*s" % (m, x[1]) for m, x in izip(maxlen, bt)]), c) if nwords: - print "Error: %.2f%%" % (float(err) / nwords * 100) + print("Error: %.2f%%" % (float(err) / nwords * 100)) else: - print "Error: %.2f%%" % (float(err) * 100) - print + print("Error: %.2f%%" % (float(err) * 100)) + print() wordcount += nwords errcount += err - print "TOTAL Error: %.2f%%" % (float(errcount) / wordcount * 100) + print("TOTAL Error: %.2f%%" % (float(errcount) / wordcount * 100)) diff --git a/python/cmusphinx/lattice_prune.py b/python/cmusphinx/lattice_prune.py index 307dd758..b5a943f6 100755 --- a/python/cmusphinx/lattice_prune.py +++ b/python/cmusphinx/lattice_prune.py @@ -16,7 +16,7 @@ command = '' for argv in sys.argv: command += argv + ' ' - print "%s\n" % command + print("%s\n" % command) abeam, nbeam, lw, lmfile, denlatdir, pruned_denlatdir, ctlfile, transfile, filecount, fileoffset = sys.argv[1:] @@ -53,10 +53,10 @@ if r[-1] != '': r.append('') r = filter(lambda x: not lattice.is_filler(x), r) - print "process sent: %s" % c + print("process sent: %s" % c) # load lattice - print "\t load lattice ..." + print("\t load lattice ...") dag = lattice.Dag(os.path.join(denlatdir, c + ".lat.gz")) dag.bypass_fillers() dag.remove_unreachable() @@ -66,13 +66,13 @@ dag.dt_posterior() # edge pruning - print "\t edge pruning ..." + print("\t edge pruning ...") dag.forward_edge_prune(abeam) dag.backward_edge_prune(abeam) dag.remove_unreachable() # node pruning - print "\t node pruning ..." + print("\t node pruning ...") dag.post_node_prune(nbeam) dag.remove_unreachable() @@ -80,7 +80,7 @@ err, bt = dag.minimum_error(r) # save pruned lattice - print "\t saving pruned lattice ...\n" + print("\t saving pruned lattice ...\n") dag.dag2sphinx(os.path.join(pruned_denlatdir, c + ".lat.gz")) sentcount += 1 @@ -89,8 +89,8 @@ wer += float(err) / len(r) density += float(dag.n_edges())/len(r) - print "Average Lattice Word Error Rate: %.2f%%" % (wer / sentcount * 100) - print "Average Lattice Density: %.2f" % (float(density) / sentcount) - print "Average Number of Node: %.2f" % (float(nodecount) / sentcount) - print "Average Number of Arc: %.2f" % (float(edgecount) / sentcount) - print "ALL DONE" + print("Average Lattice Word Error Rate: %.2f%%" % (wer / sentcount * 100)) + print("Average Lattice Density: %.2f" % (float(density) / sentcount)) + print("Average Number of Node: %.2f" % (float(nodecount) / sentcount)) + print("Average Number of Arc: %.2f" % (float(edgecount) / sentcount)) + print("ALL DONE") diff --git a/python/cmusphinx/lda.py b/python/cmusphinx/lda.py index 518918e8..58b062e7 100755 --- a/python/cmusphinx/lda.py +++ b/python/cmusphinx/lda.py @@ -20,7 +20,7 @@ try: import numpy except ImportError: - print "FATAL: Failed to import numpy modules. Check that numpy and scipy are installed" + print("FATAL: Failed to import numpy modules. Check that numpy and scipy are installed") sys.exit(1) import s3lda @@ -36,7 +36,7 @@ def makelda(gauden_counts): @type gauden_counts: cmusphinx.s3gaucnt.S3FullGauCntFile """ if not gauden_counts.pass2var: - raise Exception, "Please re-run bw with '-2passvar yes'" + raise Exception("Please re-run bw with '-2passvar yes'") mean = numpy.concatenate([x[0] for x in gauden_counts.mean]) var = numpy.concatenate([x[0] for x in gauden_counts.var]) dnom = gauden_counts.dnom.ravel() @@ -49,8 +49,8 @@ def makelda(gauden_counts): diff = m / d - globalmean sb += d * numpy.outer(diff, diff) - print "Sw:\n", sw - print "Sb:\n", sb + print("Sw:\n", sw) + print("Sb:\n", sb) BinvA = numpy.dot(numpy.linalg.inv(sw), sb) u, v = numpy.linalg.eig(BinvA) @@ -61,8 +61,8 @@ def makelda(gauden_counts): # them to be in the rows. v = v.T.take(top, 0) - print "u:\n", u - print "v:\n", v + print("u:\n", u) + print("v:\n", v) return v diff --git a/python/cmusphinx/mfcc.py b/python/cmusphinx/mfcc.py index d160e945..7d353762 100644 --- a/python/cmusphinx/mfcc.py +++ b/python/cmusphinx/mfcc.py @@ -47,8 +47,7 @@ def __init__(self, nfilt=40, ncep=13, self.filters = numpy.zeros((nfft/2+1,nfilt), 'd') dfreq = float(samprate) / nfft if upperf > samprate/2: - raise(Exception, - "Upper frequency %f exceeds Nyquist %f" % (upperf, samprate/2)) + raise Exception melmax = mel(upperf) melmin = mel(lowerf) dmelbw = (melmax - melmin) / (nfilt + 1) diff --git a/python/cmusphinx/mllr.py b/python/cmusphinx/mllr.py index a8a849e9..cafcc050 100755 --- a/python/cmusphinx/mllr.py +++ b/python/cmusphinx/mllr.py @@ -166,7 +166,7 @@ def estimate_mllr_variance(stats, inmean, invar, Ws): @rtype: list(numpy.ndarray) """ if stats.pass2var: - raise RuntimeException, "Statistics using -2passvar yes are not allowed" + raise RuntimeException("Statistics using -2passvar yes are not allowed") Hs = [] for i, W in enumerate(Ws): ndim = inmean.veclen[i] diff --git a/python/cmusphinx/mllt.py b/python/cmusphinx/mllt.py index db4ea5de..248208a8 100755 --- a/python/cmusphinx/mllt.py +++ b/python/cmusphinx/mllt.py @@ -24,7 +24,7 @@ from numpy.linalg import det, inv from scipy.optimize import fmin_l_bfgs_b except ImportError: - print "FATAL: Failed to import numpy modules. Check that numpy and scipy are installed" + print("FATAL: Failed to import numpy modules. Check that numpy and scipy are installed") sys.exit(1) import s3gaucnt @@ -47,7 +47,7 @@ def __init__(self, gauden_counts, ldadim=None): @type ldadim: int """ if not gauden_counts.pass2var: - raise Exception, "Please re-run bw with '-2passvar yes'" + raise Exception("Please re-run bw with '-2passvar yes'") if ldadim == None: ldadim = gauden_counts.veclen[0] self.cov = concatenate([x[0] for x in gauden_counts.var]) @@ -81,10 +81,10 @@ def objective(self, A, r, c): cl = diag(dot(dot(A, C), A.T)) ll = ll - (float(nj) / 2) * sum(log(cl)) lg = lg - float(nj) * dot(dot(inv(diag(cl)), A), C) - print "likelihood: %f" % ll + print("likelihood: %f" % ll) # Flatten out the gradient lg = lg.ravel() - print "gradient L2: %f" % sqrt(sum(lg*lg)) + print("gradient L2: %f" % sqrt(sum(lg*lg))) # Note: we negate these to maximize likelihood return -ll, -lg @@ -110,7 +110,7 @@ def train(self, A=None): # Flatten out the matrix so scipy.optimize can handle it AA, f, d = fmin_l_bfgs_b(self.objective, A.ravel(), args=A.shape, factr=10) if d['warnflag']: - print "WARNING! MLLT optimization failed to converge" + print("WARNING! MLLT optimization failed to converge") # Unflatten the return matrix return AA.reshape(A.shape) diff --git a/python/cmusphinx/prune_mixw.py b/python/cmusphinx/prune_mixw.py index b7dc81c5..19d91672 100644 --- a/python/cmusphinx/prune_mixw.py +++ b/python/cmusphinx/prune_mixw.py @@ -32,8 +32,8 @@ def prune_mixw_entropy(mixw, avgn): if top < mintop: mintop = top if top > maxtop: maxtop = top f.put(f.argsort()[:-top], 0) - print "Average #mixw: %.2f" % (float(avgtop) / count) - print "Min #mixw: %d Max #mixw: %d" % (mintop, maxtop) + print("Average #mixw: %.2f" % (float(avgtop) / count)) + print("Min #mixw: %d Max #mixw: %d" % (mintop, maxtop)) return histo def prune_mixw_entropy_min(mixw, avgn, minn): @@ -62,8 +62,8 @@ def prune_mixw_entropy_min(mixw, avgn, minn): if top < mintop: mintop = top if top > maxtop: maxtop = top f.put(f.argsort()[:-top], 0) - print "Average #mixw: %.2f" % (float(avgtop) / count) - print "Min #mixw: %d Max #mixw: %d" % (mintop, maxtop) + print("Average #mixw: %.2f" % (float(avgtop) / count)) + print("Min #mixw: %d Max #mixw: %d" % (mintop, maxtop)) return histo def prune_mixw_pplx_hist(mixw): @@ -87,8 +87,8 @@ def prune_mixw_pplx_hist(mixw): if top > maxtop: maxtop = top f.put(f.argsort()[:-top], 0) count = mixw.shape[0] * mixw.shape[1] - print "Average #mixw: %.2f" % (float(avgtop) / count) - print "Min #mixw: %d Max #mixw: %d" % (mintop, maxtop) + print("Average #mixw: %.2f" % (float(avgtop) / count)) + print("Min #mixw: %d Max #mixw: %d" % (mintop, maxtop)) return histo def prune_mixw_topn(mixw, n): @@ -111,8 +111,8 @@ def prune_mixw_thresh(mixw, thresh): if top > maxtop: maxtop = top f.put(toprune, 0) count = mixw.shape[0] * mixw.shape[1] - print "Average #mixw: %.2f" % (float(avgtop) / count) - print "Min #mixw: %d Max #mixw: %d" % (mintop, maxtop) + print("Average #mixw: %.2f" % (float(avgtop) / count)) + print("Min #mixw: %d Max #mixw: %d" % (mintop, maxtop)) return histo def norm_floor_mixw(mixw, floor=1e-7): diff --git a/python/cmusphinx/quantize_mixw.py b/python/cmusphinx/quantize_mixw.py index 83476f08..bf22f228 100644 --- a/python/cmusphinx/quantize_mixw.py +++ b/python/cmusphinx/quantize_mixw.py @@ -57,15 +57,15 @@ def quantize_mixw_kmeans(mixw, k, zero=0.0): mmw = lmw.min() xmw = lmw.max() rmw = xmw - mmw - print "min log mixw: %f range: %f" % (mmw, rmw) + print("min log mixw: %f range: %f" % (mmw, rmw)) cb = numpy.random.random(k) * rmw + mmw pdist = 1e+50 for i in range(0,10): tdist = mixw_kmeans_iter(lmw, cb) conv = (pdist - tdist) / pdist - print "Total distortion: %e convergence ratio: %e" % (tdist, conv) + print("Total distortion: %e convergence ratio: %e" % (tdist, conv)) if conv < 0.01: - print "Training has converged, stopping" + print("Training has converged, stopping") break pdist = tdist return cb diff --git a/python/cmusphinx/s2mfc.py b/python/cmusphinx/s2mfc.py index 5d5a36b3..752cbeb0 100644 --- a/python/cmusphinx/s2mfc.py +++ b/python/cmusphinx/s2mfc.py @@ -28,7 +28,7 @@ def open(f, mode=None, veclen=13): elif mode in ('w', 'wb'): return S2Feat_write(f,veclen) else: - raise Exception, "mode must be 'r', 'rb', 'w', or 'wb'" + raise Exception("mode must be 'r', 'rb', 'w', or 'wb'") class S2Feat_read(object): "Read Sphinx-II format feature files" diff --git a/python/cmusphinx/s3dict.py b/python/cmusphinx/s3dict.py index 07806976..ec5f9939 100644 --- a/python/cmusphinx/s3dict.py +++ b/python/cmusphinx/s3dict.py @@ -100,8 +100,7 @@ def write(self, outfile): fh = outfile else: fh = file(outfile, 'w') - wlist = self.keys() - wlist.sort() + wlist = sorted(self.keys()) for k in wlist: word = word_to_str(k) fh.write("%s\t%s\n" % (word.encode('utf8'), " ".join(self[k]))) @@ -126,7 +125,7 @@ def get_alt_phones(self, word, alt): if not dict.__contains__(self, (word, 1)): raise KeyError elif not dict.__contains__(self, (word, alt)): - raise IndexError, "Alternate pronunciation index %d does not exist" % alt + raise IndexError("Alternate pronunciation index %d does not exist" % alt) return dict.__getitem__(self, (word, alt)) def set_phones(self, word, phones): @@ -147,7 +146,7 @@ def set_alt_phones(self, word, alt, phones): """ if alt > self.maxalt[word] + 1: - raise IndexError, "Alternate pronunciation index %d too high" % alt + raise IndexError("Alternate pronunciation index %d too high" % alt) dict.__setitem__(self, (word, alt), phones) self.maxalt[word] = max(alt, self.maxalt[word]) for ph in phones: @@ -175,7 +174,7 @@ def del_alt_phones(self, word, alt): """ if not dict.__contains__(self, (word, alt)): - raise IndexError, "Alternate pronunciation index %d does not exist" % alt + raise IndexError("Alternate pronunciation index %d does not exist" % alt) for ph in self[word, alt]: self.phoneset[ph] -= 1 if self.phoneset[ph] == 0: # FIXME: make a class diff --git a/python/cmusphinx/s3file.py b/python/cmusphinx/s3file.py index 6d43c8d3..ac528699 100644 --- a/python/cmusphinx/s3file.py +++ b/python/cmusphinx/s3file.py @@ -145,7 +145,7 @@ def open(self, filename): def writeheader(self): self.fh.write("s3\n") - for k,v in self.fileattr.iteritems(): + for k,v in self.fileattr.items(): self.fh.write("%s %s\n" % (k,v)) # Make sure the binary data lives on a 4-byte boundary lsb = (self.fh.tell() + len("endhdr\n")) & 3 diff --git a/python/cmusphinx/s3gau.py b/python/cmusphinx/s3gau.py index af0f5566..36118646 100644 --- a/python/cmusphinx/s3gau.py +++ b/python/cmusphinx/s3gau.py @@ -22,7 +22,7 @@ def open(filename, mode="rb", attr={"version":1.0}): elif mode in ("w", "wb"): return S3GauFile_write(filename, mode, attr) else: - raise Exception, "mode must be 'r', 'rb', 'w', or 'wb'" + raise Exception("mode must be 'r', 'rb', 'w', or 'wb'") def open_full(filename, mode="rb", attr={"version":1.0}): if mode in ("r", "rb"): @@ -30,7 +30,7 @@ def open_full(filename, mode="rb", attr={"version":1.0}): elif mode in ("w", "wb"): return S3FullGauFile_write(filename, mode, attr) else: - raise Exception, "mode must be 'r', 'rb', 'w', or 'wb'" + raise Exception("mode must be 'r', 'rb', 'w', or 'wb'") class S3GauFile(S3File): "Read Sphinx-III format Gaussian parameter files" @@ -147,7 +147,7 @@ def writeall(self, stuff): # This will break for multi-stream files n_mgau, n_feat, density, veclen, veclen2 = shape(stuff) if n_feat != 1: - raise Exception, "Multi-stream files not supported" + raise Exception("Multi-stream files not supported") # Write the header self.fh.seek(self.data_start, 0) self.fh.write(pack("=IIIII", diff --git a/python/cmusphinx/s3gaucnt.py b/python/cmusphinx/s3gaucnt.py index 21a2838e..5b1e1a08 100644 --- a/python/cmusphinx/s3gaucnt.py +++ b/python/cmusphinx/s3gaucnt.py @@ -22,7 +22,7 @@ def open(filename, mode="rb", attr={"version":1.0}): if mode in ("r", "rb"): return S3GauCntFile(filename, mode) else: - raise Exception, "mode must be 'r' or 'rb'" + raise Exception("mode must be 'r' or 'rb'") def accumdirs(accumdirs): "Read and accumulate counts from several directories" @@ -66,7 +66,7 @@ def open_full(filename, mode="rb", attr={"version":1.0}): if mode in ("r", "rb"): return S3FullGauCntFile(filename, mode) else: - raise Exception, "mode must be 'r', 'rb'" + raise Exception("mode must be 'r', 'rb'") class S3GauCntFile(S3File): "Read Sphinx-III format Gaussian count files" diff --git a/python/cmusphinx/s3lda.py b/python/cmusphinx/s3lda.py index 35e16bc1..5b5ee6e8 100644 --- a/python/cmusphinx/s3lda.py +++ b/python/cmusphinx/s3lda.py @@ -44,5 +44,5 @@ def open(filename, mode="rb"): elif mode in ("w", "wb"): return S3LDAFile_write(filename, mode) else: - raise Exception, "mode must be 'r', 'rb', 'w', or 'wb'" + raise Exception("mode must be 'r', 'rb', 'w', or 'wb'") diff --git a/python/cmusphinx/s3mdef.py b/python/cmusphinx/s3mdef.py index 4b8f15ef..b3896a76 100644 --- a/python/cmusphinx/s3mdef.py +++ b/python/cmusphinx/s3mdef.py @@ -104,7 +104,7 @@ def read(self, filename): sseqid = 0 self.pidmap = [] - for sseq, phones in ssidmap.iteritems(): + for sseq, phones in ssidmap.items(): sids = map(int, sseq.split(',')) self.sseq[sseqid,0:len(sids)] = sids self.pidmap.append(phones) @@ -122,7 +122,7 @@ def phone_id(self, ci, lc='-', rc='-', wpos=None): if wpos == None: if lc != '-': # Try all word positions to find one that matches - for new_wpos, pmap in self.phonemap.iteritems(): + for new_wpos, pmap in self.phonemap.items(): if ci in pmap and lc in pmap[ci] and rc in pmap[ci][lc]: wpos = new_wpos break @@ -139,7 +139,7 @@ def phone_id_nearest(self, ci, lc='-', rc='-', wpos=None): return self.phone_id(ci, lc, rc, wpos) else: # First try to back off to a different word position - for new_wpos, pmap in self.phonemap.iteritems(): + for new_wpos, pmap in self.phonemap.items(): if ci in pmap and lc in pmap[ci] and rc in pmap[ci][lc]: return self.phonemap[new_wpos][ci][lc][rc] # If not, try using silence in the left/right context diff --git a/python/cmusphinx/s3mixw.py b/python/cmusphinx/s3mixw.py index 0ed9ee62..b84e9a59 100644 --- a/python/cmusphinx/s3mixw.py +++ b/python/cmusphinx/s3mixw.py @@ -21,7 +21,7 @@ def open(filename, mode="rb"): elif mode in ("w", "wb"): return S3MixwFile_write(filename, mode) else: - raise Exception, "mode must be 'r', 'rb', 'w', or 'wb'" + raise Exception("mode must be 'r', 'rb', 'w', or 'wb'") class S3MixwFile(S3File): "Read Sphinx-III format mixture weight files" diff --git a/python/cmusphinx/s3senmgau.py b/python/cmusphinx/s3senmgau.py index 82a4f2c1..2d72257f 100644 --- a/python/cmusphinx/s3senmgau.py +++ b/python/cmusphinx/s3senmgau.py @@ -53,7 +53,7 @@ def open(filename, mode="rb"): elif mode in ("w", "wb"): return S3SenmgauFile_write(filename, mode) else: - raise Exception, "mode must be 'r', 'rb', 'w', or 'wb'" + raise Exception("mode must be 'r', 'rb', 'w', or 'wb'") class S3SenmgauFile(S3File): "Read Sphinx-III format senone mapping files" diff --git a/python/cmusphinx/s3tmat.py b/python/cmusphinx/s3tmat.py index feea0591..a2b0ee1e 100644 --- a/python/cmusphinx/s3tmat.py +++ b/python/cmusphinx/s3tmat.py @@ -22,7 +22,7 @@ def open(filename, mode="rb"): elif mode in ("w", "wb"): return S3TmatFile_write(filename, mode) else: - raise Exception, "mode must be 'r', 'rb', 'w', or 'wb'" + raise Exception("mode must be 'r', 'rb', 'w', or 'wb'") class S3TmatFile(S3File): "Read Sphinx-III format transition matrix files" diff --git a/python/cmusphinx/sendump.py b/python/cmusphinx/sendump.py index 64cb921d..aab6db25 100644 --- a/python/cmusphinx/sendump.py +++ b/python/cmusphinx/sendump.py @@ -61,7 +61,7 @@ def load(self,filename): # Number of codewords and pdfs model_count = self.unpack_endian(sendump.read(4)) mixture_count = self.unpack_endian(sendump.read(4)) - print "rows (model_count): %d, columns (mixture_count): %d, features (feature_count): %d" % (model_count, mixture_count, feature_count) + print("rows (model_count): %d, columns (mixture_count): %d, features (feature_count): %d" % (model_count, mixture_count, feature_count)) # Now read the stuff self.opdf = numpy.empty((mixture_count, feature_count, model_count)) @@ -73,7 +73,7 @@ def load(self,filename): self.opdf[:,i,j] = numpy.power(1.0001, -mixw) def usage(): - print "Usage: %s IN_SENDUMP OUT_MIXW" % sys.argv[0] + print("Usage: %s IN_SENDUMP OUT_MIXW" % sys.argv[0]) if __name__ == '__main__': if len(sys.argv) < 3: diff --git a/python/cmusphinx/test_arpalm.py b/python/cmusphinx/test_arpalm.py index b46bb258..26611093 100644 --- a/python/cmusphinx/test_arpalm.py +++ b/python/cmusphinx/test_arpalm.py @@ -15,15 +15,15 @@ def setUp(self): def test_load(self): lm = arpalm.ArpaLM(os.path.join(self.testdir, "100.arpa.gz")) score = lm.score('addition') - self.assert_(abs(score - (-3.2721 * LOG10TOLOG)) < 0.01) + self.assertTrue(abs(score - (-3.2721 * LOG10TOLOG)) < 0.01) score = lm.score('vector', 'variance', 'zero') - self.assert_(abs(score - (-0.9404 * LOG10TOLOG)) < 0.01) + self.assertTrue(abs(score - (-0.9404 * LOG10TOLOG)) < 0.01) # Backoff with backoff weight score = lm.score('parameters', 'variance', 'zero') - self.assert_(abs(score - ((-1.3188 + -0.8170) * LOG10TOLOG)) < 0.01) + self.assertTrue(abs(score - ((-1.3188 + -0.8170) * LOG10TOLOG)) < 0.01) # Backoff without backoff weight score = lm.score('vector', 'variance', 'abnormal') - self.assert_(abs(score - (-0.8378 * LOG10TOLOG)) < 0.01) + self.assertTrue(abs(score - (-0.8378 * LOG10TOLOG)) < 0.01) if __name__ == '__main__': unittest.main() diff --git a/python/cmusphinx/test_evaluation.py b/python/cmusphinx/test_evaluation.py index 6236f5f7..a1354271 100644 --- a/python/cmusphinx/test_evaluation.py +++ b/python/cmusphinx/test_evaluation.py @@ -8,17 +8,17 @@ class TestEvaluation(unittest.TestCase): def test_parse_hyp(self): t, u, s = evaluation.parse_hyp("FOO BAR BLATZ (ught)") - self.assertEquals(t.strip(), "FOO BAR BLATZ") - self.assertEquals(u, "ught") - self.assertEquals(s, 0) + self.assertEqual(t.strip(), "FOO BAR BLATZ") + self.assertEqual(u, "ught") + self.assertEqual(s, 0) t, u, s = evaluation.parse_hyp(" FOOY BAR HURRRF (ught -2342)") - self.assertEquals(t.strip(), "FOOY BAR HURRRF") - self.assertEquals(u, "ught") - self.assertEquals(s, -2342) + self.assertEqual(t.strip(), "FOOY BAR HURRRF") + self.assertEqual(u, "ught") + self.assertEqual(s, -2342) t, u, s = evaluation.parse_hyp("HEYYYY") - self.assertEquals(t, None) - self.assertEquals(u, None) - self.assertEquals(s, 0) + self.assertEqual(t, None) + self.assertEqual(u, None) + self.assertEqual(s, 0) if __name__ == "__main__": unittest.main() diff --git a/python/cmusphinx/test_hmm.py b/python/cmusphinx/test_hmm.py index 67df15cc..86ffe806 100644 --- a/python/cmusphinx/test_hmm.py +++ b/python/cmusphinx/test_hmm.py @@ -43,7 +43,7 @@ def test_forward_backward(self): for a,b in zip(self.alpha, self.beta): newll = sum(a*b) if ll != 0: - self.assert_(abs(log(ll) - log(newll)) < 0.1) + self.assertTrue(abs(log(ll) - log(newll)) < 0.1) ll = newll class TestPhoneHMM(unittest.TestCase): @@ -58,7 +58,7 @@ def test_create(self): h1 = hmm.HMM(self.acmod.mdef.pid2sseq(pid), self.acmod.tmat[self.acmod.mdef.pid2tmat(pid)]) h2 = self.factory.create('OW_four', 'F_four', 'R_four') - self.assertEquals(h1[0], h2[0]) + self.assertEqual(h1[0], h2[0]) class TestHMMGraph(unittest.TestCase): def setUp(self): @@ -72,9 +72,9 @@ def test_create(self): h2 = self.factory.create('OW_four', 'F_four', 'R_four') h3 = self.factory.create('R_four', 'OW_four', 'SIL') hg = hmm.HMMGraph(h1, h2, h3) - self.assertEquals(hg[0], h1[0]) - self.assertEquals(hg[4], h2[0]) - self.assertEquals(hg[8], h3[0]) + self.assertEqual(hg[0], h1[0]) + self.assertEqual(hg[4], h2[0]) + self.assertEqual(hg[8], h3[0]) def test_forward_backward(self): mfcc = s2mfc.open(os.path.join(self.testdir, 'man.ah.111a.mfc')).getall() @@ -100,7 +100,7 @@ def test_forward_backward(self): for a,b in zip(self.alpha, self.beta): newll = sum(a*b) if ll != 0: - self.assert_(abs(log(ll) - log(newll)) < 0.1) + self.assertTrue(abs(log(ll) - log(newll)) < 0.1) ll = newll def read_dict(dictfile): diff --git a/python/cmusphinx/test_s3dict.py b/python/cmusphinx/test_s3dict.py index e268310a..b5338054 100644 --- a/python/cmusphinx/test_s3dict.py +++ b/python/cmusphinx/test_s3dict.py @@ -11,13 +11,13 @@ def setUp(self): def testRead(self): foodict = s3dict.open(os.path.join(self.basedir, "test", "foo.dict")) - self.assert_('AH' in foodict.phoneset) - self.assertEquals(foodict.get_phones('A'), ['AH']) - self.assertEquals(foodict.get_alt_phones('A', 2), ['EY']) - self.assertEquals(foodict.get_phones('ZSWANG'), ['S', 'W', 'AE', 'NG']) + self.assertTrue('AH' in foodict.phoneset) + self.assertEqual(foodict.get_phones('A'), ['AH']) + self.assertEqual(foodict.get_alt_phones('A', 2), ['EY']) + self.assertEqual(foodict.get_phones('ZSWANG'), ['S', 'W', 'AE', 'NG']) try: foo = foodict.get_phones('QRXG') - print foo + print(foo) except KeyError: pass # Expected fail else: @@ -34,10 +34,10 @@ def testRead(self): pass # Expected fail else: self.fail() - self.assertEquals(foodict['A'], ['AH']) - self.assertEquals(foodict['A',2], ['EY']) - self.assertEquals(foodict['A(2)'], ['EY']) - self.assertEquals(foodict['ZSWANG'], ['S', 'W', 'AE', 'NG']) + self.assertEqual(foodict['A'], ['AH']) + self.assertEqual(foodict['A',2], ['EY']) + self.assertEqual(foodict['A(2)'], ['EY']) + self.assertEqual(foodict['ZSWANG'], ['S', 'W', 'AE', 'NG']) def testCreate(self): mydict = s3dict.S3Dict() @@ -51,24 +51,24 @@ def testCreate(self): pass # Expected fail else: self.fail() - self.assertEquals(mydict.get_phones('A'), ['AH']) - self.assertEquals(mydict.get_alt_phones('A', 2), ['EY']) - self.assertEquals(mydict.get_phones('ZSWANG'), ['S', 'W', 'AE', 'NG']) + self.assertEqual(mydict.get_phones('A'), ['AH']) + self.assertEqual(mydict.get_alt_phones('A', 2), ['EY']) + self.assertEqual(mydict.get_phones('ZSWANG'), ['S', 'W', 'AE', 'NG']) mydict.set_alt_phones('A', 2, ['AA']) - self.assertEquals(mydict.get_alt_phones('A', 2), ['AA']) - self.assert_('ZSWANG' in mydict) + self.assertEqual(mydict.get_alt_phones('A', 2), ['AA']) + self.assertTrue('ZSWANG' in mydict) mydict.del_phones('ZSWANG') - self.assert_('ZSWANG' not in mydict) - self.assert_('NG' not in mydict.phoneset) + self.assertTrue('ZSWANG' not in mydict) + self.assertTrue('NG' not in mydict.phoneset) def testUnion(self): foodict = s3dict.open(os.path.join(self.basedir, "test", "foo.dict")) bardict = s3dict.open(os.path.join(self.basedir, "test", "bar.dict")) bazdict = s3dict.union(foodict, bardict) - self.assertEquals(foodict['ACTUALLY'], bazdict['ACTUALLY']) - self.assert_('ABANDONED' in bazdict) - self.assert_('ZONES' in bazdict) - self.assert_('ZSWANG' in bazdict) + self.assertEqual(foodict['ACTUALLY'], bazdict['ACTUALLY']) + self.assertTrue('ABANDONED' in bazdict) + self.assertTrue('ZONES' in bazdict) + self.assertTrue('ZSWANG' in bazdict) if __name__ == '__main__': unittest.main() diff --git a/python/cmusphinx/test_s3file.py b/python/cmusphinx/test_s3file.py index 7462e24a..30048e51 100644 --- a/python/cmusphinx/test_s3file.py +++ b/python/cmusphinx/test_s3file.py @@ -12,7 +12,7 @@ def test_1dfile(self): s3file.S3File_write("tmp.1d").write1d(data) data2 = s3file.S3File("tmp.1d").read1d() # Assert that all elements are equal - self.assertEquals(sum(data == data2), len(data)) + self.assertEqual(sum(data == data2), len(data)) os.unlink("tmp.1d") def test_2dfile(self): @@ -20,7 +20,7 @@ def test_2dfile(self): s3file.S3File_write("tmp.2d").write2d(data) data2 = s3file.S3File("tmp.2d").read2d() # Assert that all elements are equal - self.assertEquals((data == data2).sum(), data.size) + self.assertEqual((data == data2).sum(), data.size) os.unlink("tmp.2d") def test_3dfile(self): @@ -28,7 +28,7 @@ def test_3dfile(self): s3file.S3File_write("tmp.3d").write3d(data) data2 = s3file.S3File("tmp.3d").read3d() # Assert that all elements are equal - self.assertEquals((data == data2).sum(), data.size) + self.assertEqual((data == data2).sum(), data.size) os.unlink("tmp.3d") if __name__ == '__main__': diff --git a/python/cmusphinx/test_s3model.py b/python/cmusphinx/test_s3model.py index 025054fa..7aab6b54 100644 --- a/python/cmusphinx/test_s3model.py +++ b/python/cmusphinx/test_s3model.py @@ -15,10 +15,10 @@ def setUp(self): self.acmod = s3model.S3Model(self.testdir) def test_created(self): - self.assert_(abs(self.acmod.tmat[0][0,1] - 0.3326) < 0.01) - self.assert_(abs(sum(self.acmod.mixw[0,0]) - 1.0) < 0.01) - self.assert_(abs(self.acmod.var[0][0][0][0] - 0.2583) < 0.01) - self.assert_(abs(self.acmod.var[35][0][0][38] - 16.9266) < 0.01) + self.assertTrue(abs(self.acmod.tmat[0][0,1] - 0.3326) < 0.01) + self.assertTrue(abs(sum(self.acmod.mixw[0,0]) - 1.0) < 0.01) + self.assertTrue(abs(self.acmod.var[0][0][0][0] - 0.2583) < 0.01) + self.assertTrue(abs(self.acmod.var[35][0][0][38] - 16.9266) < 0.01) def test_compute(self): mfcc = s2mfc.open(os.path.join(self.testdir, 'man.ah.111a.mfc')).getall() @@ -28,7 +28,7 @@ def test_compute(self): expected = [3.03518949e-36, 1.00000000e+00, 4.47046728e-16, 1.07179724e-01] senscr = self.acmod.senone_compute(senones, feat[0]) for i,s in enumerate(senones): - self.assert_(abs(senscr[s] - expected[i]) < 0.01) + self.assertTrue(abs(senscr[s] - expected[i]) < 0.01) if __name__ == '__main__': unittest.main()