Skip to content

Commit

Permalink
Merge pull request #155 from QuLogic/py3k-print
Browse files Browse the repository at this point in the history
py3k: Use print function instead of statement
  • Loading branch information
kba authored Jan 23, 2017
2 parents fe8d849 + 7b8e0dc commit 2e62b8e
Show file tree
Hide file tree
Showing 26 changed files with 180 additions and 130 deletions.
6 changes: 4 additions & 2 deletions OLD/ocrolib/h5utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import print_function

from numpy import dtype
import tables
import re
Expand All @@ -10,7 +12,7 @@ def table_copy(source,dest,names=None,omit=[],verbose=1):
names = names.split()
for name in names:
a = source.getNode("/"+name)
if verbose: print "[copying",name,a.shape,a.atom,"]"
if verbose: print("[copying", name, a.shape, a.atom, "]")
if "VLArray" in str(a):
b = dest.createVLArray(dest.root,name,a.atom,filters=tables.Filters(9))
else:
Expand All @@ -28,7 +30,7 @@ def assign_array(db,name,a,verbose=1):
atom = tables.Float32Atom()
else:
raise Exception('unknown array type: %s'%a.dtype)
if verbose: print "[writing",name,a.shape,atom,"]"
if verbose: print("[writing", name, a.shape, atom, "]")
node = db.createEArray(db.root,name,atom,shape=[0]+list(a.shape[1:]),filters=tables.Filters(9))
node.append(a)

Expand Down
16 changes: 9 additions & 7 deletions OLD/ocrolib/ngraphs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# TODO:
# - handle UTF-8 inputs correctly

from __future__ import print_function

from pylab import *
from collections import Counter,defaultdict
import re
Expand Down Expand Up @@ -47,7 +49,7 @@ def safe_readlines(stream,nonl=0):
try:
line = stream.readline()
except UnicodeDecodeError as e:
if not once: print lineno,":",e
if not once: print(lineno, ":", e)
once = 1
return
if line is None: return
Expand Down Expand Up @@ -75,14 +77,14 @@ def computeNGraphs(self,fnames,n):
lineskip = 0
linelimit = 2000
for fnum,fname in enumerate(fnames):
print fnum,"of",len(fnames),":",fname
print(fnum, "of", len(fnames), ":", fname)
if fname.startswith("lineskip="):
lineskip = int(fname.split("=")[1])
print "changing lineskip to",lineskip
print("changing lineskip to", lineskip)
continue
if fname.startswith("linelimit="):
linelimit = int(fname.split("=")[1])
print "changing linelimit to",linelimit
print("changing linelimit to", linelimit)
continue
with codecs.open(fname,"r","utf-8") as stream:
for lineno,line in enumerate(safe_readlines(stream)):
Expand All @@ -106,11 +108,11 @@ def __init__(self,*args,**kw):
NGraphsCounts.__init__(self,*args,**kw)
def buildFromFiles(self,fnames,n):
"""Given a set of files, build the log posteriors."""
print "reading",len(fnames),"files"
print("reading", len(fnames), "files")
counter = self.computeNGraphs(fnames,n)
print "got",sum(counter.values()),"%d-graphs"%(n,)
print("got", sum(counter.values()), "%d-graphs" % (n, ))
self.computePosteriors(counter)
print "done building lposteriors"
print("done building lposteriors")
def computePosteriors(self,counter):
"""Given a `counter` of all n-graphs, compute
(log) conditional probabilities."""
Expand Down
24 changes: 13 additions & 11 deletions examples/rnnlib-vs-ocropy.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
"cell_type": "code",
"collapsed": false,
"input": [
"from future import print_function\n",
"\n",
"from pylab import *\n",
"import os.path\n",
"import glob\n",
Expand Down Expand Up @@ -60,7 +62,7 @@
"cell_type": "code",
"collapsed": false,
"input": [
"print \"c_lstm\"\n",
"print(\"c_lstm\")\n",
"clstm = lstm_c.C_LSTM(Ni,Ns,No)\n",
"llayer = rnnscript.as_lstm2(clstm.net.hiddenLayers[0])\n",
"clstm.setLearningRate(1e-4,0.9)\n",
Expand All @@ -72,7 +74,7 @@
" err = sum((a-ys)**2)**.5\n",
" errs.append(err)\n",
" if i%10000==0:\n",
" print i,mean(errs[-1000:])\n",
" print(i, mean(errs[-1000:]))\n",
" s = clstm.states()\n",
" clf()\n",
" subplot(121);\n",
Expand All @@ -83,7 +85,7 @@
" draw()\n",
"\n",
"test_xs,test_ys = genseq()\n",
"print \"done\""
"print(\"done\")"
],
"language": "python",
"metadata": {},
Expand Down Expand Up @@ -221,7 +223,7 @@
"plot(deltas3,color='green',linestyle='dashed')\n",
"deltas4 = -array(before.nets[1].dzspre)\n",
"plot(deltas4,color='black',linestyle='dashed')\n",
"print deltas4.shape"
"print(deltas4.shape)"
],
"language": "python",
"metadata": {},
Expand Down Expand Up @@ -289,12 +291,12 @@
"clstm.ctrain(xs,ys,update=0)\n",
"h2o.debug = False\n",
"b2o.debug = False\n",
"print\n",
"print array(h2o.dinputs).reshape(3,2)\n",
"print array(h2o.dweights).reshape(3,2)\n",
"print\n",
"print array(b2o.dinputs).reshape(3)\n",
"print array(b2o.dweights).reshape(3)"
"print()\n",
"print(array(h2o.dinputs).reshape(3, 2))\n",
"print(array(h2o.dweights).reshape(3, 2))\n",
"print()\n",
"print(array(b2o.dinputs).reshape(3))\n",
"print(array(b2o.dweights).reshape(3))"
],
"language": "python",
"metadata": {},
Expand Down Expand Up @@ -364,4 +366,4 @@
"metadata": {}
}
]
}
}
22 changes: 12 additions & 10 deletions ocrolib/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
### common functions for data structures, file name manipulation, etc.
################################################################

from __future__ import print_function

import os
import os.path
import re
Expand Down Expand Up @@ -97,7 +99,7 @@ def _wrap(f):
warned = 0
def _wrapper(*args,**kw):
if not warned:
print f,"has been DEPRECATED"
print(f, "has been DEPRECATED")
warned = 1
return f(*args,**kw)
return _wrap
Expand Down Expand Up @@ -249,7 +251,7 @@ def write_image_gray(fname,image,normalize=0,verbose=0):
type, its values are clipped to the range [0,1],
multiplied by 255 and converted to unsigned bytes. Otherwise,
the image must be of type unsigned byte."""
if verbose: print "# writing",fname
if verbose: print("# writing", fname)
if isfloatarray(image):
image = array(255*clip(image,0.0,1.0),'B')
assert image.dtype==dtype('B'),"array has wrong dtype: %s"%image.dtype
Expand All @@ -272,7 +274,7 @@ def write_image_binary(fname,image,verbose=0):
"""Write a binary image to disk. This verifies first that the given image
is, in fact, binary. The image may be of any type, but must consist of only
two values."""
if verbose: print "# writing",fname
if verbose: print("# writing", fname)
assert image.ndim==2
image = array(255*(image>midrange(image)),'B')
im = array2pil(image)
Expand Down Expand Up @@ -429,7 +431,7 @@ def bbox(self,i):
"""Return the bounding box in raster coordinates
(row0,col0,row1,col1)."""
r = self.objects[i]
# print "@@@bbox",i,r
# print("@@@bbox", i, r)
return (r[0].start,r[1].start,r[0].stop,r[1].stop)
def bboxMath(self,i):
"""Return the bounding box in math coordinates
Expand All @@ -443,7 +445,7 @@ def length(self):
def mask(self,index,margin=0):
"""Return the mask for component index."""
b = self.objects[index]
#print "@@@mask",index,b
# print("@@@mask", index, b)
m = self.labels[b]
m[m!=index] = 0
if margin>0: m = pad_by(m,margin)
Expand Down Expand Up @@ -500,7 +502,7 @@ class names that have changed."""
if not nofind:
fname = ocropus_find_file(fname)
if verbose:
print "# loading object",fname
print("# loading object", fname)
if zip==0 and fname.endswith(".gz"):
zip = 1
if zip>0:
Expand Down Expand Up @@ -866,7 +868,7 @@ def pyconstruct(s):
path = s[:s.find("(")]
if "." in path:
module = path[:path.rfind(".")]
print "import",module
print("import", module)
exec "import "+module in env
return eval(s,env)

Expand Down Expand Up @@ -923,15 +925,15 @@ def save_component(file,object,verbose=0,verify=0):
ocropus.save_component(file,object)
return
if verbose:
print "[save_component]"
print("[save_component]")
if verbose:
for k,v in object.__dict__.items():
print ":",k,obinfo(v)
print(":", k, obinfo(v))
with open(file,"wb") as stream:
pickle.dump(object,stream,pickle_mode)
if verify:
if verbose:
print "[trying to read it again]"
print("[trying to read it again]")
with open(file,"rb") as stream:
pickle.load(stream)

Expand Down
4 changes: 2 additions & 2 deletions ocrolib/edist.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def xlevenshtein(a,b,context=1):
same = filters.minimum_filter(same,1+2*context)
als = "".join([al[i] if not same[i] else "~" for i in range(len(al))])
bls = "".join([bl[i] if not same[i] else "~" for i in range(len(bl))])
# print als
# print bls
# print(als)
# print(bls)
ags = re.split(r'~+',als)
bgs = re.split(r'~+',bls)
confusions = [(a,b) for a,b in zip(ags,bgs) if a!="" or b!=""]
Expand Down
8 changes: 5 additions & 3 deletions ocrolib/extras/fgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
### text image generation with Cairo
################################################################

from __future__ import print_function

import ctypes
import cairo
from cairoextras import *
Expand Down Expand Up @@ -104,7 +106,7 @@ def pango_render_string(s,spec=None,fontfile=None,size=None,bg=(0.0,0.0,0.0),fg=
else:
layout.set_markup(s)
((xbear,ybear,tw,th),_) = layout.get_pixel_extents()
# print xbear,ybear,tw,th
# print(xbear, ybear, tw, th)
tw = tw+2*pad
th = th+2*pad
if tw<=w and th<=h: break
Expand Down Expand Up @@ -160,12 +162,12 @@ def gauss_distort(images,maxdelta=2.0,sigma=10.0):
deltas /= max(amax(deltas),-amin(deltas))
deltas *= maxdelta
xy = transpose(array(meshgrid(range(n),range(m))),axes=[0,2,1])
# print xy.shape,deltas.shape
# print(xy.shape, deltas.shape)
deltas += xy
return [map_coordinates(image,deltas,order=1) for image in images]

if __name__=="__main__":
# print sorted(pango_families())
# print(sorted(pango_families()))
ion()
show()
while 1:
Expand Down
2 changes: 2 additions & 0 deletions ocrolib/extras/lru.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# Source: http://code.activestate.com/recipes/498245-lru-and-lfu-cache-decorators/
# Author: Raymond Hettinger

from __future__ import print_function

import collections
import functools
from itertools import ifilterfalse
Expand Down
4 changes: 3 additions & 1 deletion ocrolib/lineest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import print_function

import sys
import os
import re
Expand All @@ -21,7 +23,7 @@ def __init__(self,target_height=48,params=(4,1.0,0.3)):
self.debug = int(os.getenv("debug_center") or "0")
self.target_height = target_height
self.range,self.smoothness,self.extra = params
print "# CenterNormalizer"
print("# CenterNormalizer")
def setHeight(self,target_height):
self.target_height = target_height
def measure(self,line):
Expand Down
10 changes: 6 additions & 4 deletions ocrolib/lstm.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
# Author: Thomas M. Breuel
# License: Apache 2.0

from __future__ import print_function

import common as ocrolib
from pylab import *
from collections import defaultdict
Expand Down Expand Up @@ -223,7 +225,7 @@ def update(self):
ds.ravel()[:] = self.momentum * ds.ravel()[:] + self.learning_rate * dw.ravel()[:]
w.ravel()[:] += ds.ravel()[:]
if self.verbose:
print n,(amin(w),amax(w)),(amin(dw),amax(dw))
print(n, (amin(w), amax(w)), (amin(dw), amax(dw)))

''' The following are subclass responsibility:
Expand Down Expand Up @@ -281,7 +283,7 @@ def info(self):
vars = sorted("W2".split())
for v in vars:
a = array(getattr(self,v))
print v,a.shape,amin(a),amax(a)
print(v, a.shape, amin(a), amax(a))
def weights(self):
yield self.W2,self.DW2,"Logreg"

Expand Down Expand Up @@ -325,7 +327,7 @@ def info(self):
vars = sorted("W2".split())
for v in vars:
a = array(getattr(self,v))
print v,a.shape,amin(a),amax(a)
print(v, a.shape, amin(a), amax(a))
def weights(self):
yield self.W2,self.DW2,"Softmax"

Expand Down Expand Up @@ -514,7 +516,7 @@ def info(self):
vars = sorted(vars)
for v in vars:
a = array(getattr(self,v))
print v,a.shape,amin(a),amax(a)
print(v, a.shape, amin(a), amax(a))
def preSave(self):
self.max_n = max(500,len(self.ci))
self.allocate(1)
Expand Down
8 changes: 5 additions & 3 deletions ocrolib/morph.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
### various add-ons to the SciPy morphology package
################################################################

from __future__ import print_function

from numpy import *
import pylab
from pylab import *
Expand Down Expand Up @@ -198,9 +200,9 @@ def select_regions(binary,f,min=0,nbest=100000):
for i in best[-nbest:]:
if scores[i]<=min: continue
keep[i+1] = 1
# print scores,best[-nbest:],keep
# print sorted(list(set(labels.ravel())))
# print sorted(list(set(keep[labels].ravel())))
# print(scores, best[-nbest:], keep)
# print(sorted(list(set(labels.ravel()))))
# print(sorted(list(set(keep[labels].ravel()))))
return keep[labels]

@checks(SEGMENTATION)
Expand Down
Loading

0 comments on commit 2e62b8e

Please sign in to comment.