Skip to content

Commit c80f6da

Browse files
author
Robert Sachunsky
committed
ocrolib: avoid print/stderr.write in favor of logging
1 parent e78ced0 commit c80f6da

File tree

5 files changed

+32
-34
lines changed

5 files changed

+32
-34
lines changed

ocrd_cis/ocropy/ocrolib/common.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525
from . import default
2626
from .default import getlocal
27-
from .toplevel import (checks, ABINARY2, AINT2, AINT3, BOOL, DARKSEG, GRAYSCALE,
27+
from .toplevel import (checks, LOG, ABINARY2, AINT2, AINT3, BOOL, DARKSEG, GRAYSCALE,
2828
LIGHTSEG, LINESEG, PAGESEG)
2929
from . import chars
3030
from . import ligatures
@@ -35,7 +35,6 @@
3535

3636
pickle_mode = 2
3737

38-
3938
################################################################
4039
# text normalization
4140
################################################################
@@ -187,7 +186,8 @@ def write_image_gray(fname,image,normalize=0,verbose=0):
187186
type, its values are clipped to the range [0,1],
188187
multiplied by 255 and converted to unsigned bytes. Otherwise,
189188
the image must be of type unsigned byte."""
190-
if verbose: print("# writing", fname)
189+
if verbose:
190+
LOG.info("# writing '%s'", fname)
191191
if isfloatarray(image):
192192
image = array(255*clip(image,0.0,1.0),'B')
193193
assert image.dtype==dtype('B'),"array has wrong dtype: %s"%image.dtype
@@ -210,7 +210,8 @@ def write_image_binary(fname,image,verbose=0):
210210
"""Write a binary image to disk. This verifies first that the given image
211211
is, in fact, binary. The image may be of any type, but must consist of only
212212
two values."""
213-
if verbose: print("# writing", fname)
213+
if verbose:
214+
LOG.info("# writing '%s'", fname)
214215
assert image.ndim==2
215216
image = array(255*(image>midrange(image)),'B')
216217
im = array2pil(image)
@@ -440,8 +441,8 @@ def load_object(fname,zip=0,nofind=0,verbose=0):
440441
class names that have changed."""
441442
if not nofind:
442443
fname = ocropus_find_file(fname)
443-
#if verbose:
444-
# print("# loading object", fname)
444+
if verbose:
445+
LOG.info("# loading object '%s'", fname)
445446
if zip==0 and fname.endswith(".gz"):
446447
zip = 1
447448
if zip>0:
@@ -720,16 +721,12 @@ def caller():
720721

721722
def die(message,*args):
722723
"""Die with an error message."""
723-
message = message%args
724-
message = caller()+" FATAL "+message+"\n"
725-
sys.stderr.write(message)
724+
LOG.critical(caller() + ' ' + message, args)
726725
sys.exit(1)
727726

728727
def warn(message,*args):
729728
"""Give a warning message."""
730-
message = message%args
731-
message = caller()+" WARNING "+message+"\n"
732-
sys.stderr.write(message)
729+
LOG.warning(caller() + ' ' + message, args)
733730

734731
already_warned = {}
735732

@@ -738,9 +735,7 @@ def warn_once(message,*args):
738735
c = caller()
739736
if c in already_warned: return
740737
already_warned[c] = 1
741-
message = message%args
742-
message = c+" WARNING "+message+"\n"
743-
sys.stderr.write(message)
738+
LOG.warning(c + ' ' + message, args)
744739

745740
def quick_check_page_components(page_bin,dpi):
746741
"""Quickly check whether the components of page_bin are

ocrd_cis/ocropy/ocrolib/lineest.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ def __init__(self,target_height=48,params=(4,1.0,0.3)):
2020
self.debug = int(os.getenv("debug_center") or "0")
2121
self.target_height = target_height
2222
self.range,self.smoothness,self.extra = params
23-
print("# CenterNormalizer")
2423
def setHeight(self,target_height):
2524
self.target_height = target_height
2625
def check(self,line, max_ignore=0.02):

ocrd_cis/ocropy/ocrolib/lstm.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,13 @@
3333
from scipy.ndimage import measurements,filters
3434

3535
from . import common as ocrolib
36+
from .toplevel import LOG
3637
from .exceptions import RecognitionError
3738
from .edist import levenshtein
3839
from . import utils
3940

4041
initial_range = 0.1
4142

42-
class RangeError(Exception):
43-
def __init__(self,s=None):
44-
Exception.__init__(self,s)
45-
4643
def prepare_line(line,pad=16):
4744
"""Prepare a line for recognition; this inverts it, transposes
4845
it, and pads it."""
@@ -216,7 +213,7 @@ def update(self):
216213
ds.ravel()[:] = self.momentum * ds.ravel()[:] + self.learning_rate * dw.ravel()[:]
217214
w.ravel()[:] += ds.ravel()[:]
218215
if self.verbose:
219-
print(n, (np.amin(w), np.amax(w)), (np.amin(dw), np.amax(dw)))
216+
LOG.info("{} {} {}".format(n, (np.amin(w), np.amax(w)), (np.amin(dw), np.amax(dw))))
220217

221218
def forward(self,xs):
222219
"""Propagate activations forward through the network.
@@ -270,7 +267,7 @@ def info(self):
270267
vars = sorted("W2".split())
271268
for v in vars:
272269
a = np.array(getattr(self,v))
273-
print(v, a.shape, np.amin(a), np.amax(a))
270+
LOG.info("{} {} {} {}".format(v, a.shape, np.amin(a), np.amax(a)))
274271
def weights(self):
275272
yield self.W2,self.DW2,"Logreg"
276273

@@ -314,7 +311,7 @@ def info(self):
314311
vars = sorted("W2".split())
315312
for v in vars:
316313
a = np.array(getattr(self,v))
317-
print(v, a.shape, np.amin(a), np.amax(a))
314+
LOG.info("{} {} {} {}".format(v, a.shape, np.amin(a), np.amax(a)))
318315
def weights(self):
319316
yield self.W2,self.DW2,"Softmax"
320317

@@ -504,7 +501,7 @@ def info(self):
504501
vars = sorted(vars)
505502
for v in vars:
506503
a = np.array(getattr(self,v))
507-
print(v, a.shape, np.amin(a), np.amax(a))
504+
LOG.info("{} {} {} {}".format(v, a.shape, np.amin(a), np.amax(a)))
508505
def preSave(self):
509506
self.max_n = max(500,len(self.ci))
510507
self.allocate(1)
@@ -719,7 +716,7 @@ def make_target(cs,nc):
719716
result[2*i+1,j] = 1.0
720717
result[-1,0] = 1.0
721718
except(IndexError):
722-
print('\n!!! Uuups, something went wrong !!!\nDid you import a model that was trained on less characters then needed for this operation?')
719+
LOG.critical('Cannot index target class. Did you load a model that was trained on less characters then needed for this operation?')
723720
sys.exit(1)
724721
return result
725722

ocrd_cis/ocropy/ocrolib/psegutils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,5 +227,6 @@ def rgbshow(r,g,b=None,gn=1,cn=0,ab=0,**kw):
227227
combo /= max(np.abs(np.amin(combo)),np.abs(np.amax(combo)))
228228
if ab:
229229
combo = np.abs(combo)
230-
if np.amin(combo)<0: print("warning: values less than zero")
230+
if np.amin(combo)<0:
231+
LOG.warning("RGB values less than zero")
231232
plt.imshow(np.clip(combo,0,1),**kw)

ocrd_cis/ocropy/ocrolib/toplevel.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44
import os
55
import sys
66
import warnings
7+
import logging
78

89
import numpy as np
910
from functools import (reduce, wraps)
1011

12+
LOG = logging.getLogger('ocrolib')
13+
1114
### printing
1215

1316
def strc(arg,n=10):
@@ -54,15 +57,15 @@ def wrapper(*args,**kw):
5457
try:
5558
global _trace1_depth
5659
_trace1_depth += 1
57-
print(" " * _trace1_depth, "ENTER", name, ":", end=' ')
60+
message = " " * _trace1_depth + " ENTER %s: " % name
5861
for k,v in list(zip(argnames,args))+list(kw.items()):
59-
print("%s=%s" % (k, strc(v)), end=' ')
60-
print()
62+
message += "%s=%s " % (k, strc(v))
63+
LOG.debug(message)
6164
result = f(*args,**kw)
62-
print(" " * _trace1_depth, "LEAVE", name, ":", strc(result))
65+
LOG.debug(" " * _trace1_depth + " LEAVE %s: %s", name, strc(result))
6366
return result
6467
except Exception as e:
65-
print(" " * _trace1_depth, "ERROR", name, ":", e)
68+
LOG.debug(" " * _trace1_depth + " ERROR %s: ", name, exc_info=e)
6669
raise
6770
finally:
6871
_trace1_depth -= 1
@@ -78,13 +81,16 @@ def localtrace(frame, why, arg):
7881
fname = frame.f_code.co_filename
7982
lineno = frame.f_lineno
8083
base = os.path.basename(fname)
81-
print("%s(%s): %s" % (base, lineno,
82-
linecache.getline(fname, lineno)))
84+
LOG.debug("%s(%s): %s", base, lineno,
85+
linecache.getline(fname, lineno))
8386
return localtrace
8487
@wraps(f)
8588
def wrapper(*args,**kw):
8689
sys.settrace(globaltrace)
90+
level = LOG.level
91+
LOG.setLevel('DEBUG')
8792
result = f(*args,**kw)
93+
LOG.setLevel(level)
8894
sys.settrace(None)
8995
return result
9096
return wrapper
@@ -205,7 +211,7 @@ def argument_checks(*args,**kw):
205211
e.var = var
206212
raise e
207213
except:
208-
print("unknown exception while checking function:", name)
214+
LOG.critical("unknown exception while checking function: '%s'", name)
209215
raise
210216
result = f(*args,**kw)
211217
checktype(result,kw.get("_",True))

0 commit comments

Comments
 (0)