"""dfg_art.py - Desert Fox Golf concept-artwork toolkit (Maggy + DJ-10 Midnight). Needs: python3, numpy, opencv-python, scipy, pillow, cairosvg, and poppler's `pdftocairo` on PATH.""" import re, os, io, math, json, base64, subprocess, urllib.request, urllib.parse import numpy as np, cv2, cairosvg from PIL import Image from scipy import ndimage as ndi # ---- product dielines (PDF points, 72 per inch). Do not edit these shapes. ---- PRODUCTS = { 'maggy': dict(file='Magnetic Phone Caddy', layer='Maggy', W=178.583, H=178.583, png=(732, 732), cy=0.50, die='M 22.012 178.168 C 9.875 178.168 0 168.293 0 156.156 L 0 22.012 C 0 9.875 9.875 0 22.012 0 L 156.156 0 ' 'C 168.293 0 178.168 9.875 178.168 22.012 L 178.168 156.156 C 178.168 168.293 168.293 178.168 156.156 178.168 Z'), 'dj10': dict(file='Speaker V2', layer='DJ-10', W=172.913, H=158.74, png=(709, 650), cy=0.46, die='M 104.809 158.48 C 103.637 158.48 102.688 157.527 102.688 156.359 L 102.688 152.113 C 102.688 143.141 95.387 135.84 ' '86.414 135.84 C 77.441 135.84 70.141 143.141 70.141 152.113 L 70.141 156.359 C 70.141 157.527 69.188 158.48 68.02 158.48 ' 'L 7.172 158.48 C 3.273 158.48 0.098 155.305 0.098 151.406 L 0.098 7.074 C 0.098 3.172 3.273 0 7.172 0 L 165.652 0 ' 'C 169.555 0 172.727 3.172 172.727 7.074 L 172.727 151.406 C 172.727 155.305 169.555 158.48 165.652 158.48 Z'), } RASTER = ('.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tif', '.tiff') def _disk(r): r = max(1, int(round(r))); y, x = np.ogrid[-r:r + 1, -r:r + 1]; return (x * x + y * y) <= r * r def hexrgb(h): h = h.lstrip('#'); return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)) def rgbhex(c): return '#%02X%02X%02X' % tuple(int(max(0, min(255, round(v)))) for v in c) def mix(a, b, t): A, B = hexrgb(a), hexrgb(b); return rgbhex([A[i] + (B[i] - A[i]) * t for i in range(3)]) def luminance(h): def f(v): v /= 255; return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4 r, g, b = hexrgb(h); return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b) def contrast(a, b): la, lb = sorted([luminance(a), luminance(b)], reverse=True); return (la + 0.05) / (lb + 0.05) class Logo: """Loads a customer logo (SVG/PDF/AI vector, or PNG/JPG raster) and exposes it as SVG fragments. drop: indexes of filled vector paths to delete (leftover background pieces - see debug_sheet).""" PX = 3000 # working raster width used for analysis and tracing def __init__(self, path, drop=()): ext = os.path.splitext(path)[1].lower() self.vector = ext not in RASTER if self.vector: pdf = path if ext == '.svg': pdf = path + '.tmp.pdf'; cairosvg.svg2pdf(url=path, write_to=pdf) svg = subprocess.run(['pdftocairo', '-svg', pdf, '-'], capture_output=True, check=True).stdout.decode() if pdf != path: os.remove(pdf) vb = list(map(float, re.search(r'viewBox="([^"]+)"', svg).group(1).split())) self.vw, self.vh = vb[2], vb[3] inner = svg[svg.index('>', svg.index('')] self.paths = list(re.finditer(r']*?fill="([^"]+)"[^>]*? d="([^"]+)"[^>]*/>', inner)) kill = [m.group(0) for i, m in enumerate(self.paths) if i in set(drop) or self._is_bg(m)] # Illustrator PDFs often carry a hidden grey duplicate of the art underneath: keep only the top copy. ds = [m.group(2) for m in self.paths]; half = len(ds) // 2 if half and len(ds) % 2 == 0 and ds[:half] == ds[half:]: kill += [m.group(0) for m in self.paths[:half]] self.paths = self.paths[half:] for k in kill: inner = inner.replace(k, '', 1) self.inner = inner self.simple = not re.search(r'<(image|use|mask|pattern|linearGradient|radialGradient)\b|stroke="(?!none)', inner) png = cairosvg.svg2png(bytestring=self._doc(inner, 0, 0, self.vw, self.vh).encode(), output_width=self.PX) rgba = np.array(Image.open(io.BytesIO(png)).convert('RGBA')) else: im = Image.open(path).convert('RGBA'); s = self.PX / im.width im = im.resize((self.PX, max(1, round(im.height * s))), Image.LANCZOS) rgba = self._strip_bg(np.array(im)); self.vw, self.vh = float(rgba.shape[1]), float(rgba.shape[0]) self.simple = False self.k = rgba.shape[1] / self.vw # px per logo unit a = rgba[:, :, 3] > 128 ys, xs = np.where(a) if not len(xs): raise ValueError('logo is empty after background removal') self.px0, self.py0, self.px1, self.py1 = xs.min(), ys.min(), xs.max() + 1, ys.max() + 1 self.rgba = rgba[self.py0:self.py1, self.px0:self.px1]; self.alpha = self.rgba[:, :, 3] > 128 self.box = tuple(float(v) for v in (self.px0 / self.k, self.py0 / self.k, (self.px1 - self.px0) / self.k, (self.py1 - self.py0) / self.k)) self.aspect = self.box[2] / self.box[3] self.colors = self._palette() self.mono = len(self.colors) == 1 if not self.vector: b = io.BytesIO(); Image.fromarray(self.rgba).save(b, 'PNG'); self._b64 = base64.b64encode(b.getvalue()).decode() # -- internals -- def _doc(self, inner, x, y, w, h, bg=None): r = '' % (x, y, w, h, bg) if bg else '' return '%s%s' % (x, y, w, h, r, inner) def _nums(self, d): n = list(map(float, re.findall(r'-?\d+\.?\d*', d))); return n[0::2], n[1::2] def _is_bg(self, m): xs, ys = self._nums(m.group(2)) return (max(xs) - min(xs)) > self.vw * 0.97 and (max(ys) - min(ys)) > self.vh * 0.97 def _strip_bg(self, rgba): if (rgba[:, :, 3] < 250).mean() > 0.02: return rgba # already transparent rgb = rgba[:, :, :3].astype(int); corners = np.array([rgb[0, 0], rgb[0, -1], rgb[-1, 0], rgb[-1, -1]]); bg = np.median(corners, 0) near = (np.abs(rgb - bg).sum(2) < 40) lab, _ = ndi.label(near); edge = set(lab[0]) | set(lab[-1]) | set(lab[:, 0]) | set(lab[:, -1]); edge.discard(0) out = rgba.copy(); out[np.isin(lab, list(edge)), 3] = 0; return out # only background connected to the border def _palette(self): px = self.rgba[self.alpha][:, :3]; q = (px // 24) * 24 + 12 vals, cnt = np.unique(q, axis=0, return_counts=True); order = np.argsort(-cnt); out = [] for i in order: if cnt[i] / len(px) < 0.03: break c = px[(q == vals[i]).all(1)].mean(0) if all(np.abs(c - np.array(hexrgb(o[0]))).sum() > 60 for o in out): out.append((rgbhex(c), round(float(cnt[i]) / len(px), 3))) return out def _place(self, x, y, w): s = w / self.box[2]; return s, 'translate(%s %s) scale(%s) translate(%s %s)' % (x, y, s, -self.box[0], -self.box[1]) def _trace(self, mask, eps=0.6): """Boolean pixel mask (cropped-logo pixel space) -> SVG path in logo units, holes preserved (use fill-rule evenodd).""" cs, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE); d = '' for c in cs: if cv2.contourArea(c) < 12: continue p = cv2.approxPolyDP(c, eps, True)[:, 0, :] if len(p) < 3: continue d += 'M' + 'L'.join('%.2f %.2f' % ((x + self.px0) / self.k, (y + self.py0) / self.k) for x, y in p) + 'Z' return d # -- public fragments (x, y = top-left in product points, w = width in points) -- def height(self, w): return w / self.aspect def original(self, x, y, w): """The logo in its own colours.""" s, t = self._place(x, y, w) if self.vector: return '%s' % (t, self.inner) return '' % (x, y, w, self.height(w), self._b64) def solid(self, x, y, w, color): """The whole logo recoloured to one flat colour (what you want for a single-colour logo).""" s, t = self._place(x, y, w) if self.vector and self.simple: return '%s' % (t, re.sub(r'fill="(?!none)[^"]+"', 'fill="%s"' % color, self.inner)) return '' % (t, self._trace(self.alpha), color) def motif(self, region=(0, 0, 1, 1), paths=None): """A reusable shape traced from part of the logo. Either region = fractions of the logo box (x0,y0,x1,y1), or, for vector logos, paths = indexes of the filled paths that make up the mark (from debug_sheet) - use paths when the mark overlaps lettering. Returns (path_d, width, height) with the shape's top-left at 0,0 in logo units.""" h, w = self.alpha.shape; x0, y0, x1, y1 = region if paths is not None and self.vector: keep = ''.join(self.paths[i].group(0) for i in paths) png = cairosvg.svg2png(bytestring=self._doc(keep, 0, 0, self.vw, self.vh).encode(), output_width=self.PX) full = np.array(Image.open(io.BytesIO(png)).convert('RGBA'))[:, :, 3] > 128 m = full[self.py0:self.py1, self.px0:self.px1] else: m = np.zeros_like(self.alpha); sl = (slice(int(y0 * h), int(y1 * h)), slice(int(x0 * w), int(x1 * w))); m[sl] = self.alpha[sl] ys, xs = np.where(m); ax, ay, bx, by = xs.min(), ys.min(), xs.max() + 1, ys.max() + 1 d = self._trace(m) ox, oy = (ax + self.px0) / self.k, (ay + self.py0) / self.k it = iter(re.findall(r'-?\d+\.\d+', d)); nums = ['%.2f' % (float(v) - (ox if i % 2 == 0 else oy)) for i, v in enumerate(it)] it2 = iter(nums); d = re.sub(r'-?\d+\.\d+', lambda _: next(it2), d) return d, (bx - ax) / self.k, (by - ay) / self.k def keyline(self, x, y, w, color='#FFFFFF', ring=0.035, close=0.045): """Outline that hugs only the OUTSIDE of the logo. Letter openings (the middle of an O, the gaps in an E) stay clear so the background shows through. ring/close are fractions of the logo height. Draw it UNDER original().""" H = self.alpha.shape[0]; pad = int(H * (ring + close) * 2) + 8 S = np.pad(self.alpha, pad); R = _disk(H * close) hull = ndi.binary_fill_holes(ndi.binary_closing(np.pad(S, R.shape[0]), structure=R)[R.shape[0]:-R.shape[0], R.shape[0]:-R.shape[0]]) K = ndi.binary_dilation(hull, structure=_disk(H * ring)) & ~(hull & ~ndi.binary_dilation(S, structure=_disk(2))) px0, py0 = self.px0, self.py0; self.px0, self.py0 = px0 - pad, py0 - pad d = self._trace(K, eps=1.0); self.px0, self.py0 = px0, py0 s, t = self._place(x, y, w) return '' % (t, d, color) def path_table(self, min_share=0.004): """Vector logos: every filled path big enough to matter, as {index, color, box} with box in FRACTIONS of the logo box (x0, y0, x1, y1) - the same units motif(region) uses. Boxes are approximate for curved shapes.""" if not self.vector: return [] bx, by, bw, bh = self.box; out = [] for i, m in enumerate(self.paths): xs, ys = self._nums(m.group(2)); f = [(min(xs) - bx) / bw, (min(ys) - by) / bh, (max(xs) - bx) / bw, (max(ys) - by) / bh] if (f[2] - f[0]) * (f[3] - f[1]) < min_share: continue c = m.group(1); n = re.findall(r'[\d.]+', c) if c.startswith('rgb') and len(n) >= 3: c = rgbhex([float(v) * 2.55 for v in n[:3]]) out.append({'index': i, 'color': c, 'box': [round(max(-0.05, min(1.05, v)), 3) for v in f]}) return out def debug_sheet(self, out_png, bg='#FF00FF', labels=True, width=1500): """The logo on magenta, so anything that should be see-through is obvious. Vector logos also get the index of each sizeable filled path printed at its centre (see path_table).""" x, y, lw, lh = self.box; frag = self.original(x, y, lw); pad = max(lw, lh) * 0.06 if labels and self.vector: fs = max(lw, lh) / 34 for r in self.path_table(0.012): cx = x + (r['box'][0] + r['box'][2]) / 2 * lw; cy = y + (r['box'][1] + r['box'][3]) / 2 * lh + fs * 0.35 frag += ('%d') % (cx, cy, fs, fs * 0.16, r['index']) cairosvg.svg2png(bytestring=self._doc(frag, x - pad, y - pad, lw + 2 * pad, lh + 2 * pad, bg).encode(), write_to=out_png, output_width=width) # ---- drawing helpers: every one returns an SVG fragment in product points ---- def rect(x, y, w, h, fill): return '' % (x, y, w, h, fill) def poly(pts, fill): return '' % (' '.join('%.2f,%.2f' % p for p in pts), fill) def star(cx, cy, r, fill, rot=-90): return poly([(cx + (r if i % 2 == 0 else r * .382) * math.cos(math.radians(rot + i * 36)), cy + (r if i % 2 == 0 else r * .382) * math.sin(math.radians(rot + i * 36))) for i in range(10)], fill) def shape(d, x, y, scale, fill): return '' % (x, y, scale, d, fill) def tile(W, H, motif, size, fill, gap=8, stagger=True): """Tone-on-tone repeat of a motif (d, w, h) across the whole plate. size = motif width in points.""" d, mw, mh = motif; s = size / mw; pw, ph = size + gap, mh * s + gap; g = ''; r = 0; y = -ph * .6 while y < H + ph: x = -pw + (pw / 2 if (stagger and r % 2) else 0) while x < W + pw: g += shape(d, x, y, s, fill); x += pw y += ph; r += 1 return g def star_tile(W, H, r, fill, dx=19, dy=13): g = ''; row = 0; y = 6 while y < H + dy: x = 2 + (0 if row % 2 else dx / 2) while x < W + dx: g += star(x, y, r, fill); x += dx y += dy; row += 1 return g def band(W, top, bottom, fill, trims=()): """Full-width band behind the logo. trims = [(colour, thickness, gap), ...] drawn outward above and below.""" g = rect(-5, top, W + 10, bottom - top, fill); o = 0 for c, t, gap in trims: o += gap; g += rect(-5, top - o - t, W + 10, t, c) + rect(-5, bottom + o, W + 10, t, c); o += t return g def racing_stripes(W, bottom, colors, x=0.70, widths=(6, 3, 6), step=11, slant=0.2679): """Slanted stripes dropping in from the top edge (top-right by default) and stopping above the logo.""" g = '' for i, (c, w) in enumerate(zip(colors, widths)): xx = W * x + i * step g += poly([(xx + slant * (bottom + 5), -5), (xx + w + slant * (bottom + 5), -5), (xx + w, bottom), (xx, bottom)], c) return g def corner_stripes(W, H, bands): """Diagonal stripes across the top-left and bottom-right corners. bands = [(colour, start, end), ...] in points.""" g = '' for c, a, b in bands: g += poly([(a, 0), (b, 0), (0, b), (0, a)], c) + poly([(W - a, H), (W - b, H), (W, H - b), (W, H - a)], c) return g def fit(p, logo, frac=0.80, cy=None, max_height=0.62): """Centre the logo: returns x, y, w, h. frac = logo width as a share of plate width. Tall or square logos are capped so the logo is never taller than max_height of the usable plate height (the DJ-10 loses its notch strip).""" W, H = p['W'], p['H']; usable = 135.8 if p.get('key') == 'dj10' else H w = min(W * frac, usable * max_height * logo.aspect); h = logo.height(w); c = H * (p['cy'] if cy is None else cy) return (W - w) / 2, c - h / 2, w, h def compose(product, background, layers): """Wraps fragments in a full artwork file clipped to the product dieline.""" p = PRODUCTS[product] return ('' '%s' ) % (p['W'], p['H'], p['W'], p['H'], p['die'], p['die'], background, ''.join(layers)) def save(svg, product, customer, concept, outdir): """Writes .svg/.pdf/.png and returns the PNG path (transparent outside the dieline).""" p = PRODUCTS[product]; base = os.path.join(outdir, '%s %s %s' % (customer, p['file'], concept)); os.makedirs(outdir, exist_ok=True) open(base + '.svg', 'w').write(svg) cairosvg.svg2pdf(bytestring=svg.encode(), write_to=base + '.pdf') cairosvg.svg2png(bytestring=svg.encode(), write_to=base + '.png', output_width=p['png'][0], output_height=p['png'][1]) return base + '.png' def product(key): p = dict(PRODUCTS[key]); p['key'] = key; return p def place_logo(logo, x, y, w, bg, mono_color=None, key_color='#FFFFFF'): """Puts the logo on a background colour the safe way. Single-colour logo -> recoloured (white on dark/saturated backgrounds, near-black on light ones) unless mono_color is given. Multi-colour logo -> original colours; gets an outside-only keyline when any main logo colour is too close to the background.""" if logo.mono: c = mono_color or ('#FFFFFF' if luminance(bg) < 0.60 else '#0B0F12') return logo.solid(x, y, w, c) weak = any(share > 0.12 and contrast(c, bg) < 1.8 for c, share in logo.colors) return (logo.keyline(x, y, w, key_color) if weak else '') + logo.original(x, y, w) NAMED = {'red': '#C8102E', 'blue': '#1F5FBF', 'navy': '#0A2A43', 'green': '#1E7A3C', 'yellow': '#FFD200', 'gold': '#C9A227', 'orange': '#F26A1B', 'purple': '#5B2D8E', 'pink': '#E84C8A', 'teal': '#1AA6A6', 'black': '#000000', 'white': '#FFFFFF', 'grey': '#6B7278', 'gray': '#6B7278', 'silver': '#A7ADB2', 'maroon': '#7A1F2B', 'brown': '#5A3B22'} def palette(primary=None, secondary=None): """Every colour the house set needs, worked out from the customer's primary (and optional secondary) colour. Handles the awkward cases: no colour at all, a very light primary (yellow, pale blue), and a black/near-black primary.""" ink = '#0B0F12'; p = {'ink': ink, 'neutral': primary is None} primary = primary or '#000000'; L = luminance(primary); light = L > 0.60; black = L < 0.02 p.update(primary=primary, light=light, black=black, accent=secondary or '#FFFFFF') p['on_primary'] = ink if light else '#FFFFFF' # single-colour logo colour on the primary background p['tint'] = mix(primary, '#FFFFFF', 0.45 if light else 0.38) if not black else '#8A9299' if light: # the deep shade of a light colour is mud: keep the bright colour as the field and use ink for weight p.update(deep=ink, c2_bg=primary, c2_pattern=mix(primary, '#000000', 0.13), c2_band=ink, c2_logo=primary, c2_trims=[(secondary or ink, 2.2, 2.0)], ghost=mix(ink, primary, 0.17)) elif black: # no real hue to work with: charcoal field, black band p.update(deep='#22272B', c2_bg='#22272B', c2_pattern='#2F363C', c2_band='#000000', c2_logo='#FFFFFF', c2_trims=[('#8A9299', 2, 0), (p['accent'], 2.2, 1.4)], ghost='#1C2229') else: deep = mix(primary, '#000000', 0.62) p.update(deep=deep, c2_bg=deep, c2_pattern=mix(deep, primary, 0.28), c2_band=primary, c2_logo='#FFFFFF', c2_trims=[(p['tint'], 2, 0), (p['accent'], 2.2, 1.4)], ghost=mix(ink, primary, 0.34)) return p def preview_motif(motif, out_png, fill='#FFFFFF', bg='#3A3F44'): """Renders a motif on its own so you can check it is a clean shape before using it.""" d, w, h = motif; pad = max(w, h) * 0.12 svg = ('' '') % (-pad, -pad, w + 2 * pad, h + 2 * pad, -pad, -pad, w + 2 * pad, h + 2 * pad, bg, d, fill) cairosvg.svg2png(bytestring=svg.encode(), write_to=out_png, output_width=600) def contact_sheet(pngs, out_png, bg='#8A8A8A', cell=560): """All finished artwork PNGs side by side on grey, so transparent areas and edges are visible. Look at this.""" ims = [Image.open(p).convert('RGBA') for p in pngs] for im in ims: im.thumbnail((cell, cell)) sheet = Image.new('RGBA', (len(ims) * (cell + 20) + 20, cell + 40), bg) for i, im in enumerate(ims): sheet.alpha_composite(im, (20 + i * (cell + 20), 20 + (cell - im.height) // 2)) sheet.save(out_png); return out_png def standard_three(logo, customer, outdir, primary=None, secondary=None, motif=None, names=('Classic', 'Pattern', 'Midnight'), stripes='auto', ghost='auto', products=('maggy', 'dj10')): """The house set: 1 plain brand-colour plate, 2 tone-on-tone pattern with a banded logo, 3 black 'Midnight' with a ghosted motif. stripes: 'racing' (slanted, sporty), 'corner' (formal), or 'auto'. ghost: 'frame' (giant motif centred behind the logo, best when the motif is an outline or a separate mark), 'corner' (giant motif cropped off the lower-left, best when the motif is the whole compact logo), or 'auto'. Returns {concept_name: {product: png_path}}. Treat the result as a first draft: look at it, then rebuild any concept by hand that needs it.""" c = palette(primary, secondary); compact = logo.aspect < 1.6; out = {} if ghost == 'auto': ghost = 'corner' if (motif is None and compact) else 'frame' motif = motif or logo.motif() if stripes == 'auto': stripes = 'racing' if logo.aspect > 2.5 else 'corner' for i, name in enumerate(names): concept = 'Concept %d %s' % (i + 1, name); out[concept] = {} for key in products: p = product(key); W, H = p['W'], p['H'] if i == 0: x, y, w, h = fit(p, logo, 0.80, max_height=0.66) svg = compose(key, c['primary'], [place_logo(logo, x, y, w, c['primary'], mono_color=c['on_primary'])]) elif i == 1: x, y, w, h = fit(p, logo, 0.70, max_height=0.42 if compact else 0.62); t, b = y - 8, y + h + 8 size = 21 if motif[1] >= motif[2] else 21 * motif[1] / motif[2] svg = compose(key, c['c2_bg'], [tile(W, H, motif, max(10, size), c['c2_pattern']), band(W, t, b, c['c2_band'], c['c2_trims']), place_logo(logo, x, y, w, c['c2_band'], mono_color=c['c2_logo'])]) else: x, y, w, h = fit(p, logo, 0.76, max_height=0.50 if compact else 0.62) if ghost == 'corner': # a compact logo hides a centred copy of itself: crop a big one off the lower-left instead ms = W * 1.35 / motif[1]; g = shape(motif[0], W * 0.30 - motif[1] * ms / 2, H * 0.62 - motif[2] * ms / 2, ms, c['ghost']) else: ms = min(W * 0.94 / motif[1], H * 1.25 / motif[2]); g = shape(motif[0], (W - motif[1] * ms) / 2, H * 0.05, ms, c['ghost']) s3 = [c['primary'] if not c['black'] else '#8A9299', '#FFFFFF', secondary or c['tint']] deco = (racing_stripes(W, y - 12, s3) if stripes == 'racing' and y - 12 > 24 else corner_stripes(W, H, [(s3[0], 20, 28), (s3[1], 31, 33.4), (s3[2], 36.4, 44.4)])) svg = compose(key, c['ink'], [g, deco, place_logo(logo, x, y, w, c['ink'])]) out[concept][key] = save(svg, key, customer, concept, outdir) return out # ---- Imgy mockups ---- IMGY = 'https://imgy.dfgadmin.com' TEMPLATE = 'maggy-and-dj-10-midnight-model-holding-forward' # one 1080x1920 page; warp layers keyed 'Maggy' and 'DJ-10' def imgy_mockups(items, output_dir, download_to, template=TEMPLATE, api_key=None): """items = [{'name': 'Acme Maggy and DJ-10 Midnight - Concept 1 Classic', 'Maggy': ref, 'DJ-10': ref}, ...] where each ref is something the Imgy SERVER can read: an absolute /opt/files/... path or an https:// URL of the artwork PNG. output_dir is relative to /opt/files/ (e.g. 'imgy/batches/acme-design-concepts'). Returns [(name, public_url, local_png)].""" key = api_key or os.environ['IMGY_API_KEY'] body = {'template': template, 'outputDir': output_dir, 'items': [{'name': it['name'], 'layers': {k: v for k, v in it.items() if k != 'name'}} for it in items]} req = urllib.request.Request(IMGY + '/api/external/batch', data=json.dumps(body).encode(), headers={'X-Api-Key': key, 'Content-Type': 'application/json'}, method='POST') res = json.loads(urllib.request.urlopen(req, timeout=300).read()); os.makedirs(download_to, exist_ok=True); out = [] for r in res.get('results', []): if r.get('status') != 'success': raise RuntimeError('Imgy failed for %s: %s' % (r.get('name'), r.get('error'))) p = urllib.parse.urlsplit(r['url']); url = p._replace(path=urllib.parse.quote(p.path)).geturl() # spaces -> %20 local = os.path.join(download_to, r['name'] + '.png'); urllib.request.urlretrieve(url, local); out.append((r['name'], url, local)) if len(out) != len(items): raise RuntimeError('Imgy returned %d of %d mockups' % (len(out), len(items))) return out # ---- the job folder: how the website hands a request to this toolkit ---- def clean_name(name): """Customer name made safe for file names: letters, digits, spaces, & and - only, single spaces, max 40 characters.""" return re.sub(r'\s+', ' ', re.sub(r"[^A-Za-z0-9 &\-]", '', name or '')).strip()[:40] or 'Customer' def load_job(job_dir=None): """Reads job.json from the job folder ($DFG_JOB_DIR). Returns a dict with: customer_name, logo_path, primary_color, secondary_color (validated '#RRGGBB' or None), style_note, dir (local job folder), server (the same folder as the DFG file server sees it, from $DFG_JOB_SERVER_PATH).""" d = (job_dir or os.environ['DFG_JOB_DIR']).rstrip('/'); j = json.load(open(os.path.join(d, 'job.json'))) for k in ('primary_color', 'secondary_color'): v = (j.get(k) or '').strip(); j[k] = v.upper() if re.fullmatch(r'#[0-9A-Fa-f]{6}', v) else None j.update(dir=d, server=os.environ.get('DFG_JOB_SERVER_PATH', d).rstrip('/'), logo_path=os.path.join(d, j['logo_file']), customer_name=clean_name(j.get('customer_name')), style_note=(j.get('style_note') or '').strip()) return j def job_mockups(job, files, template=TEMPLATE): """files = {concept_name: {'maggy': png_path, 'dj10': png_path}} with the PNGs saved inside the job folder. Renders one mockup per concept into /mockups/ and returns [(name, public_url, local_png)].""" if not job['server'].startswith('/opt/files/'): raise RuntimeError('mockups unavailable: the job folder is not on the DFG file server, so Imgy cannot read the artwork') ref = lambda p: job['server'] + '/' + os.path.relpath(os.path.abspath(p), os.path.abspath(job['dir'])) items = [{'name': '%s Maggy and DJ-10 Midnight - %s' % (job['customer_name'], c), 'Maggy': ref(f['maggy']), 'DJ-10': ref(f['dj10'])} for c, f in files.items()] return imgy_mockups(items, os.path.relpath(job['server'], '/opt/files') + '/mockups', os.path.join(job['dir'], 'mockups'), template)