This file provides context for Claude when working on this codebase.
ImaGUIck is a self-hosted Flask web application for single/batch image resizing, format conversion, and GIF/WEBP animation creation & editing, powered by ImageMagick. It is deployed via Docker (multi-arch: amd64 + arm64) and published on Docker Hub as tiritibambix/imaguick.
app.py # All Flask routes and image processing logic
cleanup.py # Scheduled file cleanup (48 h retention)
cleanup.sh # Manual cleanup helper script
Dockerfile # Multi-arch Docker build (ImageMagick compiled from source on both arches)
docker-compose.yml # Reference deployment
start.sh # Container entrypoint: starts cron + Gunicorn
requirements.txt # Python deps (Flask, Pillow, requests)
templates/
base.html # Design system: CSS variables, shared header/nav, SVG icon sprite, DM Sans + DM Mono fonts
index.html # Upload page — Resize / Create GIF·WEBP tabs, drag-and-drop, XHR upload, URL import
resize.html # Single-image resize options
resize_batch.html # Batch resize options
gif_create.html # Create an animated GIF/WEBP from a sequence of uploaded images
gif_edit.html # Edit an existing animated GIF/WEBP (resize/optimize/speed/reverse/rotate/loop/extract)
progress.html # Real-time SSE progress page for batch jobs and GIF creation
result.html # Success / error result page
_resize_options_styles.html # Shared <style> partial for the resize/GIF options-page layout
_resize_form_fields.html # Shared Jinja macros for repeated form field groups
static/media/ # Logo, banner, favicon
.github/workflows/
docker-build.yml # CI/CD: build + push multi-arch image to Docker Hub (every branch)
export-alerts.yml # Manual export of code-scanning alerts as an artifact
- Flask + Gunicorn (gthread worker, exactly 1 worker process × 16 threads — see
start.shcomment:jobs/upload_sessions/the ImageMagick semaphore are plain in-process Python state with no external store, so they are only consistent within a single worker process; more than one worker causes spurious "No files selected"/"Job not found" errors when a request lands on a worker that never saw an earlier request's state) - No database — job state held in-memory in the
jobsdict (protected byjobs_lock), purged afterJOBS_TTL_HOURSviapurge_old_jobs() - Async batch processing via
ThreadPoolExecutor(16 workers) +BoundedSemaphore(4)for ImageMagick concurrency - SSE streaming —
/job/<id>/statuspolls the in-memory job dict and streams JSON events; the payload'skindfield ('batch'or'gif_create') andoutput/zipfields tellprogress.htmlwhich single-file vs. ZIP download link to show - Upload sessions — batch/GIF-creation filenames stored server-side in
upload_sessionsdict (keyed by UUID) to avoid the URL length limit set by Gunicorn's--limit-request-line 8190(seestart.sh) - GIF/WEBP creation (
process_gif_create_job()) runs in two stages, which is what makes its progress measurable:prepare_gif_frame()normalises each frame in its own ImageMagick process (orientation + canvas), submitted to the shared executor under the same semaphore batch resize uses, thenbuild_gif_assemble_command()assembles the already-normalised frames in one final pass. Frames land inoutput/gifframes_<job_id>/, removed in afinallyregardless of outcome. Beyond progress, this keeps peak memory to one frame instead of the whole coalesced sequence, and leaves the assembly working on already-resized images - The GIF progress bar is a count, never an estimate. The frame stage owns
GIF_FRAME_PHASE_PERCENTof the bar and its value isround(80 * frames_done / total)— finished subprocesses, counted in Python, with nothing parsed. The assembly that follows is one indivisible invocation, so the bar goes indeterminate (indeterminateon the job and in the SSE payload) rather than inventing a figure. An earlier version assigned each ImageMagick operation a hand-picked slice of the bar; that is what produced a meaningless "14 of 14" frozen at the end of reading, and stage names scrolling past while the bar sat still. Do not reintroduce weighted bands.run_with_progress()still runs the assembly under-monitorviaPopen, but only to name the current operation (make_gif_assembly_reporter()→phase_detail) and to refresh liveness. Tags are mapped through_MONITOR_STAGE_NAMES, which matches what ImageMagick actually emits —-colorsreports asClassify/ImagethenAssign/Image(seeMagickCore/quantize.c), never "quantize" — and an unrecognised tag falls back to its own operation name instead of being dropped.- Some steps report nothing at all.
OptimizeLayerFrames(), which is what-layers optimizeruns, has no progress monitor, so silence there is expected. The job carriesstage_started_at/last_event_at, streamed asstage_seconds/idle_seconds; the page shows a per-stage timer plus a note pastMONITOR_IDLE_HINT_SECONDS. That timer is what distinguishes working from hung. run_with_progress()raises exactly whatsubprocess.run(check=True)would, keeping timeout and error handling unchanged, and strips progress lines out of the stderr used for user-facing messages- The assembly timeout is scaled to the frames, not the flat
SUBPROCESS_TIMEOUT_LONG.-layers optimizeplus-colorsover many full-resolution frames runs well past 300 s (23 frames at 2304×1536 did not finish in it, and full resolution is kept by choice — frames are only downscaled when a canvas size is requested).gif_assembly_timeout()reads each normalised frame's size from its header and budgetsGIF_ASSEMBLE_SECONDS_PER_MEGAPIXELper frame-megapixel, floored atSUBPROCESS_TIMEOUT_LONGso small jobs are unchanged and capped atGIF_ASSEMBLE_TIMEOUT_CEILINGso a runaway pass is still killed. The per-megapixel figure is an estimate; tune it against real container timings. The per-stage liveness timer onprogress.htmlis what makes a multi-minute assembly legible rather than looking hung
- GIF/WEBP editing (
/gif_edit/<filename>) is synchronous, mirroring/resize/<filename>'s pattern, since edits operate on one already-uploaded file and are bounded
- ImageMagick 7.1.2-31, built from source on both architectures. The version lives in a single
ARG IMAGEMAGICK_VERSIONin the Dockerfile and is asserted at build time (magick -version | grep -q), so a wrong tarball fails the build instead of shipping - JXL support via
libjxl-tools(cjxl/djxl) - RAW support via ExifTool (dimension extraction) + dcraw (decode to TIFF via
prepare_input_file()) - WebP support via
libwebp-dev+pkg-config(needed for animated WEBP muxing, not just single-frame WEBP — ImageMagick's./configuredetects delegate libraries like libwebp via pkg-config, so both packages are required on the amd64 source-build path) —webp_animation_supported()reads the WEBP row ofmagick -list formatonce at startup (logged) and is re-checked before any GIF/WEBP route acceptsWEBPas an output format - Vector output (SVG, EPS, PDF, AI) requires
potrace— checked at runtime before building the ImageMagick command - SVG input is rasterized by librsvg (
librsvg2-dev+--with-rsvg), not by Ghostscript. Without it ImageMagick silently falls back to its built-in MSVG renderer, which draws basic shapes but ignores gradients, filters, clip paths, CSS and font-rendered text — so a Figma/Illustrator export comes out mangled or blank. Like libwebp, this is a./configuredetection rather than a guarantee, so the Dockerfile assertsmagick -version | grep -q rsvgat build time: a detection miss fails the build instead of shipping a broken SVG path..svgis carried by its ownSVG_EXTENSIONSset rather thanDOCUMENT_INPUT_EXTENSIONS, because an SVG is not multi-page and must not get the[0]suffix - PDF/EPS input is rasterized by Ghostscript (apt package
ghostscript). Two consequences are wired intobuild_imagemagick_command(): the input gets a[0]suffix forDOCUMENT_INPUT_EXTENSIONS, because a multi-page PDF would otherwise make ImageMagick writeout-0.png,out-1.png… and never create the singleoutput_paththe caller expects; and the-densityguard scales the 72 dpi probe by the requested dpi before comparing againstMAX_DIMENSION, since a check against the probe alone cannot see a large page blowing past it once rasterized - Photo retouching —
-clahe(adaptive local contrast, levels mapped throughCLAHE_PARAMS),-modulate(brightness/saturation/hue, clamped byMODULATE_RANGESand omitted entirely when all three are neutral), and noise reduction (-despeckle,-enhance,-kuwahara).-kuwaharais superlinear in radius, so it is refused aboveKUWAHARA_MAX_PIXELSup front rather than being left to hit the subprocess timeout - GIF/WEBP animation — creation is split across
build_gif_frame_command()(one frame:-auto-orient, plus-resize/-extentwhen a canvas was requested) andbuild_gif_assemble_command()(-delay/-loopover the normalised frames, then palette and optimisation). There is deliberately no-coalesceon the creation path: these are still images with no frame-disposal history, and coalescing them forces a full RGBA materialisation of the sequence.build_gif_edit_command()handles resize/optimize/speed/reverse/rotate/loop on an existing animated file;build_gif_extract_command()pulls one frame, a range, or all frames via ImageMagick'sfile[N]/file[N-M]subimage syntax. RAW/JXL files are not supported as GIF-creation frames (they'd need the same dcraw/djxl pre-decodeprepare_input_file()does for the resize pipeline, which the GIF path doesn't call) — rejected explicitly rather than failing silently. - All subprocess calls use list form, never
shell=True - Argument order in
build_imagemagick_command()is load-bearing:-densityand-define jpeg:size=are read-time settings and must precede the input path;-auto-orientmust precede-strip, which would otherwise discard the EXIF orientation before it is applied; cropping precedes-resizeso the resize geometry frames the cropped image. Noise reduction runs before the tonal block because both-claheand-unsharpamplify whatever noise they are handed, and-modulateruns last of the tonal operations so the one manual setting is not re-equalised by an automatic one. Rotation and mirroring precede the crop, so a crop box is expressed against the image as it will be framed; effects and blur sit after the tonal block but before-unsharp, since sharpening a deliberate blur undoes it; and the watermark is applied after the resize, so its point size is relative to the delivered image, and after flattening, so it is never composited onto an alpha channel that is about to be removed. The full order is:[-density] [-define jpeg:size=] <input> -auto-orient [-strip] [-rotate/-flop/-flip] [crop] [denoise] [-auto-gamma] [-auto-level] [-clahe] [-modulate] [effect] [-blur] [-unsharp] [-resize | upscale] [flatten] [watermark] [-quality] <output>.jpeg:sizemakes libjpeg decode at a reduced scale, so it is emitted only for absolute bounding-box geometries — never alongside a percentage resize, a pixel crop box, or an enlargement, all of which are measured against the decoded image and would silently operate on the wrong size (jpeg_decode_hint()encodes the rule, andbuild_imagemagick_command()resolvescroppingandupscale_valuebefore the hint so both can suppress it) - Enlarging (
UPSCALE_FACTORS) is a-resize N%followed by-unsharp UPSCALE_UNSHARP. It is its own resize mode and wins over the presets and width/height rather than compounding with them, so the requested factor is the one that applies. Its-unsharpfollows the resize, which is the opposite of the sharpen option and deliberate: enlarging softens, so the sharpen has to come after. This is what tools advertising "AI upscaling" on a CPU generally do; naming it plainly promises nothing it cannot deliver - Cropping has two forms.
ALLOWED_CROP_RATIOSgives a centred box viacentered_crop_box()and emits-gravity center; an explicitcrop_w/h/x/ygoes throughexplicit_crop_box(), which bounds-checks the region against the source and emits no-gravity, because-gravity centerwould measure its offsets from the middle. An explicit box wins over a ratio - Reading
magick -list format— the columns are Format / Module / Mode / Description. Locate the mode by its shape viaparse_format_row(), never by index: reading position 1 returns Module.webp_animation_supported()relies on the+in the WEBP row's mode, which is what marks multi-image support; it does not use-list delegate, which reports external delegate programs rather than built-in coders like libwebp
- All templates extend
base.htmlvia Jinja2{% extends %};resize.html/resize_batch.html/gif_create.html/gif_edit.htmlalso share_resize_options_styles.html(CSS) and_resize_form_fields.html(Jinja macros) to avoid re-duplicating the options-page layout - The options pages have one control vocabulary, and a control's shape states what kind of answer it wants. Four primitives in
_resize_form_fields.htmlcover everything:segmented()for one of 2–5 exclusive choices,switch()for an independent on/off,number()for a magnitude with its unit attached, and a plain<select>for one of many. Everything sits on a single--control-h, so pills, inputs and selects line up. Before this there were eight idioms, 26.intensity-radioand 10.check-pilldoing overlapping jobs, and three inlinegrid-template-columnsoverrides. Do not add a fifth shape; if a decision does not fit one of the four, the decision is probably mis-framed - Options are grouped in the order
build_imagemagick_command()runs them, across three stages: Source (read-time settings), Actions (Size, Frame, Repair, Tone, Look, Watermark), Output (Encoding). The ordering is not a style choice — it is the pipeline, which is why "why is sharpening before the resize?" answers itself from the UI. Groups are<details>, so disclosure costs no JS and keeps keyboard behaviour native - A shut group states its own state, and only what deviates from the default.
options_script()builds each summary from the group's own controls with no per-group configuration to drift, and compares against the browser's owndefaultChecked/defaultValue/defaultSelected, so "Keep", "None" and a quality of 100 stay silent. This is what makes collapsing safe in a form with one submit button: nothing is ever both set and invisible. Controls inside ahiddenreveal are skipped, so a field belonging to an unselected mode never counts. When reading a value's unit, scope the lookup to the input's own.numwrapper — searching the parent picks up a sibling field's unit, which is how the watermark caption once rendered as "hellopt" data-when="field=value"anddata-when-filled="field"drive conditional reveals generically; there is no per-field JavaScript. A new conditional block needs only the attribute_resize_options_styles.htmlstill carries a small block of legacy layout classes (.form-grid,.section-block,.options-row,.submit-area, …) used only bygif_create.htmlandgif_edit.html, which have not been migrated to the stage/group vocabulary. It is marked as such; delete it when they move over. The resize pages reference none of them- Design system: dark theme, violet accent (
#8b5cf6), DM Sans + DM Mono (Google Fonts) - CSS variables defined in
base.html:root— do not redefine in child templates - Sticky header/nav (
base.html) with an inline SVG<symbol>icon sprite — add new icons there, reference via<svg class="icon"><use href="#icon-name"></use></svg> - No JS frameworks, no build step — vanilla JS only
- XHR upload with progress bar in
index.html; batch/GIF-creation progress via EventSource (SSE) inprogress.html - GIF creation preview (
gif_create.html) preloads every frame as a decodedImageand then plays them on a<canvas>from arequestAnimationFrameaccumulator. Both halves matter: frames are fetched from/preview_frame/<filename>?w=<px>as PIL-generated thumbnails (build_preview_thumbnail(), JPEG draft mode + an in-memory cache bounded byPREVIEW_CACHE_MAX_ENTRIES) rather than full-resolution originals, and playback is driven by elapsed time rather thansetInterval+<img src>swapping, which used to make frame duration depend on network and decode latency. Thumbnail width scales down as frame count grows, since every frame stays decoded in memory for the session index.htmlhas a Resize / Create GIF·WEBP tab switcher; the GIF tab enables drag-to-reorder on the selected-files list (order becomes frame order) and sets a hiddenintentfield read by/upload- The GIF tab covers both creation and editing, decided by what was uploaded: several images go to
gif_create_options, a single animated file (is_animated_file(), extension-gated onANIMATED_EXTENSIONSthen confirmed with PIL) goes togif_edit_options. Before this, the editor was only reachable from an inline link on the resize options page, so users looking for it on the GIF tab hit "at least 2 images" and never found it. That resize-page link is kept as a second way in.
These are non-negotiable — do not remove or weaken them:
- Serving a file the request named goes through
resolve_stored_file(name, folder), never through joining the request value onto a folder. It matches the basename against aos.scandir()listing and returns the matching entry's own absolute path, so nothing a client sends ever forms a filesystem path — traversal, absolute paths and symlink tricks simply fail to match. It returns an absolute path deliberately:send_file()resolves a relative path against the Flask app root rather than the working directory. secure_path()is for paths the application builds (output files, temp frames), not for request-named ones. It resolves both sides and tests containment againstbase + os.sep— a bare prefix test would also accept a sibling directory whose name merely starts with the folder's (uploads_elsewherenext touploads).safe_display_filename()applied to any filename from the URL or form before it is displayed, stored or logged. It preserves spaces,&and accents, and strips a leading-, which would otherwise be read as an option by a tool the name is handed to as an argv element.- Directories that get created, listed and
rmtreed are named from a UUID alone (the GIF frame-extraction scratch dir), with nothing derived from the request. A readable name is used for the resulting download instead. - Every path the app writes to is passed through
secure_path()first, including the two upload paths. The sanitiser already removes separators so the check cannot currently fail — that is the point: a regression in the sanitiser surfaces as a refused upload rather than a write outsideuploads/. - Mutually exclusive options are enforced where form input enters, not hoped for downstream. The four resize modes (pixels, percentage, the fit presets, enlarging) and the two crop modes are exclusive branches in the builder, but the form used to offer them as independent controls. The result was measurable: ticking both presets emitted
-resize 1920x1920> -resize 1080x1080>, a preset plus explicit dimensions resized twice, and a typed percentage was silently discarded when a preset was also set.resolve_size_mode()now reads a singlesize_mode(andcrop_modealongside it) andextract_processing_params()lets only that mode's fields through; the builder's resize section is a singleif/elifchain, so more than one-resizecannot be expressed. Both resolvers fall back to inferring the mode from whichever fields carry a value, in the builder's own precedence order, so a page left open across a deploy still resizes instead of silently doing nothing. Sharpening went the same way: the level is the switch, anduse_sharpenis derived, so there is no "enabled but no level" state left to resolve - An allowlisted string that goes on to form a command argument or a filename is passed through
canonical_value(), which returns the allowlist's own literal rather than the caller's string (output_format,density,extract_format, background colour). Checking membership withinand then forwarding the request's copy leaves that copy in play; this is theCOMMANDS[action]idiom CodeQL's own guidance recommends. A hex colour is rebuilt from its parsed components bycanonical_hex_color()for the same reason. Values that only ever serve as a dict key (sharpen_level,clahe_level,kuwahara_level,crop_ratio) or as the subject of an==test (denoise_mode) need no such treatment — what reaches the command is already one of our constants. - Output filenames derive from the resolved file's own name, never from the route parameter.
os.path.basename(filepath)afterresolve_stored_file()and the request string are equal by construction, but only the former is known to name a file we store, so it is the one that gets stripped of its UUID prefix to build the output name. - A numeric value that ends up in a command argument is parsed into a name of its own, never converted in place.
width = int(width)sitting insideif width:leaves two definitions ofwidthreaching the geometry string below it, and on the branch that skipped the conversion the unconverted request string is one of them — the guards make that branch unreachable, but nothing in the code says so.resize_dimension()andjpeg_decode_hint()both return fresh values for this reason;-qualityand-modulatebuild their arguments fromint()results the same way. This was the lastpy/command-line-injectionalert and the only one whose flow ran through arithmetic rather than through a path or an allowlist. - Free-form text is contained, not escaped. The watermark caption cannot be allowlisted, so
safe_watermark_text()keeps it safe structurally: it travels as exactly one argv element, verbatim, and no shell is involved — which is why spaces, quotes,;,&and accents must survive untouched. Escaping them is what breaks the moment the transport changes. Two things are still removed, because they are ImageMagick problems rather than shell ones: a leading@, which makes ImageMagick read the annotation from a file (-annotate @/etc/passwdwould render that file into the image — the same class of defect as the leading-thatsafe_display_filename()strips), and unprintable characters. Surrounding whitespace is trimmed before the@strip, or" @file"survives it and the later trim puts the@back in front. The property worth pinning if a test suite ever lands: for every-annotate,argv[i + 2]is the caption exactly ALLOWED_OUTPUT_FORMATS— explicit set; any format value not in it is rejected to''ALLOWED_SHARPEN_LEVELS—{'low', 'standard', 'high'}; unknown values fall back to'standard'POTRACE_FORMATS— vector formats checked forpotraceavailability before building the commandis_safe_url()— full DNS resolution + rejection of private/loopback/link-local/multicast IPs (SSRF prevention)MAX_DIMENSIONis enforced on both input (get_image_dimensions()) and output (build_imagemagick_command()rejects any requested width/height/percentage that would exceed it);GIF_MAX_OUTPUT_DIMENSION/GIF_MAX_FRAMES/GIF_MAX_TOTAL_PIXELSdo the equivalent for GIF/WEBP creation and editing, checked before any decode/processing workSUBPROCESS_TIMEOUT_SHORT/MEDIUM/LONG— everysubprocess.run()call has an explicit timeout- All subprocess calls use list arguments — never build shell strings with user data
Workflows live in .github/workflows/. Key conventions:
- Secrets:
DOCKER_USERNAMEandDOCKER_PASSWORD(notDOCKERHUB_*) - Actions are SHA-pinned where possible, with version comment (e.g.
# v7.0.1) - Each job has
permissions: contents: read; a globalpermissions: contents: readblock sits abovejobs: - Standard action versions in use:
actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1# v7.0.1docker/login-action@dbcb813823bdd20940b903addbd779551569679f# v4.6.0actions/cache/restore@v5/actions/cache/save@v5(SHA pin pending)docker/setup-qemu-action@v4(SHA pin pending)docker/setup-buildx-action@v4(SHA pin pending)docker/build-push-action@v7(SHA pin pending)peter-evans/dockerhub-description@v5(SHA pin pending)
One workflow covers every branch. docker-build.yml triggers on push to '**' plus workflow_dispatch; there is deliberately no pull_request trigger, because a fork PR cannot read the Docker Hub secrets and would only ever fail at the push step. There is no paths-ignore either: the point is a published image for every commit.
- The
checkjob cacheslast_commit.txtper branch (actions/cache) and setsskip=truewhen the current SHA was already built, so re-running a workflow does not rebuild and re-push the same commit. Aworkflow_dispatchalways overrides the skip. - It also composes the whole tag list, as a multi-line step output consumed by
build-and-pushasneeds.check.outputs.tags. Keeping tag composition in one shell step rather than in thetags:block is what makes the main-onlylatesta two-line conditional instead of a YAML expression per tag. update-dockerhub-descriptionis gated ongithub.ref_name == 'main'. Without that gate, pushing any branch would rewrite the public Docker Hub description from that branch's README.audit(pip-audit) gates the build, so a known CVE in Flask/Pillow/requests stops the image from being published on any branch.- Both architectures build ImageMagick from source and arm64 runs under QEMU, so this workflow is slow by nature.
cache-from/to: type=ghais what keeps a second push to the same branch from paying the full compile again; expect the first build on a new branch to be long.
- Account:
tiritibambix - Image:
tiritibambix/imaguick - Tags: every branch publishes
<branch>-latest,<branch>-<short-sha>and<branch>-<YYYYMMDD>;mainadditionally keeps the barelatest, becausedocker-compose.ymland the README both pull it by name. Branch names are sanitised to the Docker tag charset (feat/café#2→feat-caf-2), and a name starting with a separator is prefixed, since a tag may not
- Accepting PDF/EPS uploads hands arbitrary files to Ghostscript, which has a long history of vulnerabilities allowing code execution via crafted PostScript. Two things blunt it: Ghostscript ≥ 9.50 enables
-dSAFERby default and ImageMagick invokes it that way. The residual risk is accepted deliberately, consistent with the local/trusted-network model the README already documents. Note that an ImageMagick built from source ships a permissivepolicy.xml, unlike Debian's package which disables the PS/PDF coders for exactly this reason — so nothing blocks these formats at the policy layer here.DOCUMENT_INPUT_EXTENSIONSis kept separate fromIMAGE_EXTENSIONSto keep that distinction visible: those files are interpreted, not merely decoded. - Accepting SVG uploads hands arbitrary XML to a renderer, which is a smaller version of the same bargain as PDF/EPS above: an SVG can carry external entity declarations and can reference remote or local resources (
<image href="file:///…">or anhttp://URL), so a crafted file is a potential XXE and server-side request vector. librsvg does not resolve external entities and does not fetch remote resources by default, which is most of the defence; the residual risk is accepted on the same local/trusted-network basis, and it is a reason not to drop back to the MSVG fallback, whose hardening is far less clear..svgis deliberately absent fromIMAGE_EXTENSIONSfor the same reasonDOCUMENT_INPUT_EXTENSIONSis: those files are interpreted, not merely decoded. - AVIF and HEIC are not supported by this build —
libheif/libaomare not installed, so the delegates are not compiled in. They stay out of the hardcoded fallback list inget_available_formats(), which is the only path by which an unsupported format could reach the UI (the normal path filters againstmagick -list format). They remain inALLOWED_OUTPUT_FORMATSharmlessly, since that set only rejects, never offers. - The text watermark needs a font package. The Dockerfile installs
fonts-dejavu-core, andbuild_watermark_args()always emits-fontfrom theWATERMARK_FONTSallowlist. Relying on ImageMagick's compiled-in default instead fails at runtime with "unable to read font" on an image that ships no fonts, which is the trap to avoid: the failure only appears when a caption is actually requested, long after the build passed. Adding a family toWATERMARK_FONTSwithout installing it reintroduces exactly that. - potrace must be installed for SVG/EPS/PDF/AI output. The Dockerfile installs it via
apt-get install potrace. Without it, ImageMagick raises a delegate error. - Never pin the base image to
$BUILDPLATFORM, and never passTARGETARCHas an explicitbuild-argsfrom CI. Both mistakes shipped together: the workflows passedTARGETARCH=${{ matrix.arch }}while defining no matrix, so the value was empty and the Dockerfile's arm64 branch never ran, whileFROM --platform=$BUILDPLATFORMbaked the runner's architecture into every image — meaning the published arm64 manifest entry carried amd64 binaries. Both architectures now build ImageMagick from source; Debian'simagemagickpackage is ImageMagick 6 and ships nomagickbinary, so an apt path was never viable for this app anyway. - Animated WEBP support depends on
libwebpmux/libwebpdemuxbeing linked into ImageMagick at build time — the Dockerfile installslibwebp-devfor this, but it's a build-time detection (via./configure), not guaranteed. Always check viawebp_animation_supported()/docker logsrather than assuming; the UI hides/disables the WEBP option server-side when unsupported. - Gunicorn MUST run with exactly one worker process (
--workers 1instart.sh) —jobs,upload_sessions,_processing_semaphore,executor, and_webp_anim_supported_cacheare all plain in-process Python objects with no shared/external store. Multiple worker processes each get their own independent copy, so a request that lands on a different worker than an earlier one in the same flow (upload → options page → submit) won't see that earlier worker's state — this previously caused real, reproducible "No files selected" (upload_sessions) and would equally cause "Job not found" (jobs) failures under the--workers 4config that shipped before this was diagnosed. Scale via--threads(in-process, shares memory) instead of--workers. - In-memory job state is lost on container restart — any in-flight batch jobs or GIF creation jobs are abandoned. This is acceptable for the current use case (local/trusted network).
upload_sessionsdict grows indefinitely — sessions are never explicitly purged. Not a problem at typical self-hosted scale. (Unlikejobs, which is purged — seepurge_old_jobs()/JOBS_TTL_HOURS.)cleanup.pyremoves files fromuploads/andoutput/older than 48 h. Batch output subdirectories (e.g.output/batch_20240101_120000/) and GIF frame-extraction temp directories are also cleaned (the latter are additionally removed immediately after zipping in/gif_edit, socleanup.pyis only a backstop for interrupted requests).- Gunicorn's
--limit-request-line 8190URL limit — batch and GIF-creation filenames must go through the server-sideupload_sessionsmechanism, not the query string. - GIF creation doesn't call
prepare_input_file()— RAW/JXL frames are explicitly rejected (gif_create_options/gif_create) rather than silently mishandled, since ImageMagick would receive the raw/undecoded file directly. - The
flask_error/flash_errorfunction logs and rendersresult.htmlwithsuccess=False. Use it consistently for error returns instead of ad-hocrender_templatecalls. - A builder that refuses must say why, through
refuse(). The command builders have ~27 refusal paths and their callers only ever seeNone, so every one of them used to surface as "Could not build ImageMagick command" while the real reason sat in the log.refuse(message)logs it, records it on athreading.local(batch runs 16 workers against these builders at once, so a module-level variable would let one worker read a sibling's reason) and returnsNone; callers then raiseCommandRefused(last_refusal_reason())or flash it.classify_processing_error()returns aCommandRefusedmessage verbatim, which is safe precisely because we author these strings — never pass tool output through it, and never interpolate a path into a refusal message. When adding a refusal path, userefuse(); a barereturn Noneis only correct as a pass-through of an inner builder that already recorded a reason. - Enlarging is bounded by
MAX_DIMENSION, which rules it out for most modern photos (a 5142px source cannot be doubled under a 10000px cap). That is the feature working as intended, not a defect: enlarging is for small images. The failure must not be discovered after submitting, soupscale_field()receives the source dimensions on the single-image page, shows the size each factor would produce, and disables the ones that would be refused. The batch page cannot do this (sizes differ per image), so it says so and relies on the per-image refusal message instead.
- Python 3.11+ required. The floor is set by
Pillow>=13.0.0inrequirements.txt, not by any language feature the app uses: every Pillow below 13 carries unpatched decoder CVEs, and Pillow 13 requires Python >= 3.11. The Dockerfile's base image and theauditjob's container must move together — pip resolves a requirement to the newest version supporting the running Python, so a mismatched audit checks versions the image never installs - No test suite currently exists
- Commit messages in English
- Commit titles follow conventional commits format:
type(scope): description - When modifying templates: always extend
base.html, never duplicate:rootorbodystyles - When modifying
app.py: run through the security checklist above before committing