80 lines
2.6 KiB
Python
80 lines
2.6 KiB
Python
import argparse
|
|
import sys
|
|
import logging
|
|
import importlib
|
|
|
|
from pylabel import LabelSheet
|
|
|
|
class EmptySpec:
|
|
profile = None
|
|
template = None
|
|
data = None
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
parser = argparse.ArgumentParser(description="Generate a page of labels")
|
|
|
|
parser.add_argument('--count', '-c', type=int, default=0, help="Number of labels to generate")
|
|
parser.add_argument('--offset', '-o', type=int, default=0, help="Skip first n labels")
|
|
parser.add_argument('--profile', '-p', help='Label profile')
|
|
parser.add_argument('--template', '-t', type=argparse.FileType('r'), help='Template for label')
|
|
parser.add_argument('--style', '-s', type=argparse.FileType('r'), help='Additional stylesheet')
|
|
parser.add_argument('--data', '-d', type=argparse.FileType('r'), help="Pre-generated data, one entry per line")
|
|
parser.add_argument('--json', '-j', action='store_true', help='Parse data lines as json')
|
|
parser.add_argument('--logging', '-l', default="info", help="Logging level")
|
|
|
|
parser.add_argument("spec", nargs="?", help="Specification module")
|
|
|
|
options = parser.parse_args()
|
|
|
|
logging.basicConfig(level=getattr(logging, options.logging.upper(), logging.INFO))
|
|
|
|
logger.debug(options)
|
|
|
|
if options.spec:
|
|
spec = importlib.import_module(options.spec)
|
|
else:
|
|
spec = EmptySpec
|
|
|
|
try:
|
|
if options.profile:
|
|
module, profile = options.profile.rsplit('.', 1)
|
|
if module.startswith('avery'):
|
|
module = 'pylabel.avery'
|
|
m = importlib.import_module(module)
|
|
spec.profile = getattr(m, profile)
|
|
except ValueError:
|
|
raise RuntimeError("Expected profile in the form module.profile")
|
|
except ModuleNotFoundError:
|
|
raise RuntimeError(f"Unable to find profile module {module}")
|
|
except AttributeError:
|
|
raise RuntimeError(f"Unable to file profile {profile} in module {module}")
|
|
|
|
if options.template is not None:
|
|
spec.template = options.template.read()
|
|
options.template.close()
|
|
|
|
|
|
if options.style is not None:
|
|
spec.style = options.style.read()
|
|
options.style.close()
|
|
|
|
if options.data is not None:
|
|
lines = [ l.strip() for l in options.data.readlines() if l != '\n' ]
|
|
options.data.close()
|
|
if options.json:
|
|
import json
|
|
spec.data = [ json.loads(line) for line in lines ]
|
|
else:
|
|
spec.data = [ {'text': line} for line in lines ]
|
|
|
|
if options.count:
|
|
spec.data = range(options.count)
|
|
|
|
for required in ('profile', 'template', 'data'):
|
|
if not getattr(spec, required):
|
|
parser.error(f"Missing {required}")
|
|
|
|
sheet = LabelSheet(spec.profile)
|
|
|
|
sys.stdout.write(sheet.render_html(spec.template, spec.data, options.offset, getattr(spec, 'style', ''))) |