Commit 460ae5ef authored by Michael Murtaugh's avatar Michael Murtaugh

initial code from various sources

parents
Pipeline #244 canceled with stages
#!/usr/bin/env python3
from PIL import Image
import argparse, os
ap = argparse.ArgumentParser("")
ap.add_argument("input")
ap.add_argument("--thumbs", default=".thumbnails")
args = ap.parse_args()
im = Image.open(args.input)
print (im.size)
base = os.path.basename(args.input)
tpath = os.path.join(args.thumbs, base)
try:
os.makedirs(tpath)
except OSError:
pass
print ("Created {0}".format(tpath))
# import iso8601
import datetime
# def parsedate (x):
# if type(x) == datetime.datetime:
# return x
# try:
# return iso8601.parse_date(x)
# except iso8601.ParseError:
# return datetime.datetime.fromtimestamp(int(x))
def datetimeformat (t, format='%Y-%m-%d %H:%M:%S'):
return parsedate(t).strftime(format)
# def datetimeformat (t, format='%Y-%m-%d %H:%M:%S'):
# return time.strftime(format, time.localtime(t))
from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
def humanize_bytes(bytesize, precision=2):
"""
Humanize byte size figures
"""
abbrevs = (
(1 << 50, 'PB'),
(1 << 40, 'TB'),
(1 << 30, 'GB'),
(1 << 20, 'MB'),
(1 << 10, 'kB'),
(1, 'bytes')
)
if bytesize == 1:
return '1 byte'
for factor, suffix in abbrevs:
if bytesize >= factor:
break
if factor == 1:
precision = 0
return '%.*f %s' % (precision, bytesize / float(factor), suffix)
import math
def timecode(rawsecs, fract=True, alwaysfract=True, fractdelim='.', alwayshours=True):
# returns a string in HH:MM:SS[.xxx] notation
# if fract is True, uses .xxx if either necessary (non-zero)
# OR alwaysfract is True
hours = math.floor(rawsecs / 3600)
rawsecs -= hours * 3600
mins = math.floor(rawsecs / 60)
rawsecs -= mins * 60
if fract:
secs = math.floor(rawsecs)
rawsecs -= secs
if (rawsecs > 0 or alwaysfract):
fract = "%.03f" % rawsecs
if hours or alwayshours:
return "%02d:%02d:%02d%s%s" % (hours, mins, secs, fractdelim, \
fract[2:])
else:
return "%02d:%02d%s%s" % (mins, secs, fractdelim, fract[2:])
else:
if hours or alwayshours:
return "%02d:%02d:%02d" % (hours, mins, secs)
else:
return "%02d:%02d" % (mins, secs)
else:
secs = round(rawsecs)
if hours or alwayshours:
return "%02d:%02d:%02d" % (hours, mins, secs)
else:
return "%02d:%02d" % (mins, secs)
all = {
'datetimeformat': datetimeformat,
'grouper': grouper,
'timecode': timecode,
'humanize_bytes': humanize_bytes
}
\ No newline at end of file
#!/usr/bin/env python3
import argparse, sys, json, time, os
from jinja2 import Template, DictLoader, Environment, FileSystemLoader
ap = argparse.ArgumentParser("jinjafy!")
ap.add_argument("template")
ap.add_argument("--columns", type=int, default=None, help="treat incoming data as text in this many columns and not json (the default behaviour)")
ap.add_argument("--data", type=argparse.FileType('r'), default=sys.stdin)
ap.add_argument("--listkey", default="items", help="if incoming data is a list, give it this name for the template, default: items")
ap.add_argument("--output", type=argparse.FileType('w'), default=sys.stdout)
args = ap.parse_args()
if args.columns:
data = []
for line in args.data:
line = line.split(None, args.columns-1)
if line:
data.append(line)
else:
data = json.load(args.data)
tpath, tname = os.path.split(args.template)
env = Environment(loader=FileSystemLoader(tpath))
import jinjafilters
for name, fn in jinjafilters.all.items():
env.filters[name] = fn
template = env.get_template(tname)
if type(data) == list:
# print ("Detected list, adding as {0}".format(args.listkey), file=sys.stderr)
data = {
args.listkey: data
}
print (template.render(**data), file=args.output)
#!/usr/bin/env python
from __future__ import print_function
from PIL import Image
import re, sys, json, os
try:
from urllib import quote as urlquote # Python 2.X
except ImportError:
from urllib.parse import quote as urlquote # Python 3+
def fitbox (boxw, boxh, w, h):
rw = boxw
rh = int(rw * (float(h) / w))
if (rh >= boxh):
rh = boxh
rw = int(rh * (float(w) / h))
return rw, rh
def tile_image (im, maxz=0, tilew=256, tileh=256, base=".", template="z{0[z]}y{0[y]}x{0[x]}.jpg", bgcolor=(0,0,0), margin_right=0, margin_bottom=0):
z = 0
boxw, boxh = tilew, tileh
alpha = bgcolor != None # not template.endswith("jpg")
while True:
rw, rh = fitbox(boxw, boxh, im.size[0], im.size[1])
rim = im.resize((rw-margin_right, rh-margin_bottom), Image.ANTIALIAS)
if bgcolor:
tim = Image.new("RGB", (boxw, boxh), bgcolor)
tim.paste(rim, (0, 0))
else:
tim = Image.new("RGBA", (boxw, boxh))
tim.paste(rim, (0, 0))
rows, cols = 2**z, 2**z
for r in range(rows):
for c in range(cols):
ix = c*tilew
iy = r*tileh
cim = tim.crop((ix, iy, ix+tilew, iy+tileh))
op = base + template.format({'z':z, 'x':c, 'y':r})
# if not alpha:
# cim = cim.convert("RGB")
cim.save(op)
z += 1
if z>maxz:
break
boxw *= 2
boxh *= 2
def expand_template (x):
return re.sub(r"{(\w+?)}", "{0[\\1]}", x)
if __name__ == "__main__":
from argparse import ArgumentParser
ap = ArgumentParser("Generate image tiles and output JSON for a collection of images")
ap.add_argument("input", nargs="+")
ap.add_argument("--basepath", default=".")
ap.add_argument("--baseuri", default="")
ap.add_argument("--tilespath", default="tiles", help="name of path to create in the same folder as the original")
ap.add_argument("--tilewidth", type=int, default=256)
ap.add_argument("--tileheight", type=int, default=256)
ap.add_argument("--zoom", type=int, default=3)
ap.add_argument("--tilename", default="z{z}y{y}x{x}.jpg")
ap.add_argument("--force", default=False, action="store_true")
args = ap.parse_args()
"""
leafygal format: {id: original, tiles: "template", name: filename}
"""
tilenamex = expand_template(args.tilename)
bgcolor = (199, 199, 199)
items = []
for imgpath in args.input:
parent = os.path.split(imgpath)[0]
basename = os.path.basename(imgpath)
path = os.path.join(parent, args.tilespath, basename)
item = {
'id': urlquote(imgpath),
'name': basename,
'tiles': os.path.join(path, args.tilename)
}
tile0 = os.path.join(path, tilenamex.format({'x': 0, 'y': 0, 'z': 0}))
items.append(item)
if not os.path.exists(tile0) or args.force:
print ("Tiling {0}".format(imgpath), file=sys.stderr)
try:
im = Image.open(imgpath)
try:
os.makedirs(path)
except OSError:
pass
tile_image(im, args.zoom, args.tilewidth, args.tileheight, path+"/", tilenamex, bgcolor)
# tiles.append(t)
except IOError as e:
print ("Missing {0}, skipping".format(n), file=sys.stderr)
items = items[:-1]
data = {
'@context': {
'id': '@id',
'aa': 'http://activearchives.org/terms',
'name': 'aa:filename',
'tiles': 'aa:tiles'
},
'@graph': items
}
print (json.dumps(data, indent=2))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment