26 Commits
Author SHA1 Message Date
Djeex 99b3024671 Update dependency tifffile to v2026.11.12
renovate/stability-days Updates have met minimum release age requirement
CI / build-and-scan (pull_request) Successful in 4m5s
2026-11-21 19:09:41 +00:00
instameex-ci 2594dacdcf Bump build version to 1.1.4 [skip ci] 2026-11-21 19:06:49 +00:00
Djeex 554de3f041 Merge pull request 'Update dependency numpy to v2.5.4' (#7) from renovate/numpy-2.x into main
CI / build-and-scan (push) Successful in 1m42s
2026-11-21 20:05:32 +01:00
instameex-ci fc16ed0e89 Bump build version to 1.1.3 [skip ci] 2026-11-21 19:03:37 +00:00
Djeex d9b03108de Merge branch 'main' into renovate/numpy-2.x
CI / build-and-scan (pull_request) Successful in 1m31s
2026-11-21 20:02:46 +01:00
Djeex f8dd834419 Merge pull request 'Upgrade Python to 3.14.10' (#10) from python-upgrade into main
CI / build-and-scan (push) Successful in 1m18s
Reviewed-on: #10
2026-11-21 20:02:35 +01:00
Djeex b494404088 Merge remote-tracking branch 'origin/main' into python-upgrade
CI / build-and-scan (pull_request) Successful in 2m7s
2026-11-21 18:52:32 +00:00
Djeex 6fa5b0e333 Upgrade Python to 3.14.10 2026-11-21 18:49:44 +00:00
Djeex 548ccc0dbe Merge pull request 'Do not pin digests for CI tool images' (#9) from fix-pin-regex into main
CI / build-and-scan (push) Successful in 2m39s
Reviewed-on: #9
2026-11-21 19:45:57 +01:00
Djeex a4e3e36249 Do not pin digests for CI tool images
CI / build-and-scan (pull_request) Successful in 1m48s
2026-11-21 18:26:51 +00:00
Djeex 82792375a2 Update dependency numpy to v2.5.4
renovate/stability-days Updates have met minimum release age requirement
CI / build-and-scan (pull_request) Failing after 10s
2026-11-21 18:18:33 +00:00
instameex-ci 6d810b76cf Bump build version to 1.1.2 [skip ci] 2026-11-21 17:53:41 +00:00
Djeex 7378de15ec Merge pull request 'Pin base images and add end-to-end tests' (#6) from ci-cd into main
CI / build-and-scan (push) Successful in 1m50s
Reviewed-on: #6
2026-11-21 18:46:29 +01:00
Djeex 93d448140e Merge remote-tracking branch 'origin/main' into ci-cd
CI / build-and-scan (pull_request) Successful in 1m23s
# Conflicts:
#	docker/Dockerfile
2026-11-21 17:28:45 +00:00
Djeex 8e4378539d Merge pull request 'Update aquasec/trivy Docker tag to v0.76.2' (#4) from renovate/aquasec-trivy-0.x into main
CI / build-and-scan (push) Successful in 33s
Reviewed-on: #4
2026-11-21 18:28:05 +01:00
Djeex 5233594685 Merge pull request 'Update alpine Docker tag to v3.24' (#3) from renovate/alpine-3.x into main
CI / build-and-scan (push) Failing after 39s
Reviewed-on: #3
2026-11-21 18:27:51 +01:00
Djeex 657dfdef6b Pin base images and add end-to-end tests
CI / build-and-scan (pull_request) Successful in 4m54s
2026-11-21 17:25:48 +00:00
Djeex 9300430550 Update aquasec/trivy Docker tag to v0.76.2
CI / build-and-scan (pull_request) Successful in 48s
2026-11-21 16:58:51 +00:00
Djeex 8c4afd98d9 Update alpine Docker tag to v3.24
CI / build-and-scan (pull_request) Successful in 1m59s
2026-11-21 16:58:48 +00:00
instameex-ci 111571f4c1 Bump build version to 1.1.1 [skip ci] 2026-11-21 16:39:33 +00:00
Djeex 529eef3e7e Merge pull request 'Add CI/CD pipeline, Renovate config and unit tests' (#2) from ci-cd into main
CI / build-and-scan (push) Successful in 59s
Reviewed-on: #2
2026-11-21 17:38:49 +01:00
Djeex 527e8129ba Bump Pillow to 13.0.0 to fix CVEs
CI / build-and-scan (pull_request) Successful in 1m6s
2026-11-21 16:28:30 +00:00
Djeex 4e7b51c334 Add CI/CD pipeline, Renovate config and unit tests
CI / build-and-scan (pull_request) Failing after 2m9s
2026-11-21 16:15:14 +00:00
Djeex 03d6870c64 Add a "Why?" section with workflow diagram, and a README table of contents 2026-08-23 10:13:01 +02:00
Djeex dd50871cf6 Merge branch 'dev' 2026-08-03 16:07:21 +02:00
Djeex bcc609179e Added instameex-web url 2026-08-03 15:59:39 +02:00
16 changed files with 1043 additions and 9 deletions

No files matched your search

+272
View File
@@ -0,0 +1,272 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: "0 6 * * 1"
jobs:
build-and-scan:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- name: Scan for secrets
run: |
# docker cp, not a build COPY: a repo's own .dockerignore would otherwise
# silently give an empty, falsely-clean scan.
CID=$(docker create zricethezav/gitleaks:v8.30.1 detect --source=/repo --no-banner -v)
docker cp . "$CID:/repo"
docker start -a "$CID"
STATUS=$?
docker rm "$CID" > /dev/null
exit $STATUS
- name: Lint Dockerfile with hadolint
run: docker run --rm -i hadolint/hadolint:v2.15.1-alpine hadolint --failure-threshold error - < docker/Dockerfile
- name: Build Docker image
run: |
docker build -f docker/Dockerfile -t instameex:ci . 2>&1 | tee build.log
if grep -q "Building wheel for" build.log; then
echo "::warning::A dependency was built from source — check Python/Alpine compatibility"
fi
- name: Smoke test (syntax + binaries)
run: |
docker run --rm --entrypoint python instameex:ci -m compileall -q /app/main.py /app/src
docker run --rm --entrypoint sh instameex:ci -c "test -x /usr/local/bin/ultrahdr_app && exiftool -ver"
- name: Run unit tests
run: |
docker build -f docker/Dockerfile --target test -t instameex:test .
docker run --rm instameex:test pytest -v --cov=src --cov-report=term-missing --cov-fail-under=75
- name: Lint with ruff
run: docker build -f docker/Dockerfile --target lint -t instameex:lint .
- name: Check deprecation warnings
run: |
docker run --rm --entrypoint python instameex:ci -W error::DeprecationWarning -c "import main" 2>&1 | tee deprecation.log || true
if grep -qi "deprecat" deprecation.log; then
echo "::warning::Deprecation warning detected, check logs"
fi
- name: Scan with Trivy (critical - blocking)
id: trivy_critical
continue-on-error: true
run: |
docker run --rm \
-e DOCKER_HOST=tcp://dockerhost:2375 \
--add-host=dockerhost:host-gateway \
aquasec/trivy:0.76.2 image --exit-code 1 --severity CRITICAL instameex:ci
- name: Handle CRITICAL findings
if: steps.trivy_critical.outcome == 'failure'
run: |
if [ "${{ github.event_name }}" != "schedule" ]; then
echo "::error::CRITICAL vulnerabilities found, failing the build."
exit 1
fi
echo "Scheduled scan found CRITICAL vulnerabilities — attempting an automatic apk upgrade + rescan."
# Add an apk upgrade right after the base stage's FROM
sed -i '/^FROM python:.* AS base$/a RUN apk upgrade --no-cache' docker/Dockerfile
docker build -f docker/Dockerfile -t instameex:remediated .
if docker run --rm \
-e DOCKER_HOST=tcp://dockerhost:2375 \
--add-host=dockerhost:host-gateway \
aquasec/trivy:0.76.2 image --exit-code 1 --severity CRITICAL instameex:remediated; then
echo "apk upgrade clears the CRITICAL finding(s) — opening a PR for review."
BRANCH="auto/cve-fix-$(date +%Y%m%d)-$(echo "${{ github.sha }}" | cut -c1-7)"
git config user.name "instameex-ci"
git config user.email "[email protected]"
git checkout -b "$BRANCH"
git add docker/Dockerfile
git commit -m "Auto-remediate CRITICAL CVE via apk upgrade"
git config --unset-all http.https://git.djeex.fr/.extraheader || true
git push "https://Djeex:${{ secrets.CI_PUSH_TOKEN }}@git.djeex.fr/Djeex/instameex.git" "HEAD:$BRANCH"
PR_JSON=$(curl -s -X POST \
-H "Authorization: token ${{ secrets.CI_PUSH_TOKEN }}" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg head "$BRANCH" '{title: "🔒 Auto: remediate CRITICAL CVE via apk upgrade", head: $head, base: "main", body: "Opened automatically by the scheduled CVE scan. An `apk upgrade --no-cache` cleared the CRITICAL Trivy finding(s) in a rebuild — review the diff and merge to publish the fix."}')" \
"https://git.djeex.fr/api/v1/repos/Djeex/instameex/pulls")
echo "PR API response: $(echo "$PR_JSON" | jq -r '.html_url // .message // "unknown"')"
else
echo "::error::apk upgrade does not clear the CRITICAL finding(s) — no automatic fix available, needs manual review."
exit 1
fi
- name: Scan with Trivy (high - informative)
run: |
docker run --rm \
-e DOCKER_HOST=tcp://dockerhost:2375 \
--add-host=dockerhost:host-gateway \
aquasec/trivy:0.76.2 image --exit-code 0 --severity HIGH instameex:ci
- name: Publish tagged image
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
run: |
BEFORE="${{ github.event.before }}"
if [ -n "$BEFORE" ] && [ "$BEFORE" != "0000000000000000000000000000000000000000" ] && git cat-file -e "$BEFORE" 2>/dev/null; then
BASE_REF="$BEFORE"
else
BASE_REF="HEAD~1"
fi
CHANGED=$(git diff --name-only "$BASE_REF" "${{ github.sha }}")
echo "Changed files:"
echo "$CHANGED"
if ! echo "$CHANGED" | grep -qE '^(VERSION|main\.py|requirements\.txt)$|^(docker|src)/'; then
echo "No container-relevant file changed, skipping publish."
exit 0
fi
if echo "$CHANGED" | grep -qE '^VERSION$'; then
echo "VERSION was manually edited in this push, using it as-is."
else
echo "VERSION untouched but container files changed, auto-bumping the build number (Z)."
OLD_VERSION=$(tr -d '[:space:]' < VERSION)
IFS='.' read -r MAJOR MINOR PATCH <<< "$OLD_VERSION"
NEW_VERSION="${MAJOR}.${MINOR}.$((PATCH + 1))"
echo "$NEW_VERSION" > VERSION
git config user.name "instameex-ci"
git config user.email "[email protected]"
git add VERSION
git commit -m "Bump build version to $NEW_VERSION [skip ci]"
git config --unset-all http.https://git.djeex.fr/.extraheader || true
git push "https://Djeex:${{ secrets.CI_PUSH_TOKEN }}@git.djeex.fr/Djeex/instameex.git" HEAD:main
fi
VERSION=$(tr -d '[:space:]' < VERSION)
IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION"
MINOR_TAG="${MAJOR}.${MINOR}"
IMAGE=git.djeex.fr/djeex/instameex
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.djeex.fr -u Djeex --password-stdin
# Retag the already-built, already-scanned image — never rebuild for publish,
# so what ships is byte-for-byte what Trivy just scanned.
docker tag instameex:ci "$IMAGE:latest"
docker tag instameex:ci "$IMAGE:$MINOR_TAG"
docker tag instameex:ci "$IMAGE:$VERSION"
docker push "$IMAGE:latest"
docker push "$IMAGE:$MINOR_TAG"
docker push "$IMAGE:$VERSION"
GHCR_IMAGE=ghcr.io/djeex/instameex
echo "${{ secrets.GH_TOKEN }}" | docker login ghcr.io -u Djeex --password-stdin
docker tag instameex:ci "$GHCR_IMAGE:latest"
docker tag instameex:ci "$GHCR_IMAGE:$MINOR_TAG"
docker tag instameex:ci "$GHCR_IMAGE:$VERSION"
docker push "$GHCR_IMAGE:latest"
docker push "$GHCR_IMAGE:$MINOR_TAG"
docker push "$GHCR_IMAGE:$VERSION"
TRIGGER_MSG=$(git log -1 --format=%s "${{ github.sha }}")
PR_NUM=$(echo "$TRIGGER_MSG" | grep -oE '#[0-9]+' | head -1 | tr -d '#' || true)
CATEGORY="🔧 Maintenance"
CHANGE_TITLE="$TRIGGER_MSG"
if [ -n "$PR_NUM" ]; then
PR_JSON=$(curl -s -H "Authorization: token ${{ secrets.CI_PUSH_TOKEN }}" \
"https://git.djeex.fr/api/v1/repos/Djeex/instameex/pulls/$PR_NUM")
PR_TITLE=$(echo "$PR_JSON" | jq -r '.title // empty' 2>/dev/null || true)
LABELS=$(echo "$PR_JSON" | jq -r '.labels[]?.name' 2>/dev/null || true)
if [ -n "$PR_TITLE" ]; then
CHANGE_TITLE="$PR_TITLE"
fi
if echo "$LABELS" | grep -qx 'bug'; then
CATEGORY="⚠️ Hotfix"
elif echo "$LABELS" | grep -qx 'major'; then
CATEGORY="💥 Breaking change"
elif echo "$LABELS" | grep -qx 'minor'; then
CATEGORY="✨ Update"
fi
fi
REPO_URL="https://git.djeex.fr/Djeex/instameex"
COMMIT_LIST=$(git log --no-merges --format="- %s ([%h](${REPO_URL}/commit/%H))" "$BASE_REF".."${{ github.sha }}")
SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
SOURCE_LINE="[${SHORT_SHA}](${REPO_URL}/commit/${{ github.sha }})"
if [ -n "$PR_NUM" ]; then
SOURCE_LINE="[#${PR_NUM}](${REPO_URL}/pulls/${PR_NUM}) · ${SOURCE_LINE}"
fi
NOTE_BANNER=$(printf '> [!NOTE]\n>⚠️ _This is an heavily vibe-coded proof of concept — do not expose it to the internet — use it at your own risk._')
BODY=$(cat <<EOF
${NOTE_BANNER}
## Changelog
### ${CATEGORY}
${CHANGE_TITLE}
**Source:** ${SOURCE_LINE}
**Image:** \`${IMAGE}:${VERSION}\`
**Commits:**
${COMMIT_LIST}
EOF
)
JSON_PAYLOAD=$(jq -n \
--arg tag "v$VERSION" \
--arg name "v$VERSION" \
--arg body "$BODY" \
'{tag_name: $tag, name: $name, target_commitish: "main", body: $body}')
curl -s -o /dev/null -w "Release API response: %{http_code}\n" -X POST \
-H "Authorization: token ${{ secrets.CI_PUSH_TOKEN }}" \
-H "Content-Type: application/json" \
-d "$JSON_PAYLOAD" \
"https://git.djeex.fr/api/v1/repos/Djeex/instameex/releases"
MIRROR_NOTICE="_This github repo is a mirror of https://git.djeex.fr/Djeex/instameex. You'll find full package, PR, history and release note there._"
GH_BODY=$(printf '%s\n\n%s' "$MIRROR_NOTICE" "$BODY")
GH_JSON_PAYLOAD=$(jq -n \
--arg tag "v$VERSION" \
--arg name "v$VERSION" \
--arg body "$GH_BODY" \
--arg sha "${{ github.sha }}" \
'{tag_name: $tag, name: $name, target_commitish: $sha, body: $body}')
GH_STATUS=0
for i in 1 2 3 4 5; do
GH_STATUS=$(curl -s -o /tmp/gh_release.json -w "%{http_code}" -X POST \
-H "Authorization: Bearer ${{ secrets.GH_TOKEN }}" \
-H "Accept: application/vnd.github+json" \
-H "Content-Type: application/json" \
-d "$GH_JSON_PAYLOAD" \
"https://api.github.com/repos/Djeex/instameex/releases")
if [ "$GH_STATUS" = "201" ]; then
break
fi
echo "GitHub Release attempt $i failed (HTTP $GH_STATUS) — mirror may not have synced this commit yet, retrying in 15s..."
sleep 15
done
echo "GitHub Release API response: $GH_STATUS"
if [ "$GH_STATUS" != "201" ]; then
cat /tmp/gh_release.json 2>/dev/null || true
fi
+23
View File
@@ -21,12 +21,35 @@
A small web front end for assembling Instagram-compatible HDR JPEGs (gain A small web front end for assembling Instagram-compatible HDR JPEGs (gain
map) from an SDR export and an HDR export out of Lightroom or Camera Raw. map) from an SDR export and an HDR export out of Lightroom or Camera Raw.
Check the online version : [Instameex-web](https://instameex.djeex.fr/)
The gain-map assembly logic ([src/script/app/assembler.py](src/script/app/assembler.py)) is The gain-map assembly logic ([src/script/app/assembler.py](src/script/app/assembler.py)) is
adapted from [kostis-kounadis/instagram-hdr-assembler](https://github.com/kostis-kounadis/instagram-hdr-assembler), adapted from [kostis-kounadis/instagram-hdr-assembler](https://github.com/kostis-kounadis/instagram-hdr-assembler),
itself based on the reverse-engineering work of itself based on the reverse-engineering work of
[karachungen/instagram-hdr-converter](https://github.com/karachungen/instagram-hdr-converter). [karachungen/instagram-hdr-converter](https://github.com/karachungen/instagram-hdr-converter).
Original MIT license kept in [LICENSE](LICENSE). Original MIT license kept in [LICENSE](LICENSE).
## Contents
- [Why?](#why)
- [How it works](#how-it-works)
- [Running locally, without Docker](#running-locally-without-docker)
- [Running with Docker](#running-with-docker)
- [Running this on the open internet](#running-this-on-the-open-internet)
## Why ?
Nothing is more frustrating than Instagram's HDR handling. It compresses and destroys gain maps, and the slightest change in aspect ratio or size simply strips HDR out entirely. As for Lightroom, its "SDR preview" system is frankly unacceptable, it makes it impossible to get consistent results. Until now, posting on Instagram meant choosing between decent SDR with broken HDR, or the other way around.
Why not simply edit your SDR file to perfection on one side, your HDR file on the other, and then recalculate a gain map from those two perfect files?
A few pioneers have already gone down that road, notably with an [Adobe Lightroom Classic](https://github.com/karachungen/lightroom-plugin-export-hdr) plugin. Judge me if you want, but I only use Lightroom CC, which does not support plugins.
I drew inspiration from a [fork of the original project](https://github.com/kostis-kounadis/instagram-hdr-assembler), the one that eventually became the LrC plugin, to build a frontend that can be easily deployed with Docker. Let's be honest: it was also a great excuse to put my Claude Code subscription to the test. And I have to say, watching it spin up its own environments, run end-to-end tests, self-correct its code, and write detailed summaries is genuinely impressive. I still reviewed everything myself, don't worry. I also learned a great deal about HDR fundamentals, gain maps, HLG/PQ tone curves, color spaces, and more.
In short, here is what my workflow now looks like for posting on Instagram:
![Instameex workflow](illustration/instameex-workflow.svg)
## How it works ## How it works
1. Upload an SDR file (`.jpg`/`.jpeg`) and an HDR file: either a gain-map 1. Upload an SDR file (`.jpg`/`.jpeg`) and an HDR file: either a gain-map
+1 -1
View File
@@ -1 +1 @@
1.1.0 1.1.4
+26 -5
View File
@@ -1,23 +1,28 @@
# syntax=docker/dockerfile:1 # syntax=docker/dockerfile:1
# ---- Stage 1: compile libultrahdr (ultrahdr_app) -------------------------- # ---- Stage 1: compile libultrahdr (ultrahdr_app) --------------------------
FROM alpine:3.21 AS uhdr-build FROM alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf AS uhdr-build
RUN apk add --no-cache \ RUN apk add --no-cache \
git cmake make g++ nasm pkgconf libjpeg-turbo-dev git cmake make g++ nasm pkgconf libjpeg-turbo-dev
WORKDIR /build WORKDIR /build
# Pin to a commit once you've confirmed it works for you — HEAD can move. # Pinned to an exact commit (v2.0.2 + fixes) for reproducible, auditable builds.
RUN git clone --depth 1 https://github.com/google/libultrahdr.git ARG UHDR_COMMIT=c6fd15cdb2d05d3aaed84b817e4c4a274a4ce600
RUN git init libultrahdr \
&& git -C libultrahdr fetch --depth 1 https://github.com/google/libultrahdr.git "$UHDR_COMMIT" \
&& git -C libultrahdr checkout --detach FETCH_HEAD
RUN cmake -G "Unix Makefiles" -DUHDR_WRITE_XMP=ON \ RUN cmake -G "Unix Makefiles" -DUHDR_WRITE_XMP=ON \
-S libultrahdr -B libultrahdr/build \ -S libultrahdr -B libultrahdr/build \
&& cmake --build libultrahdr/build -j"$(nproc)" && cmake --build libultrahdr/build -j"$(nproc)"
# ---- Stage 2: runtime ------------------------------------------------------- # ---- Stage 2: runtime -------------------------------------------------------
FROM python:3.11-alpine FROM python:3.14.10-alpine@sha256:5862d971d1f0ae26b258cefa4e893556b1d3aba81bd2ff30888704ad378bab67 AS base
RUN apk add --no-cache exiftool libjpeg-turbo libstdc++ # apk upgrade pulls Alpine security fixes released after the base image was built.
RUN apk upgrade --no-cache \
&& apk add --no-cache exiftool libjpeg-turbo libstdc++
COPY --from=uhdr-build /build/libultrahdr/build/ultrahdr_app /usr/local/bin/ultrahdr_app COPY --from=uhdr-build /build/libultrahdr/build/ultrahdr_app /usr/local/bin/ultrahdr_app
RUN chmod +x /usr/local/bin/ultrahdr_app RUN chmod +x /usr/local/bin/ultrahdr_app
@@ -32,6 +37,22 @@ COPY LICENSE VERSION ./
COPY docker/entrypoint.sh /app/entrypoint.sh COPY docker/entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh RUN chmod +x /app/entrypoint.sh
FROM base AS test
RUN pip install --no-cache-dir pytest==9.1.1 pytest-cov==7.1.0
COPY pytest.ini ./
COPY tests/ tests/
CMD ["pytest", "-v"]
FROM base AS lint
RUN pip install --no-cache-dir ruff==0.16.4
COPY ruff.toml ./
COPY tests/ tests/
RUN ruff check .
FROM base
RUN adduser -D runner && mkdir -p /app/jobs && chown -R runner:runner /app RUN adduser -D runner && mkdir -p /app/jobs && chown -R runner:runner /app
USER runner USER runner
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1473.7981439579798 1123.3987043300267" width="4421.3944318739395" height="3370.19611299008"><!-- svg-source:excalidraw --><metadata></metadata><defs><style class="style-fonts">
@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAACR8AA4AAAAAQSAAACQnAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbkHwcgg4GYACBBBEICuQAyVMLegABNgIkA4FwBCAFgxgHIBuGMiMDwcYBCKD4Nsj+6oA3jBq/Z9BINnEYKBpJmFcpAhquP/azruCQcouvwskISWaH5+fW+71k1bAkQ0YIi6YWjA5BpAQj8URMyiq0L1TMPEXv2syrMIOCmrXeSXJn7BmN5rf499d4CuG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SbVevuk2GjvyJsiuyGOhwgKguEmSV3OCz/pdjUCrM103ZbdEMEAH/KO3Roe6pes+JQzFMbUnhe2a163K7MwJMmtdTbcHTlQsK8zofJ1xW/ngOkRLbslDRbYSGwhycf0BuJDRf0cO1z1ct+6oaBS17IcYdB8SaxLvLdHeTSiw2WOJkzLiqboSj5gWLv7e/3KYks36aX6JQTJ29mKBU7Dx3UQYli32+6Q5KUCA9iHPRX9rkQTHH+PFsNDTzJtim639c9P/7/hz/gCbf7BLH2jJLhk6au9H+FMocHj9/aq/l/2K/GPuyvXPry325cE9BTVI6VZ/vUR4Bi6GgWODx7MvK2fj/jQRmhLine truncated

After

Width:  |  Height:  |  Size: 242 KiB

+2
View File
@@ -0,0 +1,2 @@
[pytest]
testpaths = tests
+54
View File
@@ -0,0 +1,54 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["config:recommended", "docker:pinDigests"],
"timezone": "Europe/Paris",
"minimumReleaseAge": "3 days",
"labels": ["bot"],
"vulnerabilityAlerts": {
"addLabels": ["bug"]
},
"customManagers": [
{
"customType": "regex",
"description": "Docker images pinned in CI 'docker run' / 'docker create' commands",
"managerFilePatterns": ["/^\\.gitea/workflows/.+\\.ya?ml$/"],
"matchStrings": [
"(?<depName>(?:zricethezav/gitleaks|hadolint/hadolint|aquasec/trivy)):(?<currentValue>v?\\d+\\.\\d+\\.\\d+(?:-[a-z]+)?)"
],
"datasourceTemplate": "docker"
}
],
"packageRules": [
{
"matchManagers": ["custom.regex"],
"pinDigests": false
},
{
"matchManagers": ["pip_requirements"],
"minimumReleaseAge": "7 days"
},
{
"matchManagers": ["pip_requirements"],
"matchUpdateTypes": ["patch", "minor"],
"automerge": true
},
{
"matchManagers": ["dockerfile"],
"matchUpdateTypes": ["patch"],
"automerge": true
},
{
"matchManagers": ["dockerfile"],
"matchUpdateTypes": ["pin", "digest"],
"automerge": true
},
{
"matchUpdateTypes": ["major"],
"addLabels": ["major"]
},
{
"matchUpdateTypes": ["minor"],
"addLabels": ["minor"]
}
]
}
+3 -3
View File
@@ -1,5 +1,5 @@
Flask==3.1.3 Flask==3.1.3
gunicorn==23.0.0 gunicorn==23.0.0
Pillow==11.1.0 Pillow==13.0.0
numpy==2.4.6 numpy==2.5.4
tifffile==2026.3.3 tifffile==2026.11.12
+12
View File
@@ -0,0 +1,12 @@
line-length = 100
[lint]
select = ["E", "F", "I", "UP", "B"]
# E501: long lines are left alone. B905: zip() in routes.py is already
# length-checked just before; not touching app logic here.
ignore = ["E501", "B905"]
[lint.isort]
# Pinned explicitly: auto-detection of first-party modules differs between the
# host and the Docker lint stage, which would silently diverge import sorting.
known-first-party = ["app", "main"]
+2
View File
@@ -226,6 +226,8 @@ def _tiff_max_boost(hdr_linear: np.ndarray, sdr_420: Path) -> float:
sdr_linear = _jpeg_to_linear(sdr_420) sdr_linear = _jpeg_to_linear(sdr_420)
real_signal = sdr_linear > 0.005 real_signal = sdr_linear > 0.005
ratio = hdr_linear[real_signal] / sdr_linear[real_signal] ratio = hdr_linear[real_signal] / sdr_linear[real_signal]
if ratio.size == 0:
return 1.0 # all-black SDR: nothing to boost
n = min(32, ratio.size) n = min(32, ratio.size)
return float(np.partition(ratio, -n)[-n]) return float(np.partition(ratio, -n)[-n])
+28
View File
@@ -0,0 +1,28 @@
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src" / "script"))
sys.path.insert(0, str(ROOT))
@pytest.fixture
def jobs_dir(tmp_path, monkeypatch):
from app import jobs
monkeypatch.setattr(jobs, "JOBS_DIR", tmp_path / "jobs")
jobs.JOBS.clear()
yield tmp_path / "jobs"
jobs.JOBS.clear()
@pytest.fixture
def client(jobs_dir, monkeypatch):
from app import create_app, jobs
monkeypatch.setattr(jobs, "start_reaper", lambda: None)
app = create_app()
app.config["TESTING"] = True
return app.test_client()
+207
View File
@@ -0,0 +1,207 @@
import subprocess
from types import SimpleNamespace
import numpy as np
import pytest
import tifffile
from PIL import Image
from app import assembler
def cp(returncode=0, stdout="", stderr=""):
return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
@pytest.fixture
def tools(monkeypatch):
monkeypatch.setattr(assembler.shutil, "which", lambda t: f"/usr/bin/{t}")
def test_check_dependencies(monkeypatch):
monkeypatch.setattr(assembler.shutil, "which", lambda t: None)
assert assembler.check_dependencies() == ["ultrahdr_app", "exiftool"]
monkeypatch.setattr(assembler.shutil, "which", lambda t: "/x" if t == "exiftool" else None)
assert assembler.check_dependencies() == ["ultrahdr_app"]
monkeypatch.setattr(assembler.shutil, "which", lambda t: "/x")
assert assembler.check_dependencies() == []
@pytest.mark.parametrize("desc,code", [
("Display P3", "1"), ("Rec2020 PQ", "2"), ("ITU-R BT.2100", "2"),
("sRGB IEC61966-2.1", "0"), ("", "0"),
])
def test_detect_gamut(monkeypatch, tmp_path, desc, code):
monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(stdout=desc + "\n"))
assert assembler._detect_gamut(tmp_path / "x.jpg") == code
def test_decode_hdr_intent_error(monkeypatch, tools, tmp_path):
monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(1, stderr="bad file"))
with pytest.raises(assembler.AssemblyError, match="bad file"):
assembler._decode_hdr_intent(tmp_path / "h.jpg", tmp_path / "o.raw")
def test_encode_without_and_with_max_boost(monkeypatch, tools, tmp_path):
calls = []
monkeypatch.setattr(assembler.subprocess, "run", lambda args, **k: calls.append(args) or cp())
assembler._encode(tmp_path / "r", "0", tmp_path / "s", "0", 10, 20, tmp_path / "o")
assert "-K" not in calls[0] and calls[0][calls[0].index("-t") + 1] == "1"
assembler._encode(tmp_path / "r", "1", tmp_path / "s", "0", 10, 20, tmp_path / "o", max_boost=4.0)
args = calls[1]
assert args[args.index("-K") + 1] == "4.0"
assert args[args.index("-k") + 1] == "1" # floor never below 1
assert args[args.index("-L") + 1] == str(4.0 * 203)
@pytest.mark.parametrize("boost,nits", [(0.1, 203), (100.0, 10000)])
def test_encode_target_nits_clamped(monkeypatch, tools, tmp_path, boost, nits):
calls = []
monkeypatch.setattr(assembler.subprocess, "run", lambda args, **k: calls.append(args) or cp())
assembler._encode(tmp_path / "r", "0", tmp_path / "s", "0", 1, 1, tmp_path / "o", max_boost=boost)
assert calls[0][calls[0].index("-L") + 1] == str(nits)
def test_encode_failure(monkeypatch, tools, tmp_path):
monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(1, stderr="nope"))
with pytest.raises(assembler.AssemblyError, match="nope"):
assembler._encode(tmp_path / "r", "0", tmp_path / "s", "0", 1, 1, tmp_path / "o")
def test_to_4_2_0_keeps_icc_profile(tmp_path):
src, dest = tmp_path / "s.jpg", tmp_path / "d.jpg"
Image.new("RGB", (16, 16), "red").save(src, "JPEG", icc_profile=b"ICCDATA")
assembler._to_4_2_0(src, dest)
with Image.open(dest) as img:
assert img.info.get("icc_profile") == b"ICCDATA"
assert img.size == (16, 16)
def test_to_4_2_0_without_icc(tmp_path):
src, dest = tmp_path / "s.jpg", tmp_path / "d.jpg"
Image.new("RGB", (8, 8)).save(src, "JPEG")
assembler._to_4_2_0(src, dest)
assert dest.exists()
def test_tiff_to_hdr_raw(tmp_path):
tiff = tmp_path / "h.tif"
data = np.full((2, 3, 3), 2.0, dtype=np.float32)
data[0, 0] = -1.0 # negative values must be clipped
tifffile.imwrite(tiff, data)
dest = tmp_path / "out.raw"
w, h, linear = assembler._tiff_to_hdr_raw(tiff, dest)
assert (w, h) == (3, 2)
assert linear[0, 0, 0] == 0.0
assert linear[1, 1, 0] == pytest.approx(2.0 ** assembler._HLG_SYSTEM_GAMMA)
assert dest.stat().st_size == 2 * 3 * 4 * 2 # RGBA half floats
def test_jpeg_to_linear_range(tmp_path):
p = tmp_path / "w.jpg"
Image.new("RGB", (4, 4), "white").save(p, "JPEG")
lin = assembler._jpeg_to_linear(p)
assert lin.shape == (4, 4, 3) and lin.max() == pytest.approx(1.0, abs=0.02)
def test_tiff_max_boost_ignores_near_black_and_picks_32nd(tmp_path):
sdr = tmp_path / "s.jpg"
Image.new("RGB", (16, 16), (128, 128, 128)).save(sdr, "JPEG", quality=100)
sdr_lin = assembler._jpeg_to_linear(sdr)
hdr = sdr_lin * 3.0
assert assembler._tiff_max_boost(hdr, sdr) == pytest.approx(3.0, rel=0.01)
hdr[0, 0] = 1000.0 # a lone spike must not set the boost
assert assembler._tiff_max_boost(hdr, sdr) == pytest.approx(3.0, rel=0.01)
def test_tiff_max_boost_all_black_image_has_no_signal(tmp_path):
sdr = tmp_path / "s.jpg"
Image.new("RGB", (8, 8), "black").save(sdr, "JPEG")
assert assembler._tiff_max_boost(np.ones((8, 8, 3), dtype=np.float32), sdr) == 1.0
def test_tiff_max_boost_fewer_than_32_pixels(tmp_path):
sdr = tmp_path / "s.jpg"
Image.new("RGB", (2, 2), (128, 128, 128)).save(sdr, "JPEG", quality=100)
hdr = assembler._jpeg_to_linear(sdr) * 2.0
assert assembler._tiff_max_boost(hdr, sdr) == pytest.approx(2.0, rel=0.01)
def test_probe_hdr_capacity(monkeypatch, tools, tmp_path):
out = "foo\n --hdrCapacityMax 3.5\n"
monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(stdout=out))
assert assembler._probe_hdr_capacity(tmp_path / "x") == 3.5
monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(stdout="nothing"))
with pytest.raises(assembler.AssemblyError):
assembler._probe_hdr_capacity(tmp_path / "x")
def fake_exiftool(min_value=None, extract_ok=True, report_stdout=None):
import json
def run(args, **k):
if "-MPImage2" in args:
return cp(0 if extract_ok else 1, stdout=b"data" if extract_ok else b"")
stdout = report_stdout
if stdout is None:
meta = {"XMP-hdrgm:Version": "1.0", "Other:Tag": "x"}
if min_value is not None:
meta["XMP-hdrgm:GainMapMin"] = min_value
stdout = json.dumps([meta])
return cp(stdout=stdout)
return run
@pytest.mark.parametrize("value,negative", [(-0.5, True), (0, False), (1, False), (None, False)])
def test_validate_output_gain_map_min(monkeypatch, tmp_path, value, negative):
monkeypatch.setattr(assembler.subprocess, "run", fake_exiftool(min_value=value))
log = []
assert assembler._validate_output(tmp_path / "o.jpg", log) is negative
assert any("Validation report" in line for line in log)
assert any("WARNING" in line for line in log) is negative
assert not any("Other:Tag" in line for line in log) # non-hdrgm tags filtered
@pytest.mark.parametrize("kwargs", [
{"extract_ok": False}, {"report_stdout": "not json"}, {"report_stdout": "[]"},
])
def test_validate_output_unreadable_metadata(monkeypatch, tmp_path, kwargs):
monkeypatch.setattr(assembler.subprocess, "run", fake_exiftool(**kwargs))
log = []
assert assembler._validate_output(tmp_path / "o.jpg", log) is False
assert log == []
def test_run_missing_tools(monkeypatch, tmp_path):
monkeypatch.setattr(assembler.shutil, "which", lambda t: None)
ok, log, warn = assembler.run(tmp_path / "s.jpg", tmp_path / "h.jpg", tmp_path / "o.jpg")
assert (ok, warn) == (False, False) and "ultrahdr_app" in log
@pytest.mark.parametrize("suffix,target", [
(".jpg", "_assemble_from_jpeg"), (".JPEG", "_assemble_from_jpeg"),
(".tif", "_assemble_from_tiff_hdr"), (".TIFF", "_assemble_from_tiff_hdr"),
])
def test_run_dispatch_by_hdr_extension(monkeypatch, tools, tmp_path, suffix, target):
called = []
for name in ("_assemble_from_jpeg", "_assemble_from_tiff_hdr"):
monkeypatch.setattr(assembler, name, lambda *a, n=name: called.append(n))
monkeypatch.setattr(assembler, "_validate_output", lambda *a: True)
ok, log, warn = assembler.run(tmp_path / "s.jpg", tmp_path / f"h{suffix}", tmp_path / "o.jpg")
assert called == [target] and ok is True and warn is True and "Done!" in log
@pytest.mark.parametrize("exc", [
assembler.AssemblyError("boom"),
subprocess.CalledProcessError(1, "x"),
subprocess.TimeoutExpired("x", 1),
])
def test_run_pipeline_errors_are_reported(monkeypatch, tools, tmp_path, exc):
def fail(*a):
raise exc
monkeypatch.setattr(assembler, "_assemble_from_jpeg", fail)
ok, log, warn = assembler.run(tmp_path / "s.jpg", tmp_path / "h.jpg", tmp_path / "o.jpg")
assert (ok, warn) == (False, False) and log.startswith("Error:")
+77
View File
@@ -0,0 +1,77 @@
"""End-to-end: runs the real ultrahdr_app + exiftool (present in the Docker
image, skipped elsewhere) to catch regressions from dependency or base image
updates that the mocked unit tests cannot see."""
import shutil
import numpy as np
import pytest
import tifffile
from PIL import Image
from app import assembler
pytestmark = pytest.mark.skipif(
bool(assembler.check_dependencies()) or not shutil.which("exiftool"),
reason="ultrahdr_app/exiftool not installed",
)
SIZE = 128
def gradient():
"""A horizontal ramp 0..1 with a bright highlight block, as float values."""
ramp = np.tile(np.linspace(0.05, 1.0, SIZE, dtype=np.float32), (SIZE, 1))
img = np.stack([ramp, ramp, ramp], axis=-1)
return img
@pytest.fixture
def sdr(tmp_path):
arr = (np.clip(gradient() ** (1 / 2.2), 0, 1) * 255).astype(np.uint8)
path = tmp_path / "sdr.jpg"
Image.fromarray(arr).save(path, "JPEG", quality=95)
return path
@pytest.fixture
def hdr_tiff(tmp_path):
hdr = gradient()
hdr[:32, :32] *= 3.0 # highlight brighter than SDR white
path = tmp_path / "hdr.tif"
tifffile.imwrite(path, hdr.astype(np.float32), photometric="rgb")
return path
def assert_valid_ultrahdr(out, log):
assert out.exists() and out.stat().st_size > 0
with Image.open(out) as img:
assert img.format == "JPEG" and img.size == (SIZE, SIZE)
assert "Validation report" in log # gain map found and readable
assert "XMP-hdrgm:GainMapMax" in log
def test_tiff_pipeline_produces_ultrahdr_jpeg(tmp_path, sdr, hdr_tiff):
out = tmp_path / "out.jpg"
ok, log, warning = assembler.run(sdr, hdr_tiff, out)
assert ok, log
assert_valid_ultrahdr(out, log)
assert warning is False # GainMapMin must not be negative (Instagram rejects it)
def test_jpeg_pipeline_round_trip(tmp_path, sdr, hdr_tiff):
first = tmp_path / "first.jpg"
ok, log, _ = assembler.run(sdr, hdr_tiff, first)
assert ok, log
second = tmp_path / "second.jpg"
ok, log, warning = assembler.run(sdr, first, second) # existing gain-map JPEG as HDR input
assert ok, log
assert_valid_ultrahdr(second, log)
assert warning is False
def test_invalid_hdr_jpeg_fails_cleanly(tmp_path, sdr):
not_hdr = tmp_path / "plain.jpg"
shutil.copy(sdr, not_hdr) # a JPEG without any gain map
ok, log, warning = assembler.run(sdr, not_hdr, tmp_path / "out.jpg")
assert ok is False and warning is False
assert log.splitlines()[-1].startswith("Error:")
+79
View File
@@ -0,0 +1,79 @@
import time
import pytest
from app import jobs
def test_new_job_dir_creates_directory(jobs_dir):
d = jobs.new_job_dir("abc")
assert d == jobs_dir / "abc" and d.is_dir()
assert jobs.new_job_dir("abc") == d # idempotent
def test_register_get_unknown(jobs_dir):
assert jobs.get("nope") is None
jobs.register("j1", items=[1])
job = jobs.get("j1")
assert job["items"] == [1] and "last_seen" in job
def test_touch_updates_and_ignores_unknown(jobs_dir):
jobs.register("j1")
jobs.JOBS["j1"]["last_seen"] = 0
jobs.touch("j1")
assert jobs.JOBS["j1"]["last_seen"] > 0
jobs.touch("unknown") # must not raise
assert "unknown" not in jobs.JOBS
def test_cleanup_removes_registry_and_dir(jobs_dir):
d = jobs.new_job_dir("j1")
(d / "f.txt").write_text("x")
jobs.register("j1")
jobs.cleanup("j1")
assert jobs.get("j1") is None and not d.exists()
def test_cleanup_unknown_job_is_noop(jobs_dir):
jobs.reset_jobs_dir()
jobs.cleanup("ghost")
def test_reset_jobs_dir_wipes_leftovers(jobs_dir):
jobs.new_job_dir("old")
jobs.reset_jobs_dir()
assert jobs_dir.is_dir() and list(jobs_dir.iterdir()) == []
def test_reap_removes_only_stale_jobs(jobs_dir, monkeypatch):
jobs.new_job_dir("stale")
jobs.new_job_dir("fresh")
jobs.register("stale")
jobs.register("fresh")
jobs.JOBS["stale"]["last_seen"] = time.time() - 1000
def stop(_):
if stop.called:
raise StopIteration
stop.called = True
stop.called = False
monkeypatch.setattr(jobs.time, "sleep", stop)
with pytest.raises(StopIteration):
jobs._reap_stale_jobs()
assert "stale" not in jobs.JOBS and not (jobs_dir / "stale").exists()
assert "fresh" in jobs.JOBS and (jobs_dir / "fresh").exists()
def test_reap_with_no_jobs(jobs_dir, monkeypatch):
calls = []
def stop(_):
if calls:
raise StopIteration
calls.append(1)
monkeypatch.setattr(jobs.time, "sleep", stop)
with pytest.raises(StopIteration):
jobs._reap_stale_jobs()
+147
View File
@@ -0,0 +1,147 @@
import io
import zipfile
import pytest
from PIL import Image
from app import assembler, jobs
def jpeg_bytes(size=(1080, 1080)):
buf = io.BytesIO()
Image.new("RGB", size, "gray").save(buf, "JPEG")
return buf.getvalue()
def pair(name="a", sdr_name=None, hdr_name=None, size=(1080, 1080)):
return (
(io.BytesIO(jpeg_bytes(size)), sdr_name or f"{name}_sdr.jpg"),
(io.BytesIO(jpeg_bytes(size)), hdr_name or f"{name}_hdr.jpg"),
)
def post(client, pairs):
data = {"sdr[]": [p[0] for p in pairs], "hdr[]": [p[1] for p in pairs]}
return client.post("/convert", data=data, content_type="multipart/form-data")
@pytest.fixture
def fake_run(monkeypatch):
def run(sdr_path, hdr_path, out_path):
out_path.write_bytes(b"OUT:" + out_path.name.encode())
return True, "ok", False
monkeypatch.setattr(assembler, "run", run)
def job_id_from(resp):
return resp.headers["Location"].rstrip("/").split("/")[-1]
def test_index(client):
assert client.get("/").status_code == 200
def test_convert_without_files(client):
resp = client.post("/convert", data={}, content_type="multipart/form-data")
assert resp.status_code == 400 and b"at least one" in resp.data
def test_convert_unbalanced_pairs(client):
data = {"sdr[]": [(io.BytesIO(jpeg_bytes()), "a.jpg")], "hdr[]": []}
resp = client.post("/convert", data=data, content_type="multipart/form-data")
assert resp.status_code == 400
def test_convert_success_single(client, fake_run):
resp = post(client, [pair()])
assert resp.status_code == 302
jid = job_id_from(resp)
page = client.get(f"/result/{jid}")
assert page.status_code == 200 and b"JPEG assembled" in page.data
dl = client.get(f"/download/{jid}")
assert dl.status_code == 200
assert dl.headers["Content-Disposition"].endswith("instagram_hdr_output.jpg")
assert dl.data.startswith(b"OUT:")
def test_convert_multiple_downloads_zip(client, fake_run):
jid = job_id_from(post(client, [pair("a"), pair("b"), pair("c")]))
assert b"All 3 assembled" in client.get(f"/result/{jid}").data
dl = client.get(f"/download/{jid}")
assert dl.mimetype == "application/zip"
with zipfile.ZipFile(io.BytesIO(dl.data)) as zf:
assert zf.namelist() == [f"instagram_hdr_output_{i}.jpg" for i in (1, 2, 3)]
def test_partial_failure_download_only_successes(client, fake_run):
bad = pair("b", sdr_name="b.png")
jid = job_id_from(post(client, [pair("a"), bad]))
assert b"1/2 assembled" in client.get(f"/result/{jid}").data
dl = client.get(f"/download/{jid}")
assert dl.mimetype != "application/zip" # a single success is sent as a plain JPEG
def test_all_failed(client, fake_run):
jid = job_id_from(post(client, [pair(sdr_name="x.png")]))
assert b"Conversion failed" in client.get(f"/result/{jid}").data
assert client.get(f"/download/{jid}").status_code == 404
def test_bad_hdr_extension_reported(client, fake_run):
jid = job_id_from(post(client, [pair(hdr_name="h.png")]))
assert jobs.get(jid)["items"][0]["success"] is False
assert "HDR file" in jobs.get(jid)["items"][0]["log"]
@pytest.mark.parametrize("sdr_name,hdr_name", [("", "h.jpg"), ("s.jpg", ""), ("", "")])
def test_empty_filename_reported(tmp_path, sdr_name, hdr_name):
from types import SimpleNamespace
from app.routes import _process_pair
item = _process_pair(tmp_path, 1, SimpleNamespace(filename=sdr_name),
SimpleNamespace(filename=hdr_name))
assert item["success"] is False and "Missing" in item["log"]
def test_resolution_rejected_and_inputs_removed(client, fake_run, jobs_dir):
jid = job_id_from(post(client, [pair(size=(100, 100))]))
item = jobs.get(jid)["items"][0]
assert not item["success"] and "Instagram requires" in item["log"]
assert list((jobs_dir / jid).iterdir()) == []
def test_ignore_ig_resolution_flag(client, fake_run):
pairs = [pair(size=(100, 100))]
data = {"sdr[]": [pairs[0][0]], "hdr[]": [pairs[0][1]], "ignore_ig_resolution": "on"}
resp = client.post("/convert", data=data, content_type="multipart/form-data")
assert jobs.get(job_id_from(resp))["items"][0]["success"] is True
def test_assembler_failure_has_no_output(client, monkeypatch):
monkeypatch.setattr(assembler, "run", lambda *a: (False, "boom", False))
jid = job_id_from(post(client, [pair()]))
item = jobs.get(jid)["items"][0]
assert item["success"] is False and item["output"] is None
assert client.get(f"/download/{jid}").status_code == 404
def test_unknown_job_404(client):
assert client.get("/result/nope").status_code == 404
assert client.get("/download/nope").status_code == 404
def test_heartbeat(client):
assert client.post("/heartbeat/unknown").status_code == 204
jobs.register("j1")
jobs.JOBS["j1"]["last_seen"] = 0
assert client.post("/heartbeat/j1").status_code == 204
assert jobs.JOBS["j1"]["last_seen"] > 0
def test_too_large(client, monkeypatch):
client.application.config["MAX_CONTENT_LENGTH"] = 10
resp = client.post("/convert", data={"sdr[]": (io.BytesIO(b"x" * 100), "a.jpg")},
content_type="multipart/form-data")
assert resp.status_code == 413 and b"too large" in resp.data
+106
View File
@@ -0,0 +1,106 @@
import numpy as np
import pytest
import tifffile
from PIL import Image
from app import validation
def make_jpeg(path, size):
Image.new("RGB", size, "gray").save(path, "JPEG")
return path
def make_tiff(path, size):
tifffile.imwrite(path, np.zeros((size[1], size[0], 3), dtype=np.float32))
return path
@pytest.mark.parametrize("name,expected", [
("a.JPG", ".jpg"), ("a.b.tiff", ".tiff"), ("noext", ""), ("", ""),
])
def test_ext(name, expected):
assert validation.ext(name) == expected
@pytest.mark.parametrize("name,expected", [
("x.tif", True), ("x.TIFF", True), ("x.jpg", False), ("tif", False),
])
def test_is_tiff(name, expected):
assert validation.is_tiff(name) is expected
@pytest.mark.parametrize("name,ok", [
("a.jpg", True), ("a.JPEG", True), ("a.tif", False), ("a.png", False), ("", False),
])
def test_sdr_ext_error(name, ok):
assert (validation.sdr_ext_error(name) is None) is ok
@pytest.mark.parametrize("name,ok", [
("a.jpg", True), ("a.jpeg", True), ("a.tif", True), ("a.TIFF", True),
("a.png", False), ("a.avif", False), ("", False),
])
def test_hdr_ext_error(name, ok):
assert (validation.hdr_ext_error(name) is None) is ok
def test_probe_dimensions_jpeg_and_tiff(tmp_path):
assert validation.probe_dimensions(make_jpeg(tmp_path / "a.jpg", (30, 20))) == (30, 20)
assert validation.probe_dimensions(make_tiff(tmp_path / "a.tif", (30, 20))) == (30, 20)
def test_probe_dimensions_corrupt(tmp_path):
bad_jpg = tmp_path / "bad.jpg"
bad_jpg.write_bytes(b"not an image")
bad_tif = tmp_path / "bad.tif"
bad_tif.write_bytes(b"not a tiff")
with pytest.raises(ValueError, match="image dimensions"):
validation.probe_dimensions(bad_jpg)
with pytest.raises(ValueError, match="TIFF dimensions"):
validation.probe_dimensions(bad_tif)
def test_probe_dimensions_missing_file(tmp_path):
with pytest.raises(ValueError):
validation.probe_dimensions(tmp_path / "missing.jpg")
@pytest.mark.parametrize("size", [(1080, 1080), (1080, 1350), (1080, 566)])
def test_resolution_ok_for_each_instagram_format(tmp_path, size):
sdr = make_jpeg(tmp_path / "s.jpg", size)
hdr = make_jpeg(tmp_path / "h.jpg", size)
assert validation.instagram_resolution_error(sdr, hdr) is None
def test_resolution_ok_with_tiff_hdr(tmp_path):
sdr = make_jpeg(tmp_path / "s.jpg", (1080, 1080))
hdr = make_tiff(tmp_path / "h.tif", (1080, 1080))
assert validation.instagram_resolution_error(sdr, hdr) is None
def test_resolution_mismatch_always_rejected(tmp_path):
sdr = make_jpeg(tmp_path / "s.jpg", (1080, 1080))
hdr = make_jpeg(tmp_path / "h.jpg", (1080, 1350))
for ignore in (False, True):
assert "identical" in validation.instagram_resolution_error(sdr, hdr, ignore)
def test_resolution_not_instagram(tmp_path):
sdr = make_jpeg(tmp_path / "s.jpg", (100, 100))
hdr = make_jpeg(tmp_path / "h.jpg", (100, 100))
assert "Instagram requires" in validation.instagram_resolution_error(sdr, hdr)
assert validation.instagram_resolution_error(sdr, hdr, ignore_ig_resolution=True) is None
def test_resolution_swapped_dimensions_rejected(tmp_path):
sdr = make_jpeg(tmp_path / "s.jpg", (1350, 1080))
hdr = make_jpeg(tmp_path / "h.jpg", (1350, 1080))
assert validation.instagram_resolution_error(sdr, hdr) is not None
def test_resolution_unreadable_file(tmp_path):
sdr = make_jpeg(tmp_path / "s.jpg", (1080, 1080))
bad = tmp_path / "h.jpg"
bad.write_bytes(b"")
assert "Could not validate" in validation.instagram_resolution_error(sdr, bad)