4 Commits

Author SHA1 Message Date
ml d5f4381169 Add a custom Android CI/release build image and packaging scripts
build / build (push) Failing after 0s
- build-image/: Dockerfile bundling JDK 17, the Android SDK, and
  Node.js (needed by Gitea's JS-based actions) - the app has no
  native code, so no NDK
- build-image.sh/upload-image.sh: extended to also build/push this
  image alongside the existing OCR pipeline tools image
- run-image.sh: runs `make android` inside the image against a live
  checkout, for a CI-equivalent local build
- Makefile: `make android` builds and versions a release APK into
  dist/, from the current git tag
- .gitea/workflows/build.yml: now pulls the custom image and just
  runs `make android`, replacing the ad-hoc Node/SDK install steps
- README.md: describes the pipeline, server, app, and build tooling
- registry.env.example: fix REGISTRY_IMAGE to be fully-qualified
  (an unqualified name was silently resolving pushes to Docker Hub
  instead of the configured registry)
2026-09-29 17:48:02 +02:00
ml 516f5d3b7d Add HTTP API server, Android app, and CI build/publish pipeline
build / build (push) Failing after 14s
- docker-compose.yml + tooling-container/src/server.py: serve
  preprocess/OCR/extract over an async job API (POST /jobs, GET
  /jobs/{id}) instead of manual host-script runs per receipt
- android/: Kotlin/Compose app - capture a receipt photo, poll job
  progress, review/edit extracted fields, save locally (Room), export
  to CSV/ODS
- .gitea/workflows/build.yml: build the debug APK and publish it to
  dl.ladkau.de on push
- build-image.sh: also pull ollama/ollama so all pipeline images are
  ready after one script
- add project logo (also used for the app's launcher icon/splash)
2026-09-29 12:58:58 +02:00
matthias 7cea285ec3 Rename project from gastronomy to fuelish
Renamed all image tags, container/volume names, and doc references.
2026-09-28 19:47:05 +02:00
matthias 7678d28717 Add containerized OCR pipeline for fuel receipts
Self-hosted, verifiable pipeline for extracting structured data (station,
date/time, price per litre, litres, discount, total) from German fuel
receipt photos: grayscale + mild bilateral filter + contrast stretch,
Tesseract OCR, then LLM structuring via a small local model (Qwen 2.5,
served by Ollama). Each step is independently runnable and inspectable
through numbered scripts against a shared tooling container.

Ollama runs as its own long-lived container (0_run_ollama.sh), separate
from the stateless per-receipt pipeline steps, so the model stays loaded
in memory between runs. Includes a containerized ground-truth batch test
(test_batch.sh) that reproduces the full pipeline over the test receipts
and reports per-field accuracy.

Targets eventual deployment on a Raspberry Pi 4 k3s cluster.
2026-09-28 19:35:29 +02:00
66 changed files with 3305 additions and 2 deletions
+74
View File
@@ -0,0 +1,74 @@
name: build
# Builds the Android app (android/) debug APK on every push/PR, plus
# on-demand via the Gitea "Run workflow" button. Runs inside build-image
# (see ../../build-image/Dockerfile, built/pushed via ../../build-image.sh
# and ../../upload-image.sh), which bundles the JDK, Android SDK, and
# Node.js (needed by the JS-based actions below - see
# build-image/Dockerfile's own comment) so the runner itself doesn't need
# any of that installed. The Gradle build still needs network access at
# job runtime (Gradle/AGP/androidx dependency resolution).
on:
push:
pull_request:
workflow_dispatch:
jobs:
build:
# Runner defaults `run:` steps to `sh`, which doesn't understand
# `set -o pipefail` used below - force bash explicitly.
defaults:
run:
shell: bash
# Must match a label your act_runner is registered with.
runs-on: ubuntu-latest
container:
image: cr.ladkau.de/fuelish/android-builder:latest
credentials:
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
steps:
- uses: actions/checkout@v4
with:
# `make android`'s version comes from `git describe --tags` -
# needs full history/tags, not actions/checkout's default
# shallow single-commit clone.
fetch-depth: 0
- name: Preflight
run: |
set -euo pipefail
command -v java >/dev/null 2>&1 || { echo "PREFLIGHT FAIL: java not in PATH" >&2; exit 1; }
command -v make >/dev/null 2>&1 || { echo "PREFLIGHT FAIL: make not in PATH" >&2; exit 1; }
[ -n "${ANDROID_HOME:-}" ] || { echo "PREFLIGHT FAIL: ANDROID_HOME not set" >&2; exit 1; }
- name: Build
run: make android
- name: Upload build artifact
# v4 uses the newer @actions/artifact backend, which this Gitea
# instance's artifact storage doesn't support (GHESNotSupportedError) — v3 works.
uses: actions/upload-artifact@v3
with:
name: fuelish-android
path: dist/fuelish-*.apk
- name: Publish to dl.ladkau.de
# Uploads the APK over SFTP instead of using actions/upload-artifact
# (whose zip wrapping can't be disabled). Only runs on push so PR
# builds don't publish.
if: gitea.event_name == 'push'
run: |
set -euo pipefail
APK="$(ls dist/fuelish-*.apk)"
mkdir -p ~/.ssh
echo "${{ secrets.DL_SFTP_KEY }}" > ~/.ssh/dl_sftp_key
chmod 600 ~/.ssh/dl_sftp_key
sftp -i ~/.ssh/dl_sftp_key -P 2223 \
-o StrictHostKeyChecking=accept-new \
uploader@dl.ladkau.de <<EOF
-mkdir files/fuelish
put $APK files/fuelish/$(basename "$APK")
EOF
+41
View File
@@ -0,0 +1,41 @@
# Test receipt images / ground-truth spreadsheets (not checked in)
/testdata/
# Local registry credentials (see registry.env.example)
/registry.env
# Local Claude Code settings
/.claude/settings.local.json
# Generated pipeline output (see test_batch.sh, 1_preprocess_image.sh,
# 2_ocr_image.sh, 3_extract_data.sh) - intermediate/result dirs are
# created as siblings of whatever -in directory was processed
*-scratch/
*-result/
# Python bytecode cache (picked up if src/ is ever imported on the host
# instead of run through the container)
__pycache__/
*.pyc
# Build output (see the root Makefile's `android` target, run-image.sh)
/dist/
# Android app build output/local config and generated resources (launcher
# icon + splash art - see android/app/build.gradle.kts's
# generateAppIcons task and android/scripts/gen_app_icons.py's own
# doc comment).
/android/local.properties
/android/.gradle
/android/build
/android/app/build
/android/app/src/main/res/drawable-nodpi
/android/app/src/main/res/mipmap-mdpi
/android/app/src/main/res/mipmap-hdpi
/android/app/src/main/res/mipmap-xhdpi
/android/app/src/main/res/mipmap-xxhdpi
/android/app/src/main/res/mipmap-xxxhdpi
# Android Studio project files - per-developer, not shared
/android/.idea/
/android/gradle/gradle-daemon-jvm.properties
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
# Step 0: start the Ollama inference server that the pipeline's
# structuring step (3_extract_data.sh) talks to. Runs the official
# ollama/ollama image as a long-lived container with model weights kept
# in a named Docker volume - deliberately separate from the
# tooling-container (which is stateless and one-shot per receipt), so the
# model stays loaded in memory between pipeline runs instead of being
# reloaded on every receipt.
#
# Usage: ./0_run_ollama.sh [-model <name>]
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
fail() { echo "FAIL: $*" >&2; exit 1; }
command -v docker >/dev/null 2>&1 || fail "docker not found in PATH"
MODEL="qwen2.5:3b"
while [ $# -gt 0 ]; do
case "$1" in
-model) MODEL="${2:-}"; shift 2 ;;
*) fail "unknown argument: $1" ;;
esac
done
CONTAINER=fuelish-ollama
VOLUME=fuelish-ollama-data
PORT=11434
if docker ps --format '{{.Names}}' | grep -qx "$CONTAINER"; then
echo "== $CONTAINER already running =="
elif docker ps -a --format '{{.Names}}' | grep -qx "$CONTAINER"; then
echo "== Starting existing $CONTAINER container =="
docker start "$CONTAINER" >/dev/null
else
echo "== Creating $CONTAINER (model weights kept in volume $VOLUME) =="
docker run -d \
--name "$CONTAINER" \
-p "127.0.0.1:$PORT:11434" \
-v "$VOLUME:/root/.ollama" \
--restart unless-stopped \
ollama/ollama >/dev/null
fi
echo "== Waiting for Ollama to become ready =="
ready=0
for _ in $(seq 1 30); do
if curl -s --max-time 2 "http://127.0.0.1:$PORT/api/tags" >/dev/null 2>&1; then
ready=1
break
fi
sleep 1
done
[ "$ready" = "1" ] || fail "Ollama did not become ready on port $PORT"
if ! docker exec "$CONTAINER" ollama list | awk 'NR>1{print $1}' | grep -qx "$MODEL"; then
echo "== Pulling model $MODEL =="
docker exec "$CONTAINER" ollama pull "$MODEL"
fi
echo "== Done =="
echo "Ollama running at http://127.0.0.1:$PORT (model: $MODEL)"
echo "Next: ./1_preprocess_image.sh -in <photo> -out <scratch-dir>"
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
# Step 1 of the OCR pipeline: mild smoothing + contrast-stretch a receipt
# photo. Writes each intermediate stage (01_gray, 02_bilateral, 03_final)
# into the output directory so every step can be inspected independently
# before trusting the final image to OCR.
#
# Usage: ./1_preprocess_image.sh -in <photo> -out <scratch-dir>
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(pwd)"
fail() { echo "FAIL: $*" >&2; exit 1; }
IN_PATH=""
OUT_DIR=""
while [ $# -gt 0 ]; do
case "$1" in
-in) IN_PATH="${2:-}"; shift 2 ;;
-out) OUT_DIR="${2:-}"; shift 2 ;;
*) fail "unknown argument: $1" ;;
esac
done
[ -n "$IN_PATH" ] && [ -n "$OUT_DIR" ] \
|| fail "usage: $0 -in <photo> -out <scratch-dir>"
[ -f "$IN_PATH" ] || fail "input file not found: $IN_PATH"
command -v docker >/dev/null 2>&1 || fail "docker not found in PATH"
IMAGE="${REGISTRY_IMAGE:-fuelish/tools}"
if [ -f "$ROOT/registry.env" ]; then
# shellcheck disable=SC1091
source "$ROOT/registry.env"
IMAGE="${REGISTRY_IMAGE:-$IMAGE}"
fi
VERSION="$(<"$ROOT/tooling-container/VERSION")"
IMAGE="$IMAGE:$VERSION"
docker image inspect "$IMAGE" >/dev/null 2>&1 \
|| fail "$IMAGE not found locally - run ./build-image.sh first"
IN_ABS="$(realpath "$IN_PATH")"
IN_DIR="$(dirname "$IN_ABS")"
IN_FILE="$(basename "$IN_ABS")"
mkdir -p "$OUT_DIR"
OUT_ABS="$(realpath "$OUT_DIR")"
# On a vboxsf-mounted repo, files are owned by root:vboxsf with no
# "other" access - join the mounted dirs' groups so --user can read/write
# them without needing root inside the container.
GROUP_ADD_ARGS=(--group-add "$(stat -c %g "$IN_DIR")")
OUT_GID="$(stat -c %g "$OUT_ABS")"
[ "$OUT_GID" = "$(stat -c %g "$IN_DIR")" ] || GROUP_ADD_ARGS+=(--group-add "$OUT_GID")
echo "== Preprocessing $IN_FILE =="
docker run --rm \
--user "$(id -u):$(id -g)" \
"${GROUP_ADD_ARGS[@]}" \
-v "$IN_DIR:/data/in:ro" \
-v "$OUT_ABS:/data/out" \
"$IMAGE" \
python3 /opt/app/src/preprocess.py -in "/data/in/$IN_FILE" -out /data/out
echo "== Done =="
echo "Stages written to: $OUT_ABS/{01_gray,02_bilateral,03_final}.png"
echo "Next: ./2_ocr_image.sh -in $OUT_ABS/03_final.png -out $OUT_ABS"
Executable
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
# Step 2 of the pipeline: run Tesseract OCR (German) over a preprocessed
# receipt image, writing the raw recognized text to the output directory
# so it can be checked before it is handed to the AI structuring step.
#
# Usage: ./2_ocr_image.sh -in <preprocessed-image> -out <scratch-dir>
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(pwd)"
fail() { echo "FAIL: $*" >&2; exit 1; }
IN_PATH=""
OUT_DIR=""
while [ $# -gt 0 ]; do
case "$1" in
-in) IN_PATH="${2:-}"; shift 2 ;;
-out) OUT_DIR="${2:-}"; shift 2 ;;
*) fail "unknown argument: $1" ;;
esac
done
[ -n "$IN_PATH" ] && [ -n "$OUT_DIR" ] \
|| fail "usage: $0 -in <preprocessed-image> -out <scratch-dir>"
[ -f "$IN_PATH" ] || fail "input file not found: $IN_PATH"
command -v docker >/dev/null 2>&1 || fail "docker not found in PATH"
IMAGE="${REGISTRY_IMAGE:-fuelish/tools}"
if [ -f "$ROOT/registry.env" ]; then
# shellcheck disable=SC1091
source "$ROOT/registry.env"
IMAGE="${REGISTRY_IMAGE:-$IMAGE}"
fi
VERSION="$(<"$ROOT/tooling-container/VERSION")"
IMAGE="$IMAGE:$VERSION"
docker image inspect "$IMAGE" >/dev/null 2>&1 \
|| fail "$IMAGE not found locally - run ./build-image.sh first"
IN_ABS="$(realpath "$IN_PATH")"
IN_DIR="$(dirname "$IN_ABS")"
IN_FILE="$(basename "$IN_ABS")"
mkdir -p "$OUT_DIR"
OUT_ABS="$(realpath "$OUT_DIR")"
# On a vboxsf-mounted repo, files are owned by root:vboxsf with no
# "other" access - join the mounted dirs' groups so --user can read/write
# them without needing root inside the container.
GROUP_ADD_ARGS=(--group-add "$(stat -c %g "$IN_DIR")")
OUT_GID="$(stat -c %g "$OUT_ABS")"
[ "$OUT_GID" = "$(stat -c %g "$IN_DIR")" ] || GROUP_ADD_ARGS+=(--group-add "$OUT_GID")
echo "== OCR-ing $IN_FILE =="
docker run --rm \
--user "$(id -u):$(id -g)" \
"${GROUP_ADD_ARGS[@]}" \
-v "$IN_DIR:/data/in:ro" \
-v "$OUT_ABS:/data/out" \
"$IMAGE" \
python3 /opt/app/src/ocr.py -in "/data/in/$IN_FILE" -out /data/out
echo "== Done =="
echo "OCR text written to: $OUT_ABS/ocr.txt"
echo "Next: ./3_extract_data.sh -in $OUT_ABS/ocr.txt -out $OUT_ABS"
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Step 3 of the pipeline: send raw OCR text to a small text-only LLM
# (served by Ollama on the host) to structure it into the receipt JSON
# schema. Runs with --network host so the container can reach Ollama at
# 127.0.0.1 on the host; override with OLLAMA_URL / OLLAMA_MODEL env vars
# if Ollama runs elsewhere or you want a different model.
#
# Usage: ./3_extract_data.sh -in <ocr.txt> -out <scratch-dir>
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(pwd)"
fail() { echo "FAIL: $*" >&2; exit 1; }
IN_PATH=""
OUT_DIR=""
while [ $# -gt 0 ]; do
case "$1" in
-in) IN_PATH="${2:-}"; shift 2 ;;
-out) OUT_DIR="${2:-}"; shift 2 ;;
*) fail "unknown argument: $1" ;;
esac
done
[ -n "$IN_PATH" ] && [ -n "$OUT_DIR" ] \
|| fail "usage: $0 -in <ocr.txt> -out <scratch-dir>"
[ -f "$IN_PATH" ] || fail "input file not found: $IN_PATH"
command -v docker >/dev/null 2>&1 || fail "docker not found in PATH"
IMAGE="${REGISTRY_IMAGE:-fuelish/tools}"
if [ -f "$ROOT/registry.env" ]; then
# shellcheck disable=SC1091
source "$ROOT/registry.env"
IMAGE="${REGISTRY_IMAGE:-$IMAGE}"
fi
VERSION="$(<"$ROOT/tooling-container/VERSION")"
IMAGE="$IMAGE:$VERSION"
docker image inspect "$IMAGE" >/dev/null 2>&1 \
|| fail "$IMAGE not found locally - run ./build-image.sh first"
IN_ABS="$(realpath "$IN_PATH")"
IN_DIR="$(dirname "$IN_ABS")"
IN_FILE="$(basename "$IN_ABS")"
mkdir -p "$OUT_DIR"
OUT_ABS="$(realpath "$OUT_DIR")"
# On a vboxsf-mounted repo, files are owned by root:vboxsf with no
# "other" access - join the mounted dirs' groups so --user can read/write
# them without needing root inside the container.
GROUP_ADD_ARGS=(--group-add "$(stat -c %g "$IN_DIR")")
OUT_GID="$(stat -c %g "$OUT_ABS")"
[ "$OUT_GID" = "$(stat -c %g "$IN_DIR")" ] || GROUP_ADD_ARGS+=(--group-add "$OUT_GID")
echo "== Extracting structured data from $IN_FILE =="
docker run --rm \
--network host \
--user "$(id -u):$(id -g)" \
"${GROUP_ADD_ARGS[@]}" \
-e OLLAMA_URL="${OLLAMA_URL:-http://127.0.0.1:11434/api/chat}" \
-e OLLAMA_MODEL="${OLLAMA_MODEL:-qwen2.5:3b}" \
-v "$IN_DIR:/data/in:ro" \
-v "$OUT_ABS:/data/out" \
"$IMAGE" \
python3 /opt/app/src/extract.py -in "/data/in/$IN_FILE" -out /data/out
echo "== Done =="
echo "Extracted JSON written to: $OUT_ABS/extracted.json"
+87
View File
@@ -0,0 +1,87 @@
# fuelish
Extracts structured data from photos of German fuel/petrol receipts:
petrol station, transaction number, date, time, price per litre, litres,
discount, and total price.
The extraction pipeline is self-hosted (no cloud AI APIs) and is built to
eventually run on a Raspberry Pi 4 cluster under k3s. Everything runs in
containers; there is no host Python environment to set up.
## Pipeline
Three verifiable, independently-inspectable steps, each a thin host
script that runs the actual work inside the `fuelish/tools` container:
1. `1_preprocess_image.sh -in <photo> -out <dir>` - grayscale conversion,
a mild bilateral filter, and a percentile contrast stretch. Writes
every intermediate stage (`01_gray.png`, `02_bilateral.png`,
`03_final.png`) so each step can be checked on its own.
2. `2_ocr_image.sh -in <dir>/03_final.png -out <dir>` - Tesseract OCR
(German), writes `ocr.txt`.
3. `3_extract_data.sh -in <dir>/ocr.txt -out <dir>` - sends the raw OCR
text to a small local LLM (`qwen2.5:3b`, served by Ollama) with a JSON
schema, writes `extracted.json`.
Preprocessing choice is evidence-based, not assumed: heavier processing
(strong denoising, CLAHE, unsharp masking) was tried and measured worse -
it amplifies the receipt's dotted security-background pattern into OCR
noise. The lighter bilateral+autocontrast approach in
`tooling-container/src/preprocess.py` is what survived testing.
## Supporting scripts
- `0_run_ollama.sh [-model <name>]` - starts Ollama as its own long-lived
Docker container (`fuelish-ollama`, model weights in the named
volume `fuelish-ollama-data`), pulling the model if not already
present. Deliberately separate from the tooling container: Ollama needs
to stay resident in memory with the model loaded, while the pipeline
steps are short-lived and stateless (one `docker run` per receipt).
`3_extract_data.sh` reaches it via `--network host` at
`http://127.0.0.1:11434` by default (override with `OLLAMA_URL`/
`OLLAMA_MODEL`).
- `build-image.sh` / `upload-image.sh` - build/push the
`tooling-container/` image, tagged from `tooling-container/VERSION`.
Image name defaults to `fuelish/tools`, overridable via
`registry.env` (copy from `registry.env.example`; gitignored).
- `test_batch.sh -in <test-data-dir>` - runs the full pipeline over every
`*.jpg` in a directory and compares results against that directory's
ground-truth spreadsheet (`*.ods`). For an input dir `<path>/<name>` it
creates sibling `<path>/<name>-scratch/` (intermediate step output per
receipt) and `<path>/<name>-result/` (final `extracted.json` per
receipt, plus `summary.txt`). Both are gitignored.
## Current state
Last full run against the 17-receipt ground-truth test set
(`testdata/2026_new/`, not checked in - see `.gitignore`):
- 15/17 receipts date-matched to ground truth (up from 11/17 with the
original plain-grayscale preprocessing)
- price_per_litre: 11/15 correct, litres: 9/15, discount: 11/15,
total_price: 12/15
Known remaining failure modes, not expected to be fixable by further
preprocessing tuning:
- OCR garbling on the compact "litres EUR/l price" line on some receipts
(the raw text sometimes lacks recoverable digits)
- Occasional year-digit misreads in the date causing a false date-match
failure
- Low-resolution source photos (well below the ~4000x3000 the good
results come from) OCR poorly regardless of preprocessing
The structuring prompt in `tooling-container/src/extract.py` uses
deliberately non-colliding example values. An earlier version used real
receipt values as worked examples, which caused the small model to
copy/anchor on those exact numbers instead of reading the actual OCR
text - a subtle failure mode worth remembering if the prompt is revised.
## Not yet built
Per the original idea (see git history / project notes): an Android app
to capture and confirm receipts, a backend server to store raw + confirmed
submissions, a simple authenticated web UI to query/filter/export
(CSV/JSON), and cross-checking total_price against
price_per_litre * litres - discount. None of that exists yet - this repo
currently covers only the extraction pipeline.
+45
View File
@@ -0,0 +1,45 @@
# Builds the Android app (android/) and packages a versioned release APK.
# The OCR pipeline itself (tooling-container/, 0-3_*.sh, test_batch.sh) is
# container-only and has no host build step, so this Makefile only covers
# the Android app.
ANDROID_DIR := android
ANDROID_APK := $(ANDROID_DIR)/app/build/outputs/apk/debug/app-debug.apk
DIST_DIR := dist
.PHONY: all android clean
all: android
# Builds the Android app (`./gradlew assembleDebug` in android/, via its
# own Gradle/AGP toolchain) and copies the resulting debug APK into
# dist/, named with the current git tag, or `make android VERSION=1.2.3`
# to override. Untagged builds (including every CI build, unless a
# release tag is pushed) get a 0.0.0-dev+<sha> placeholder version.
# Ships the auto-generated debug keystore, not a release signing config -
# fine for sideloading; a real release signing setup is a separate,
# not-yet-needed step. Requires the Android SDK (ANDROID_HOME set) - see
# build-image/Dockerfile for the exact version this is built/tested
# against, or run this inside it via ./run-image.sh.
android:
cd $(ANDROID_DIR) && ./gradlew assembleDebug
@mkdir -p $(DIST_DIR)
@V="$(VERSION)"; \
if [ -z "$$V" ]; then \
if TAG=$$(git describe --tags --exact-match --match 'v[0-9]*.[0-9]*.[0-9]*' 2>/dev/null); then \
V=$${TAG#v}; \
else \
V="0.0.0-dev+$$(git rev-parse --short HEAD)"; \
echo "WARNING: HEAD is not on a vX.Y.Z tag - building placeholder version $$V (push a tag to drive a real release version)" >&2; \
fi; \
fi; \
case "$$V" in \
[0-9]*.[0-9]*.[0-9]*) ;; \
*) echo "PREFLIGHT FAIL: VERSION '$$V' is not a semantic version (expected X.Y.Z, optionally with a -pre+meta suffix)" >&2; exit 1;; \
esac; \
APK_NAME="fuelish-$$V.apk"; \
cp $(ANDROID_APK) "$(DIST_DIR)/$$APK_NAME"; \
echo "Wrote $(DIST_DIR)/$$APK_NAME"
clean:
rm -rf $(DIST_DIR) $(ANDROID_DIR)/build $(ANDROID_DIR)/app/build
+138 -2
View File
@@ -1,3 +1,139 @@
# gastronomy <p align="center">
<img src="logo.png" width="280" alt="fuelish logo">
</p>
Extracting and organising fuel data from fuel receipts. # fuelish
Extracts structured data from photos of German fuel/petrol receipts —
petrol station, transaction number, date, time, price per litre, litres,
discount, and total price — and lets you review, correct, save, and
export it from an Android app.
The extraction pipeline is self-hosted (no cloud AI APIs): Tesseract OCR
plus a small local LLM (`qwen2.5:3b`, served by Ollama), all running in
containers. It's built to eventually run on a Raspberry Pi 4 cluster
under k3s; see [`AGENT.md`](AGENT.md) for the pipeline's architecture,
preprocessing rationale, and current extraction-accuracy notes.
## How it fits together
- **Pipeline** (`tooling-container/`): preprocess → OCR → LLM-structure a
receipt photo into JSON. Runs either as three independently-inspectable
host scripts (for development/testing) or as an HTTP job API (for the
app).
- **Server** (`docker-compose.yml`): the same pipeline, served over HTTP
(`POST /jobs`, `GET /jobs/{id}`) so the Android app can submit a photo
and poll real per-stage progress, backed by an Ollama container.
- **Android app** (`android/`): take a photo, watch it get processed,
correct any misread fields, save it locally, browse everything saved
so far, and export to CSV or `.ods` (matching the layout of the
ground-truth spreadsheets under `testdata/`).
- **CI** (`.gitea/workflows/build.yml`): builds the Android debug APK on
every push and publishes it to dl.ladkau.de, using a custom build image
(`build-image/`) so the runner needs nothing preinstalled.
## Repository layout
```
tooling-container/ Pipeline source (preprocess.py, ocr.py, extract.py,
server.py, compare_ground_truth.py) and the
Dockerfile/VERSION for the fuelish/tools image
both the host scripts and docker-compose.yml run.
0-3_*.sh Numbered host scripts driving one pipeline stage
each, for independent inspection during
development (0_run_ollama.sh starts Ollama).
test_batch.sh Runs the full pipeline over a directory of test
receipts and compares against its ground-truth
.ods - see AGENT.md's "Current state".
docker-compose.yml Runs the pipeline as a long-lived HTTP job API
(api + ollama services) for the Android app.
android/ The Android app: Kotlin + Jetpack Compose, Room
for local storage, OkHttp against the server API,
CSV/.ods export.
build-image/ Dockerfile for the Android CI/release build
environment (JDK + Android SDK, no NDK needed -
the app has no native code), used by CI and by
the build-image.sh/run-image.sh/upload-image.sh
scripts at the repo root (see "Building" below).
.gitea/workflows/ CI: builds the Android APK and publishes it to
dl.ladkau.de.
Makefile Root Makefile - packages a versioned release APK
(`make android`).
testdata/ Real receipt photos + ground-truth .ods files
(gitignored, not checked in - personal data).
```
See [`AGENT.md`](AGENT.md) for the pipeline's architecture, why the
current preprocessing approach was chosen over heavier alternatives, and
the latest batch-accuracy numbers and known failure modes.
## Building
**The pipeline image** (`tooling-container/`), used by the numbered host
scripts, `test_batch.sh`, and `docker-compose.yml`:
```bash
./build-image.sh # builds fuelish/tools and the Android build-image
# (below), and pulls ollama/ollama
```
**The server**, once the tools image is built:
```bash
docker compose up -d # starts ollama + api; api reachable at :8080
```
**The Android app** (`android/`) needs the Android SDK
(`ANDROID_HOME` set). Locally, without installing it yourself:
```bash
cp registry.env.example registry.env # fill in your registry credentials
./build-image.sh # builds the android-builder image (JDK + Android SDK)
./run-image.sh # runs `make android` inside it, against this
# checkout -> dist/fuelish-<version>.apk
```
With the SDK already installed, `make android` (or
`cd android && ./gradlew assembleDebug`) works directly on the host.
**CI** builds the same way — `.gitea/workflows/build.yml` runs
`make android` inside the `build-image/` image (pulled from the
registry, published via `./upload-image.sh` after `./build-image.sh`)
and publishes the APK to dl.ladkau.de on every push to the default
branch.
## Running
**Inspect the pipeline stage by stage**, for development/debugging one
receipt at a time:
```bash
./0_run_ollama.sh # once, starts Ollama
./1_preprocess_image.sh -in photo.jpg -out scratch/
./2_ocr_image.sh -in scratch/03_final.png -out scratch/
./3_extract_data.sh -in scratch/ocr.txt -out scratch/ # -> extracted.json
```
**Batch-test against ground truth**:
```bash
./test_batch.sh -in testdata/<some-set> # needs a *.ods ground-truth
# file in that directory
```
**Serve it for the app**:
```bash
docker compose up -d
```
Then, in the Android app's Settings tab, point it at
`http://<this-host>:8080` (both HTTP-only - see the app's
`network_security_config.xml` - and LAN-only by design, no auth/TLS).
Take a photo, watch the 4-stage progress (upload → preprocess → OCR →
extract), correct anything the model got wrong, and save. The Receipts
tab lists everything saved so far and exports to CSV or `.ods`.
## License
MIT — see [`LICENSE`](LICENSE).
+79
View File
@@ -0,0 +1,79 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.ksp)
}
android {
namespace = "de.ladkau.fuelish"
compileSdk = 36
defaultConfig {
applicationId = "de.ladkau.fuelish"
minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "0.0.0-dev"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
buildFeatures {
compose = true
}
}
// Compiles with an actual JDK 17 toolchain (auto-provisioned - see
// settings.gradle.kts's foojay-resolver plugin) rather than whatever JDK
// launched Gradle, so it stays in sync with android.compileOptions above
// regardless of which JDK's on PATH.
kotlin {
jvmToolchain(17)
}
// Regenerates app/src/main/res/{mipmap-*,drawable-nodpi}/* from ../../logo.png
// (see scripts/gen_app_icons.py) - gitignored generated output, so a fresh
// checkout needs it produced before any resource-merge/asset-packaging task
// runs.
val generateAppIcons = tasks.register<Exec>("generateAppIcons") {
workingDir = rootDir
commandLine("python3", "scripts/gen_app_icons.py")
}
tasks.named("preBuild") {
dependsOn(generateAppIcons)
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
implementation(libs.androidx.material.icons.core)
implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.core.splashscreen)
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.ktx)
ksp(libs.androidx.room.compiler)
implementation(libs.kotlinx.serialization.json)
implementation(libs.kotlinx.coroutines.android)
implementation(libs.okhttp)
debugImplementation(libs.androidx.ui.tooling)
}
+9
View File
@@ -0,0 +1,9 @@
# kotlinx.serialization needs its generated serializer classes kept.
-keepattributes *Annotation*, InnerClasses
-dontnote kotlinx.serialization.AnnotationsKt
-keepclasseswithmembers class de.ladkau.fuelish.data.** {
*** Companion;
}
-keepclasseswithmembers class de.ladkau.fuelish.data.** {
kotlinx.serialization.KSerializer serializer(...);
}
+39
View File
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<application
android:name=".FuelishApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:networkSecurityConfig="@xml/network_security_config"
android:theme="@style/Theme.Fuelish.Splash">
<activity
android:name=".MainActivity"
android:exported="true"
android:theme="@style/Theme.Fuelish.Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
@@ -0,0 +1,5 @@
package de.ladkau.fuelish
import android.app.Application
class FuelishApplication : Application()
@@ -0,0 +1,22 @@
package de.ladkau.fuelish
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import de.ladkau.fuelish.ui.FuelishApp
import de.ladkau.fuelish.ui.theme.FuelishTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
FuelishTheme {
FuelishApp()
}
}
}
}
@@ -0,0 +1,47 @@
package de.ladkau.fuelish.data
import java.io.File
import java.io.IOException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNamingStrategy
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
/** Talks to tooling-container/src/server.py's two endpoints. Every call
* takes the server's base URL explicitly (from [ConfigRepository]) rather
* than storing it, since the user can change it from Settings mid-session. */
class ApiClient(private val client: OkHttpClient = OkHttpClient()) {
@OptIn(ExperimentalSerializationApi::class)
private val json = Json {
ignoreUnknownKeys = true
namingStrategy = JsonNamingStrategy.SnakeCase
}
suspend fun submitImage(baseUrl: String, imageFile: File): String = withContext(Dispatchers.IO) {
val body = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", imageFile.name, imageFile.asRequestBody("image/jpeg".toMediaType()))
.build()
val request = Request.Builder().url("${baseUrl.trimEnd('/')}/jobs").post(body).build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("upload failed: HTTP ${response.code}")
val text = response.body?.string().orEmpty()
json.decodeFromString(CreateJobResponse.serializer(), text).jobId
}
}
suspend fun getJobStatus(baseUrl: String, jobId: String): JobStatusResponse = withContext(Dispatchers.IO) {
val request = Request.Builder().url("${baseUrl.trimEnd('/')}/jobs/$jobId").get().build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("status check failed: HTTP ${response.code}")
val text = response.body?.string().orEmpty()
json.decodeFromString(JobStatusResponse.serializer(), text)
}
}
}
@@ -0,0 +1,10 @@
package de.ladkau.fuelish.data
/**
* Everything the app needs that isn't a saved receipt: just the fuelish
* server's base URL (e.g. "http://192.168.1.10:8080") right now.
* Persisted via Preferences DataStore, see [ConfigRepository].
*/
data class AppConfig(
val serverUrl: String = "",
)
@@ -0,0 +1,29 @@
package de.ladkau.fuelish.data
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
private val Context.configDataStore: DataStore<Preferences> by preferencesDataStore(name = "fuelish_config")
/** Preferences DataStore-backed persistence for [AppConfig]. */
class ConfigRepository(private val context: Context) {
private object Keys {
val SERVER_URL = stringPreferencesKey("server_url")
}
val config: Flow<AppConfig> = context.configDataStore.data.map { prefs ->
AppConfig(serverUrl = prefs[Keys.SERVER_URL] ?: "")
}
suspend fun save(config: AppConfig) {
context.configDataStore.edit { prefs ->
prefs[Keys.SERVER_URL] = config.serverUrl
}
}
}
@@ -0,0 +1,25 @@
package de.ladkau.fuelish.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Receipt::class], version = 1, exportSchema = false)
abstract class FuelishDatabase : RoomDatabase() {
abstract fun receiptDao(): ReceiptDao
companion object {
@Volatile
private var instance: FuelishDatabase? = null
fun get(context: Context): FuelishDatabase =
instance ?: synchronized(this) {
instance ?: Room.databaseBuilder(
context.applicationContext,
FuelishDatabase::class.java,
"fuelish.db",
).build().also { instance = it }
}
}
}
@@ -0,0 +1,37 @@
package de.ladkau.fuelish.data
import kotlinx.serialization.Serializable
/** Mirrors tooling-container/src/server.py's POST /jobs response. */
@Serializable
data class CreateJobResponse(val jobId: String)
/** Mirrors tooling-container/src/server.py's GET /jobs/{id} response. */
@Serializable
data class JobStatusResponse(
val status: String,
val result: ExtractedReceiptDto? = null,
val error: String? = null,
) {
companion object {
const val STATUS_QUEUED = "queued"
const val STATUS_PREPROCESSING = "preprocessing"
const val STATUS_OCR = "ocr"
const val STATUS_EXTRACTING = "extracting"
const val STATUS_DONE = "done"
const val STATUS_ERROR = "error"
}
}
/** Mirrors tooling-container/src/extract.py's SCHEMA. */
@Serializable
data class ExtractedReceiptDto(
val petrolStation: String? = null,
val transactionNumber: String? = null,
val date: String? = null,
val time: String? = null,
val pricePerLitre: Double? = null,
val litres: Double? = null,
val discount: Double? = null,
val totalPrice: Double? = null,
)
@@ -0,0 +1,27 @@
package de.ladkau.fuelish.data
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* A confirmed receipt, as the user saved it after reviewing the server's
* extraction. This app is the system of record - the server is
* stateless processing only (see docker-compose.yml / server.py).
*/
@Entity(tableName = "receipts")
data class Receipt(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val petrolStation: String?,
val transactionNumber: String?,
/** DD.MM.YYYY, matching testdata/.../benzin_kosten.ods's ground-truth format. */
val date: String?,
/** HH:MM:SS. */
val time: String?,
val pricePerLitre: Double?,
val litres: Double?,
val discount: Double?,
val totalPrice: Double?,
/** content:// or file:// URI of the captured photo, kept for reference - null if unavailable. */
val imageUri: String?,
val createdAtEpochMillis: Long,
)
@@ -0,0 +1,26 @@
package de.ladkau.fuelish.data
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface ReceiptDao {
@Query("SELECT * FROM receipts ORDER BY date DESC, createdAtEpochMillis DESC")
fun observeAll(): Flow<List<Receipt>>
@Query("SELECT * FROM receipts WHERE id = :id")
suspend fun getById(id: Long): Receipt?
@Insert
suspend fun insert(receipt: Receipt): Long
@Update
suspend fun update(receipt: Receipt)
@Delete
suspend fun delete(receipt: Receipt)
}
@@ -0,0 +1,25 @@
package de.ladkau.fuelish.data
import android.content.Context
import java.io.File
import kotlinx.coroutines.flow.Flow
/** Wraps the local Room store (the system of record for confirmed
* receipts) and the [ApiClient] (stateless per-receipt processing) behind
* one entry point for the ui layer. */
class ReceiptRepository(context: Context) {
private val dao = FuelishDatabase.get(context).receiptDao()
private val api = ApiClient()
val receipts: Flow<List<Receipt>> = dao.observeAll()
suspend fun submitImage(baseUrl: String, imageFile: File): String = api.submitImage(baseUrl, imageFile)
suspend fun pollJob(baseUrl: String, jobId: String): JobStatusResponse = api.getJobStatus(baseUrl, jobId)
suspend fun save(receipt: Receipt): Long = dao.insert(receipt)
suspend fun update(receipt: Receipt) = dao.update(receipt)
suspend fun delete(receipt: Receipt) = dao.delete(receipt)
}
@@ -0,0 +1,28 @@
package de.ladkau.fuelish.export
import de.ladkau.fuelish.data.Receipt
import java.io.OutputStream
/** ";"-delimited, not ",": our cells use a German decimal comma (see
* [toExportRow]), which would otherwise collide with a comma delimiter -
* ";" is also what German-locale Excel/LibreOffice expect by default. */
private const val DELIMITER = ";"
private val UTF8_BOM = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte())
fun exportCsv(receipts: List<Receipt>, out: OutputStream) {
out.write(UTF8_BOM)
out.write(csvLine(EXPORT_HEADERS).toByteArray(Charsets.UTF_8))
for (receipt in receipts) {
out.write(csvLine(receipt.toExportRow()).toByteArray(Charsets.UTF_8))
}
}
private fun csvLine(fields: List<String>): String =
fields.joinToString(DELIMITER) { escapeCsvField(it) } + "\r\n"
private fun escapeCsvField(field: String): String =
if (field.contains(DELIMITER) || field.contains('"') || field.contains('\n')) {
"\"" + field.replace("\"", "\"\"") + "\""
} else {
field
}
@@ -0,0 +1,92 @@
package de.ladkau.fuelish.export
import de.ladkau.fuelish.data.Receipt
import java.io.OutputStream
import java.util.zip.CRC32
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
private const val MIMETYPE = "application/vnd.oasis.opendocument.spreadsheet"
/**
* A minimal hand-rolled ODF spreadsheet writer - no dependency needed,
* since an .ods is just a zip of a few fixed XML files. Writes only what
* testdata/.../benzin_kosten.ods's own reader (compare_ground_truth.py,
* via odfpy) needs: one table, string-typed cells (matching how that
* ground-truth sheet itself stores formatted values - see
* [toExportRow]'s doc comment), no styles/formulas.
*/
fun exportOds(receipts: List<Receipt>, out: OutputStream) {
ZipOutputStream(out).use { zip ->
// Must be the first entry, stored uncompressed with no extra
// fields, so ODF-aware tools can sniff the file type without
// inflating - the format spec requires this.
val mimetypeBytes = MIMETYPE.toByteArray(Charsets.US_ASCII)
val mimetypeEntry = ZipEntry("mimetype").apply {
method = ZipEntry.STORED
size = mimetypeBytes.size.toLong()
compressedSize = mimetypeBytes.size.toLong()
crc = CRC32().apply { update(mimetypeBytes) }.value
}
zip.putNextEntry(mimetypeEntry)
zip.write(mimetypeBytes)
zip.closeEntry()
zip.putNextEntry(ZipEntry("META-INF/manifest.xml"))
zip.write(manifestXml().toByteArray(Charsets.UTF_8))
zip.closeEntry()
zip.putNextEntry(ZipEntry("content.xml"))
zip.write(contentXml(receipts).toByteArray(Charsets.UTF_8))
zip.closeEntry()
}
}
private fun manifestXml(): String = """
<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">
<manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="$MIMETYPE"/>
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
</manifest:manifest>
""".trimIndent()
private fun contentXml(receipts: List<Receipt>): String {
val rows = buildString {
append(tableRow(EXPORT_HEADERS))
for (receipt in receipts) {
append(tableRow(receipt.toExportRow()))
}
}
return """
<?xml version="1.0" encoding="UTF-8"?>
<office:document-content
xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
office:version="1.2">
<office:body>
<office:spreadsheet>
<table:table table:name="Receipts">
$rows
</table:table>
</office:spreadsheet>
</office:body>
</office:document-content>
""".trimIndent()
}
private fun tableRow(cells: List<String>): String = buildString {
append("<table:table-row>")
for (cell in cells) {
append("<table:table-cell office:value-type=\"string\"><text:p>")
append(escapeXml(cell))
append("</text:p></table:table-cell>")
}
append("</table:table-row>")
}
private fun escapeXml(text: String): String = text
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
@@ -0,0 +1,29 @@
package de.ladkau.fuelish.export
import de.ladkau.fuelish.data.Receipt
import java.util.Locale
/**
* The first 6 columns mirror testdata/.../benzin_kosten.ods's layout
* exactly (date, time, price_per_litre, litres, discount, total_price -
* see tooling-container/src/compare_ground_truth.py's column order and
* its German-locale decimal-comma / "€"-suffix parsing, which this
* reproduces on the way out). petrol_station/transaction_number are
* appended as extra trailing columns - present in this app's data but
* not in the original ground-truth sheet.
*/
val EXPORT_HEADERS = listOf(
"Datum", "Uhrzeit", "Preis/Liter", "Liter", "Rabatt", "Gesamtpreis",
"Tankstelle", "Transaktionsnummer",
)
fun Receipt.toExportRow(): List<String> = listOf(
date.orEmpty(),
time.orEmpty(),
pricePerLitre?.let { String.format(Locale.GERMANY, "%.3f", it) }.orEmpty(),
litres?.let { String.format(Locale.GERMANY, "%.2f", it) }.orEmpty(),
discount?.let { String.format(Locale.GERMANY, "%.2f €", it) }.orEmpty(),
totalPrice?.let { String.format(Locale.GERMANY, "%.2f €", it) }.orEmpty(),
petrolStation.orEmpty(),
transactionNumber.orEmpty(),
)
@@ -0,0 +1,105 @@
package de.ladkau.fuelish.ui
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import de.ladkau.fuelish.R
import de.ladkau.fuelish.ui.capture.CaptureScreen
import de.ladkau.fuelish.ui.overview.OverviewScreen
import de.ladkau.fuelish.ui.settings.ConfigScreen
import kotlinx.coroutines.launch
private object Destinations {
const val CAPTURE = "capture"
const val OVERVIEW = "overview"
const val SETTINGS = "settings"
}
/** Burger menu = ModalNavigationDrawer, leading to Scan/Receipts/Settings -
* the app's single navigation host. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FuelishApp() {
val navController = rememberNavController()
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
val currentRoute = navController.currentBackStackEntryAsState().value?.destination?.route
ModalNavigationDrawer(
drawerState = drawerState,
drawerContent = {
ModalDrawerSheet {
NavigationDrawerItem(
label = { Text(stringResource(R.string.nav_capture)) },
selected = currentRoute == Destinations.CAPTURE,
onClick = { navigateTo(navController, Destinations.CAPTURE); scope.launch { drawerState.close() } },
modifier = Modifier.padding(horizontal = 12.dp),
)
NavigationDrawerItem(
label = { Text(stringResource(R.string.nav_overview)) },
selected = currentRoute == Destinations.OVERVIEW,
onClick = { navigateTo(navController, Destinations.OVERVIEW); scope.launch { drawerState.close() } },
modifier = Modifier.padding(horizontal = 12.dp),
)
NavigationDrawerItem(
label = { Text(stringResource(R.string.nav_settings)) },
selected = currentRoute == Destinations.SETTINGS,
onClick = { navigateTo(navController, Destinations.SETTINGS); scope.launch { drawerState.close() } },
modifier = Modifier.padding(horizontal = 12.dp),
)
}
},
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.app_name)) },
navigationIcon = {
IconButton(onClick = { scope.launch { drawerState.open() } }) {
Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.nav_settings))
}
},
)
},
) { innerPadding ->
NavHost(
navController = navController,
startDestination = Destinations.CAPTURE,
modifier = Modifier.padding(innerPadding),
) {
composable(Destinations.CAPTURE) { CaptureScreen() }
composable(Destinations.OVERVIEW) { OverviewScreen() }
composable(Destinations.SETTINGS) { ConfigScreen() }
}
}
}
}
private fun navigateTo(navController: NavHostController, route: String) {
navController.navigate(route) {
popUpTo(navController.graph.startDestinationId) { saveState = true }
launchSingleTop = true
restoreState = true
}
}
@@ -0,0 +1,170 @@
package de.ladkau.fuelish.ui.capture
import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import de.ladkau.fuelish.R
import de.ladkau.fuelish.data.ExtractedReceiptDto
import de.ladkau.fuelish.data.JobStatusResponse
import java.io.File
@Composable
fun CaptureScreen(viewModel: CaptureViewModel = viewModel()) {
val uiState by viewModel.uiState.collectAsState()
val context = LocalContext.current
var pendingFile by remember { mutableStateOf<File?>(null) }
var pendingUri by remember { mutableStateOf<Uri?>(null) }
val takePictureLauncher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { success ->
val file = pendingFile
val uri = pendingUri
if (success && file != null && uri != null) {
viewModel.submit(file, uri)
}
}
fun launchCamera() {
val dir = File(context.cacheDir, "captures").apply { mkdirs() }
val file = File(dir, "capture-${System.currentTimeMillis()}.jpg")
val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
pendingFile = file
pendingUri = uri
takePictureLauncher.launch(uri)
}
val cameraPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) launchCamera()
}
Box(modifier = Modifier.fillMaxSize().padding(16.dp)) {
when (val state = uiState) {
is CaptureUiState.Idle -> Button(
onClick = {
val hasPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
if (hasPermission) launchCamera() else cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
},
) {
Text(stringResource(R.string.capture_take_photo))
}
is CaptureUiState.Uploading -> ProgressStage(stringResource(R.string.capture_stage_uploading), 0.2f)
is CaptureUiState.Processing -> {
val (labelRes, progress) = when (state.stage) {
JobStatusResponse.STATUS_PREPROCESSING -> R.string.capture_stage_preprocessing to 0.45f
JobStatusResponse.STATUS_OCR -> R.string.capture_stage_ocr to 0.7f
JobStatusResponse.STATUS_EXTRACTING -> R.string.capture_stage_extracting to 0.9f
else -> R.string.capture_stage_uploading to 0.2f
}
ProgressStage(stringResource(labelRes), progress)
}
is CaptureUiState.Editing -> EditForm(draft = state.draft, onSave = { viewModel.save(it) })
is CaptureUiState.Error -> Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(R.string.capture_stage_error, state.message))
Button(onClick = { viewModel.reset() }) { Text(stringResource(R.string.capture_retry)) }
}
}
}
}
@Composable
private fun ProgressStage(label: String, progress: Float) {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(label)
LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth())
}
}
@Composable
private fun EditForm(draft: ExtractedReceiptDto, onSave: (ExtractedReceiptDto) -> Unit) {
var petrolStation by remember { mutableStateOf(draft.petrolStation.orEmpty()) }
var transactionNumber by remember { mutableStateOf(draft.transactionNumber.orEmpty()) }
var date by remember { mutableStateOf(draft.date.orEmpty()) }
var time by remember { mutableStateOf(draft.time.orEmpty()) }
var pricePerLitre by remember { mutableStateOf(draft.pricePerLitre?.toString().orEmpty()) }
var litres by remember { mutableStateOf(draft.litres?.toString().orEmpty()) }
var discount by remember { mutableStateOf(draft.discount?.toString().orEmpty()) }
var totalPrice by remember { mutableStateOf(draft.totalPrice?.toString().orEmpty()) }
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
LabeledField(R.string.capture_field_petrol_station, petrolStation) { petrolStation = it }
LabeledField(R.string.capture_field_transaction_number, transactionNumber) { transactionNumber = it }
LabeledField(R.string.capture_field_date, date) { date = it }
LabeledField(R.string.capture_field_time, time) { time = it }
LabeledField(R.string.capture_field_price_per_litre, pricePerLitre) { pricePerLitre = it }
LabeledField(R.string.capture_field_litres, litres) { litres = it }
LabeledField(R.string.capture_field_discount, discount) { discount = it }
LabeledField(R.string.capture_field_total_price, totalPrice) { totalPrice = it }
Button(
onClick = {
onSave(
ExtractedReceiptDto(
petrolStation = petrolStation.ifBlank { null },
transactionNumber = transactionNumber.ifBlank { null },
date = date.ifBlank { null },
time = time.ifBlank { null },
pricePerLitre = pricePerLitre.toDoubleOrNull(),
litres = litres.toDoubleOrNull(),
discount = discount.toDoubleOrNull(),
totalPrice = totalPrice.toDoubleOrNull(),
),
)
},
modifier = Modifier.align(Alignment.End),
) {
Text(stringResource(R.string.capture_save))
}
}
}
@Composable
private fun LabeledField(labelRes: Int, value: String, onValueChange: (String) -> Unit) {
OutlinedTextField(
value = value,
onValueChange = onValueChange,
label = { Text(stringResource(labelRes)) },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
}
@@ -0,0 +1,14 @@
package de.ladkau.fuelish.ui.capture
import de.ladkau.fuelish.data.ExtractedReceiptDto
sealed interface CaptureUiState {
data object Idle : CaptureUiState
data object Uploading : CaptureUiState
/** [stage] is one of JobStatusResponse's STATUS_* constants (preprocessing/ocr/extracting). */
data class Processing(val stage: String) : CaptureUiState
data class Editing(val draft: ExtractedReceiptDto) : CaptureUiState
data class Error(val message: String) : CaptureUiState
}
@@ -0,0 +1,96 @@
package de.ladkau.fuelish.ui.capture
import android.app.Application
import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.ladkau.fuelish.data.ConfigRepository
import de.ladkau.fuelish.data.ExtractedReceiptDto
import de.ladkau.fuelish.data.JobStatusResponse
import de.ladkau.fuelish.data.Receipt
import de.ladkau.fuelish.data.ReceiptRepository
import java.io.File
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
private const val POLL_INTERVAL_MILLIS = 1_500L
class CaptureViewModel(application: Application) : AndroidViewModel(application) {
private val repository = ReceiptRepository(application)
private val configRepository = ConfigRepository(application)
private val _uiState = MutableStateFlow<CaptureUiState>(CaptureUiState.Idle)
val uiState: StateFlow<CaptureUiState> = _uiState.asStateFlow()
// The captured photo's local URI, kept alongside the receipt once saved
// (see Receipt.imageUri) - set right before submit(), cleared on save()/reset().
private var pendingImageUri: Uri? = null
fun submit(imageFile: File, imageUri: Uri) {
pendingImageUri = imageUri
viewModelScope.launch {
_uiState.value = CaptureUiState.Uploading
try {
val baseUrl = configRepository.config.first().serverUrl
if (baseUrl.isBlank()) {
_uiState.value = CaptureUiState.Error("Set the server URL in Settings first")
return@launch
}
val jobId = repository.submitImage(baseUrl, imageFile)
pollUntilDone(baseUrl, jobId)
} catch (e: Exception) {
_uiState.value = CaptureUiState.Error(e.message ?: "unknown error")
}
}
}
private suspend fun pollUntilDone(baseUrl: String, jobId: String) {
while (true) {
val status = repository.pollJob(baseUrl, jobId)
when (status.status) {
JobStatusResponse.STATUS_DONE -> {
_uiState.value = CaptureUiState.Editing(status.result ?: ExtractedReceiptDto())
return
}
JobStatusResponse.STATUS_ERROR -> {
_uiState.value = CaptureUiState.Error(status.error ?: "processing failed")
return
}
else -> {
_uiState.value = CaptureUiState.Processing(status.status)
delay(POLL_INTERVAL_MILLIS)
}
}
}
}
fun save(draft: ExtractedReceiptDto) {
viewModelScope.launch {
repository.save(
Receipt(
petrolStation = draft.petrolStation,
transactionNumber = draft.transactionNumber,
date = draft.date,
time = draft.time,
pricePerLitre = draft.pricePerLitre,
litres = draft.litres,
discount = draft.discount,
totalPrice = draft.totalPrice,
imageUri = pendingImageUri?.toString(),
createdAtEpochMillis = System.currentTimeMillis(),
),
)
pendingImageUri = null
_uiState.value = CaptureUiState.Idle
}
}
fun reset() {
pendingImageUri = null
_uiState.value = CaptureUiState.Idle
}
}
@@ -0,0 +1,93 @@
package de.ladkau.fuelish.ui.overview
import android.content.Intent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import de.ladkau.fuelish.R
import de.ladkau.fuelish.data.Receipt
@Composable
fun OverviewScreen(viewModel: OverviewViewModel = viewModel()) {
val receipts by viewModel.receipts.collectAsState()
val context = LocalContext.current
Column(modifier = Modifier.fillMaxSize()) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Button(onClick = { viewModel.exportCsv { uri -> shareFile(context, uri, "text/csv") } }) {
Text(stringResource(R.string.overview_export_csv))
}
Button(onClick = { viewModel.exportOds { uri -> shareFile(context, uri, "application/vnd.oasis.opendocument.spreadsheet") } }) {
Text(stringResource(R.string.overview_export_ods))
}
}
if (receipts.isEmpty()) {
Text(
text = stringResource(R.string.overview_empty),
modifier = Modifier.padding(16.dp),
)
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(receipts, key = { it.id }) { receipt ->
ReceiptRow(receipt = receipt, onDelete = { viewModel.delete(receipt) })
HorizontalDivider()
}
}
}
}
}
@Composable
private fun ReceiptRow(receipt: Receipt, onDelete: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column {
Text(text = receipt.date.orEmpty())
Text(text = listOfNotNull(receipt.petrolStation, receipt.totalPrice?.let { "%.2f €".format(it) }).joinToString(" · "))
}
IconButton(onClick = onDelete) {
Icon(Icons.Filled.Delete, contentDescription = null)
}
}
}
private fun shareFile(context: android.content.Context, uri: android.net.Uri, mimeType: String) {
val intent = Intent(Intent.ACTION_SEND).apply {
type = mimeType
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(Intent.createChooser(intent, null))
}
@@ -0,0 +1,46 @@
package de.ladkau.fuelish.ui.overview
import android.app.Application
import android.net.Uri
import androidx.core.content.FileProvider
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.ladkau.fuelish.data.Receipt
import de.ladkau.fuelish.data.ReceiptRepository
import de.ladkau.fuelish.export.exportCsv as writeCsvRows
import de.ladkau.fuelish.export.exportOds as writeOdsRows
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class OverviewViewModel(application: Application) : AndroidViewModel(application) {
private val repository = ReceiptRepository(application)
val receipts: StateFlow<List<Receipt>> = repository.receipts
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
fun delete(receipt: Receipt) {
viewModelScope.launch { repository.delete(receipt) }
}
fun exportCsv(onReady: (Uri) -> Unit) = export("fuelish-receipts.csv", ::writeCsvRows, onReady)
fun exportOds(onReady: (Uri) -> Unit) = export("fuelish-receipts.ods", ::writeOdsRows, onReady)
private fun export(fileName: String, write: (List<Receipt>, java.io.OutputStream) -> Unit, onReady: (Uri) -> Unit) {
val app = getApplication<Application>()
viewModelScope.launch {
val uri = withContext(Dispatchers.IO) {
val dir = File(app.cacheDir, "exports").apply { mkdirs() }
val file = File(dir, fileName)
file.outputStream().use { write(receipts.value, it) }
FileProvider.getUriForFile(app, "${app.packageName}.fileprovider", file)
}
onReady(uri)
}
}
}
@@ -0,0 +1,42 @@
package de.ladkau.fuelish.ui.settings
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import de.ladkau.fuelish.R
@Composable
fun ConfigScreen(viewModel: ConfigViewModel = viewModel()) {
val config by viewModel.config.collectAsState()
val isDirty by viewModel.isDirty.collectAsState()
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
OutlinedTextField(
value = config.serverUrl,
onValueChange = { viewModel.update { c -> c.copy(serverUrl = it) } },
label = { Text(stringResource(R.string.settings_server_url)) },
placeholder = { Text(stringResource(R.string.settings_server_url_hint)) },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
Button(onClick = { viewModel.save() }, enabled = isDirty) {
Text(stringResource(R.string.capture_save))
}
}
}
@@ -0,0 +1,51 @@
package de.ladkau.fuelish.ui.settings
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.ladkau.fuelish.data.AppConfig
import de.ladkau.fuelish.data.ConfigRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
class ConfigViewModel(application: Application) : AndroidViewModel(application) {
private val configRepository = ConfigRepository(application)
// A local editable draft, seeded once from the persisted config below -
// deliberately not a live collection of configRepository.config, so
// in-progress edits aren't clobbered by DataStore's own emission of the
// write this same screen is about to make on save().
private val _config = MutableStateFlow(AppConfig())
val config: StateFlow<AppConfig> = _config.asStateFlow()
private val _savedConfig = MutableStateFlow(AppConfig())
val isDirty: StateFlow<Boolean> = combine(_config, _savedConfig) { draft, saved -> draft != saved }
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
init {
viewModelScope.launch {
val loaded = configRepository.config.first()
_config.value = loaded
_savedConfig.value = loaded
}
}
fun update(transform: (AppConfig) -> AppConfig) {
_config.value = transform(_config.value)
}
fun save() {
viewModelScope.launch {
val toSave = _config.value
configRepository.save(toSave)
_savedConfig.value = toSave
}
}
}
@@ -0,0 +1,30 @@
package de.ladkau.fuelish.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val LightColors = lightColorScheme()
private val DarkColors = darkColorScheme()
@Composable
fun FuelishTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
) {
val context = LocalContext.current
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
darkTheme -> DarkColors
else -> LightColors
}
MaterialTheme(colorScheme = colorScheme, content = content)
}
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Matches the white background baked into logo.png, so the
generated launcher icon / splash screen sit on the same
background the source art was designed against. -->
<color name="ic_launcher_background">#FFFFFF</color>
<color name="splash_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">fuelish</string>
<string name="nav_capture">Scan receipt</string>
<string name="nav_overview">Receipts</string>
<string name="nav_settings">Settings</string>
<string name="capture_take_photo">Take photo</string>
<string name="capture_stage_uploading">Uploading…</string>
<string name="capture_stage_preprocessing">Preprocessing image…</string>
<string name="capture_stage_ocr">Reading text (OCR)…</string>
<string name="capture_stage_extracting">Extracting fields…</string>
<string name="capture_stage_error">Something went wrong: %1$s</string>
<string name="capture_retry">Retry</string>
<string name="capture_save">Save</string>
<string name="capture_field_petrol_station">Petrol station</string>
<string name="capture_field_transaction_number">Transaction number</string>
<string name="capture_field_date">Date (DD.MM.YYYY)</string>
<string name="capture_field_time">Time (HH:MM:SS)</string>
<string name="capture_field_price_per_litre">Price per litre</string>
<string name="capture_field_litres">Litres</string>
<string name="capture_field_discount">Discount</string>
<string name="capture_field_total_price">Total price</string>
<string name="overview_empty">No receipts saved yet</string>
<string name="overview_export_csv">Export CSV</string>
<string name="overview_export_ods">Export ODS</string>
<string name="overview_export_done">Exported to %1$s</string>
<string name="settings_server_url">Server URL</string>
<string name="settings_server_url_hint">http://192.168.1.10:8080</string>
</resources>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Fuelish" parent="android:Theme.Material.Light.NoActionBar" />
<style name="Theme.Fuelish.Splash" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/splash_background</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
<item name="postSplashScreenTheme">@style/Theme.Fuelish</item>
</style>
</resources>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Where the FileProvider (see AndroidManifest.xml) is allowed to serve
content:// URIs from. Captured receipt photos are written to the
cache dir by CaptureScreen before being handed to the camera intent
and then uploaded - see ui/capture/CaptureViewModel.kt. -->
<paths>
<cache-path name="captures" path="captures/" />
<!-- Exported CSV/ODS files (see export/CsvExporter.kt, OdsExporter.kt),
shared out via an ACTION_SEND intent - see
ui/overview/OverviewViewModel.kt. -->
<cache-path name="exports" path="exports/" />
</paths>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- fuelish talks to a self-hosted, LAN-only server with no TLS (see
AGENT.md / the server plan - auth and TLS are an explicit v1
non-goal for a personal LAN tool). Android's network security config
has no CIDR-range matcher, only literal domains/IPs, so rather than
enumerate private-range addresses we allow cleartext globally; the
app never talks to anything but the server URL the user enters in
Settings. -->
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
+6
View File
@@ -0,0 +1,6 @@
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.serialization) apply false
alias(libs.plugins.kotlin.compose) apply false
alias(libs.plugins.ksp) apply false
}
+11
View File
@@ -0,0 +1,11 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
kotlin.code.style=official
ksp.useKSP2=true
# AGP 9's built-in Kotlin support rejects KSP's use of the kotlin.sourceSets
# DSL to register generated-source dirs (Room's annotation processor, via
# KSP) - this is AGP/KSP's own suggested suppression, not a workaround for
# anything we did. See https://developer.android.com/r/tools/built-in-kotlin
android.disallowKotlinSourceSets=false
+56
View File
@@ -0,0 +1,56 @@
[versions]
# Version-lookup tools (WebFetch/registry browsing) were unavailable while
# this file was written, so these are last-known-good pins rather than a
# freshly verified "latest stable" snapshot - if Gradle can't resolve one,
# bump it to whatever's current on Google's Maven / Maven Central.
#
# kotlin/ksp are pinned to 2.3.x rather than 2.2.20: androidx.room:
# room-common-jvm:2.8.5 declares a `{strictly 2.3.20}` constraint on
# kotlin-stdlib, which would otherwise silently resolve above what a
# 2.2.20 compiler/KSP understands. Keep these two in sync if Room is ever
# bumped further.
agp = "9.2.1"
kotlin = "2.3.20"
# KSP's versioning stopped mirroring Kotlin's exact patch after the 2.3.0
# line (no "2.3.20" KSP release exists) - 2.3.12 is the latest in the same
# 2.3.x line as kotlin above.
ksp = "2.3.12"
coreKtx = "1.17.0"
lifecycleRuntimeKtx = "2.9.4"
activityCompose = "1.13.0"
composeBom = "2026.06.01"
navigationCompose = "2.9.8"
datastorePreferences = "1.2.1"
kotlinxSerializationJson = "1.11.0"
kotlinxCoroutines = "1.11.0"
room = "2.8.5"
splashscreen = "1.0.1"
okhttp = "4.12.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleRuntimeKtx" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-material-icons-core = { group = "androidx.compose.material", name = "material-icons-core" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" }
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
androidx-core-splashscreen = { group = "androidx.core", name = "core-splashscreen", version.ref = "splashscreen" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+82
View File
@@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Generates the Android launcher icon and splash screen art from
../../logo.png (the repo's brand mark + "fuelish" wordmark).
Only the graphic mark (not the wordmark) works as a launcher/splash icon,
so this first isolates it: crop the upper portion of the source image
(where the mark lives) and auto-crop that to its actual non-transparent
bounding box, rather than relying on any hardcoded pixel offsets that
would break if logo.png is ever redrawn at a different resolution.
Produces:
- mipmap-<density>/ic_launcher_foreground.png - the mark centered, scaled
to the adaptive-icon safe zone (66% of a 108dp canvas), transparent
background - paired at runtime with @color/ic_launcher_background (see
mipmap-anydpi-v26/ic_launcher.xml, committed - a static reference, not
generated) for API 26+.
- mipmap-<density>/ic_launcher.png / ic_launcher_round.png - the same
mark flattened onto ic_launcher_background, for API <26 devices that
can't use the adaptive-icon XML at all.
- drawable-nodpi/splash_icon.png - the mark on a transparent background,
referenced by Theme.Fuelish.Splash's windowSplashScreenAnimatedIcon
(see values/themes.xml).
Generated output, not committed (see the repo's root .gitignore's
/android/app/src/main/res/{mipmap-*,drawable-nodpi} entries) - regenerate
by running this script directly or via Gradle's generateAppIcons task
(wired into app's preBuild, see ../app/build.gradle.kts). Requires
Pillow.
"""
import os
import sys
from PIL import Image
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
LOGO_PATH = os.path.normpath(os.path.join(SCRIPT_DIR, "..", "..", "logo.png"))
RES_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, "..", "app", "src", "main", "res"))
BACKGROUND_RGBA = (255, 255, 255, 255) # matches @color/ic_launcher_background
# (density qualifier, adaptive-icon canvas px, legacy launcher px)
DENSITIES = [
("mdpi", 108, 48),
("hdpi", 162, 72),
("xhdpi", 216, 96),
("xxhdpi", 324, 144),
("xxxhdpi", 432, 192),
]
# Adaptive icons render only the inner ~66% "safe zone" reliably across
# launchers that apply their own mask shape.
SAFE_ZONE_RATIO = 0.66
# Fraction of logo.png's height (from the top) that contains the graphic
# mark, before the "fuelish" wordmark begins.
MARK_REGION_HEIGHT_RATIO = 0.60
SPLASH_CANVAS_PX = 480
SPLASH_ICON_RATIO = 0.75
def extract_mark(logo: Image.Image) -> Image.Image:
width, height = logo.size
region = logo.crop((0, 0, width, round(height * MARK_REGION_HEIGHT_RATIO)))
bbox = region.getchannel("A").getbbox()
if bbox is None:
raise ValueError(f"{LOGO_PATH}: no non-transparent pixels found in the top "
f"{MARK_REGION_HEIGHT_RATIO:.0%} of the image")
mark = region.crop(bbox)
# Pad to square so downstream scaling doesn't distort the aspect ratio.
side = max(mark.width, mark.height)
square = Image.new("RGBA", (side, side), (0, 0, 0, 0))
square.paste(mark, ((side - mark.width) // 2, (side - mark.height) // 2), mark)
return square
def resized(image: Image.Image, target_px: int) -> Image.Image:
ratio = target_px / max(image.width, image.height)
size = (round(image.width * ratio), round(image.height * ratio))
return image.resize(size, Image.LANCZOS)
def centered_on(canvas_px: int, content: Image.Image, background: tuple) -> Image.Image:
canvas = Image.new("RGBA", (canvas_px, canvas_px), background)
offset = ((canvas_px - content.width) // 2, (canvas_px - content.height) // 2)
canvas.paste(content, offset, content)
return canvas
def main():
logo = Image.open(LOGO_PATH).convert("RGBA")
mark = extract_mark(logo)
for density, canvas_px, legacy_px in DENSITIES:
mipmap_dir = os.path.join(RES_DIR, f"mipmap-{density}")
os.makedirs(mipmap_dir, exist_ok=True)
foreground = centered_on(canvas_px, resized(mark, round(canvas_px * SAFE_ZONE_RATIO)), (0, 0, 0, 0))
foreground.save(os.path.join(mipmap_dir, "ic_launcher_foreground.png"))
legacy = centered_on(legacy_px, resized(mark, round(legacy_px * SAFE_ZONE_RATIO)), BACKGROUND_RGBA)
legacy.convert("RGB").save(os.path.join(mipmap_dir, "ic_launcher.png"))
legacy.convert("RGB").save(os.path.join(mipmap_dir, "ic_launcher_round.png"))
drawable_dir = os.path.join(RES_DIR, "drawable-nodpi")
os.makedirs(drawable_dir, exist_ok=True)
splash = centered_on(SPLASH_CANVAS_PX, resized(mark, round(SPLASH_CANVAS_PX * SPLASH_ICON_RATIO)), (0, 0, 0, 0))
splash.save(os.path.join(drawable_dir, "splash_icon.png"))
print(f"wrote launcher icons for {len(DENSITIES)} densities + splash icon to {RES_DIR}", file=sys.stderr)
if __name__ == "__main__":
main()
+26
View File
@@ -0,0 +1,26 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
// Auto-provisions the JDK 17 toolchain app/build.gradle.kts requests (see
// its jvmToolchain(17) call) - this host's only JDKs otherwise are system
// JDK 11 (too old for AGP 9) and Android Studio's bundled JBR 25 (newer
// than Kotlin's compiler officially targets yet).
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "fuelish-android"
include(":app")
Executable
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Builds every image this repo's pipeline/CI needs: the fuelish tools
# image (tooling-container/Dockerfile) and the Android CI/release build
# image (build-image/Dockerfile), each tagged from its own VERSION file,
# plus pulls ollama/ollama (used by 0_run_ollama.sh). Does not push - test
# the tools image with the numbered pipeline scripts and the
# android-builder image with ./run-image.sh, then publish both with
# ./upload-image.sh.
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(pwd)"
fail() { echo "PREFLIGHT FAIL: $*" >&2; exit 1; }
command -v docker >/dev/null 2>&1 \
|| fail "docker not found in PATH"
TOOLS_IMAGE="${REGISTRY_IMAGE:-fuelish/tools}"
ANDROID_IMAGE="${REGISTRY_ANDROID_IMAGE:-cr.ladkau.de/fuelish/android-builder}"
if [ -f "$ROOT/registry.env" ]; then
# shellcheck disable=SC1091
source "$ROOT/registry.env"
TOOLS_IMAGE="${REGISTRY_IMAGE:-$TOOLS_IMAGE}"
ANDROID_IMAGE="${REGISTRY_ANDROID_IMAGE:-$ANDROID_IMAGE}"
fi
TOOLS_VERSION="$(<"$ROOT/tooling-container/VERSION")"
[ -n "$TOOLS_VERSION" ] || fail "tooling-container/VERSION is empty"
ANDROID_VERSION="$(<"$ROOT/build-image/VERSION")"
[ -n "$ANDROID_VERSION" ] || fail "build-image/VERSION is empty"
echo "== Building $TOOLS_IMAGE:$TOOLS_VERSION =="
docker build \
-f "$ROOT/tooling-container/Dockerfile" \
-t "$TOOLS_IMAGE:$TOOLS_VERSION" \
-t "$TOOLS_IMAGE:latest" \
"$ROOT/tooling-container"
echo "== Building $ANDROID_IMAGE:$ANDROID_VERSION =="
docker build \
-t "$ANDROID_IMAGE:$ANDROID_VERSION" \
-t "$ANDROID_IMAGE:latest" \
"$ROOT/build-image"
echo "== Pulling ollama/ollama (used by 0_run_ollama.sh) =="
docker pull ollama/ollama
echo "== Done =="
echo "Images: $TOOLS_IMAGE:$TOOLS_VERSION, $ANDROID_IMAGE:$ANDROID_VERSION (both also :latest)"
echo "Test the tools image with the numbered pipeline scripts, the android-builder image with ./run-image.sh, then publish both with ./upload-image.sh"
+73
View File
@@ -0,0 +1,73 @@
# Build environment for the Android app (android/): JDK + Android SDK
# cmdline-tools, pinned to the versions validated on the maintainer's dev
# machine (matching android/app/build.gradle.kts's compileSdk). Used both
# by .gitea/workflows/build.yml's CI container and by ../run-image.sh for
# a local, CI-equivalent build. Rebuild with ../build-image.sh whenever a
# version below changes.
#
# fuelish's Android app has no native/NDK code, so unlike a build image
# that also needs an NDK/CMake toolchain, this is just a JDK + the SDK's
# own cmdline-tools/platform/build-tools.
#
# Does NOT contain any secrets - registry/SFTP credentials are injected
# at job runtime from Gitea Actions secrets, never baked into this image.
FROM ubuntu:24.04
ARG NODE_VERSION=24.16.0
ARG ANDROID_CMDLINE_TOOLS_VERSION=9862592
ARG ANDROID_PLATFORM_VERSION=36
ARG ANDROID_BUILD_TOOLS_VERSION=36.0.0
ENV DEBIAN_FRONTEND=noninteractive
# openjdk-17-jdk-headless: Gradle/AGP's own minimum JDK (see
# android/app/build.gradle.kts's compileOptions).
# make: the root Makefile's `android` target (run by both run-image.sh
# and .gitea/workflows/build.yml).
# python3/python3-pil: android/scripts/gen_app_icons.py's Pillow
# dependency (see android/app/build.gradle.kts's generateAppIcons
# preBuild task) - apt's python3-pil is used instead of pip/venv since
# nothing else in this image needs a Python environment.
# git/curl/ca-certificates/unzip/xz-utils: checkout and SDK/Node tool
# downloads (xz-utils: Node's release tarball below is .tar.xz).
# openssh-client: the build workflow's `sftp` publish to dl.ladkau.de.
RUN apt-get update && apt-get install -y --no-install-recommends \
openjdk-17-jdk-headless make python3 python3-pil \
git curl ca-certificates unzip xz-utils openssh-client \
&& rm -rf /var/lib/apt/lists/*
# Node.js: actions/checkout@v4 and actions/upload-artifact@v3 (used by
# .gitea/workflows/build.yml) are both JS actions - Gitea's act_runner
# execs them with whatever `node` is on this image's PATH rather than
# injecting one itself (https://github.com/nektos/act/issues/107), and
# this base image doesn't bring one.
RUN curl -sSL -o /tmp/node.tar.xz \
"https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" \
&& tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1 \
&& rm /tmp/node.tar.xz
# Android SDK: the cmdline-tools' own sdkmanager installs exactly the
# platform/build-tools version android/app/build.gradle.kts pins -
# resolved here so no `docker run` of this image needs network access to
# install anything before `./gradlew assembleDebug` works. The Gradle
# build itself still needs network access at build time (Gradle/AGP/
# androidx dependency resolution against Google's Maven + Maven Central) -
# android/gradlew resolves its own pinned Gradle version, no Gradle
# binary is baked into this image.
ENV ANDROID_HOME=/opt/android-sdk \
ANDROID_SDK_ROOT=/opt/android-sdk
ENV PATH=${ANDROID_HOME}/cmdline-tools/latest/bin:${ANDROID_HOME}/platform-tools:${PATH}
RUN mkdir -p "${ANDROID_HOME}/cmdline-tools" \
&& curl -sSL -o /tmp/cmdline-tools.zip \
"https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_CMDLINE_TOOLS_VERSION}_latest.zip" \
&& unzip -q /tmp/cmdline-tools.zip -d "${ANDROID_HOME}/cmdline-tools" \
&& mv "${ANDROID_HOME}/cmdline-tools/cmdline-tools" "${ANDROID_HOME}/cmdline-tools/latest" \
&& rm /tmp/cmdline-tools.zip \
&& yes | sdkmanager --licenses >/dev/null \
&& sdkmanager --install \
"platform-tools" \
"platforms;android-${ANDROID_PLATFORM_VERSION}" \
"build-tools;${ANDROID_BUILD_TOOLS_VERSION}"
WORKDIR /workspace
+1
View File
@@ -0,0 +1 @@
0.1.0
+35
View File
@@ -0,0 +1,35 @@
# Runs the pipeline as a long-lived HTTP API for the Android app, on top
# of the same tooling-container image the numbered host scripts use.
# `docker compose up` alone is enough: the api service waits for Ollama
# and pulls the model itself (see tooling-container/src/server.py).
#
# The numbered host scripts (0_run_ollama.sh, 1/2/3_*.sh) and
# test_batch.sh are untouched and remain the way to inspect/test the
# pipeline stage by stage; this is the additive "serve it for real" path.
#
# Usage: docker compose up -d
# API reachable at http://<this-host>:8080 from any device on the LAN.
services:
ollama:
image: ollama/ollama
volumes:
- fuelish-ollama-data:/root/.ollama
restart: unless-stopped
api:
build:
context: ./tooling-container
restart: unless-stopped
depends_on:
- ollama
environment:
OLLAMA_URL: http://ollama:11434/api/chat
OLLAMA_BASE_URL: http://ollama:11434
OLLAMA_MODEL: qwen2.5:3b
command: ["uvicorn", "server:app", "--app-dir", "/opt/app/src", "--host", "0.0.0.0", "--port", "8000"]
ports:
- "8080:8000"
volumes:
fuelish-ollama-data:
name: fuelish-ollama-data
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

+19
View File
@@ -0,0 +1,19 @@
# Copy to registry.env (gitignored, never commit the real values) and fill
# in your registry credentials. Used by build-image.sh, upload-image.sh,
# run-image.sh, and the numbered pipeline scripts.
#
# REGISTRY_IMAGE (the OCR pipeline's tools image, tooling-container/) and
# REGISTRY_ANDROID_IMAGE (the Android CI/release build image,
# build-image/) must both be fully-qualified with the registry host -
# upload-image.sh does `docker push "$REGISTRY_IMAGE:..."` directly, so
# an unqualified name (e.g. "fuelish/tools") silently resolves to Docker
# Hub instead of $REGISTRY and fails to push there ("insufficient_scope:
# authorization failed") even though `docker login "$REGISTRY"`
# succeeded. Adjust the host below if your registry isn't cr.ladkau.de.
# REGISTRY/REGISTRY_USER/REGISTRY_PASSWORD are only needed to push with
# upload-image.sh.
REGISTRY=cr.ladkau.de
REGISTRY_IMAGE=cr.ladkau.de/fuelish/tools
REGISTRY_ANDROID_IMAGE=cr.ladkau.de/fuelish/android-builder
REGISTRY_USER=
REGISTRY_PASSWORD=
Executable
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env bash
# Runs `make android` inside the local android-builder image, mirroring
# what the Gitea Actions build workflow does - useful for testing
# build-image/ changes locally before pushing anything to a registry.
#
# Usage: ./run-image.sh [VERSION]
# VERSION is passed through to `make android` (see the Makefile's
# `android` target); omit it for its own git-tag-based default.
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(pwd)"
fail() { echo "PREFLIGHT FAIL: $*" >&2; exit 1; }
command -v docker >/dev/null 2>&1 \
|| fail "docker not found in PATH"
IMAGE="${REGISTRY_ANDROID_IMAGE:-cr.ladkau.de/fuelish/android-builder}"
if [ -f "$ROOT/registry.env" ]; then
# shellcheck disable=SC1091
source "$ROOT/registry.env"
IMAGE="${REGISTRY_ANDROID_IMAGE:-$IMAGE}"
fi
IMAGE_TAG="$(<"$ROOT/build-image/VERSION")"
[ -n "$IMAGE_TAG" ] || fail "build-image/VERSION is empty"
IMAGE="$IMAGE:$IMAGE_TAG"
docker image inspect "$IMAGE" >/dev/null 2>&1 \
|| fail "$IMAGE not found locally - run ./build-image.sh first"
VERSION="${1:-${VERSION:-}}"
# CI always starts from a fresh checkout, but this script bind-mounts the
# live host repo - so build output left over from a previous local run
# (dist/, android/build, the generated app icon/splash resources) would
# make this run skip work a real fresh checkout wouldn't, silently hiding
# bugs that only show up in CI. Wipe them first so every run exercises a
# true from-scratch build, same as CI.
echo "== Cleaning generated build artifacts for a fresh build =="
rm -rf \
"$ROOT/dist" "$ROOT/android/build" "$ROOT/android/app/build" \
"$ROOT/android/app/src/main/res/drawable-nodpi" \
"$ROOT/android/app/src/main/res"/mipmap-mdpi "$ROOT/android/app/src/main/res"/mipmap-hdpi \
"$ROOT/android/app/src/main/res"/mipmap-xhdpi "$ROOT/android/app/src/main/res"/mipmap-xxhdpi \
"$ROOT/android/app/src/main/res"/mipmap-xxxhdpi
echo "== Running make android inside $IMAGE =="
# The container runs as root (needed for the SDK/Gradle caches baked into
# the image), so anything it writes into this bind mount - dist/,
# android/build, android/.gradle, etc. - would otherwise come back owned
# by root, leaving the host repo unusable without sudo. Chown everything
# back to the host user on exit, whether the build succeeds or fails.
docker run --rm \
-v "$ROOT:/workspace" \
-w /workspace \
-e VERSION="$VERSION" \
-e HOST_UID="$(id -u)" \
-e HOST_GID="$(id -g)" \
"$IMAGE" \
bash -c '
git config --global --add safe.directory /workspace
trap "chown -R \"$HOST_UID:$HOST_GID\" /workspace" EXIT
make android
'
echo "== Done - artifact in dist/ =="
ls -la "$ROOT/dist"
Executable
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env bash
# Test-only tool: runs the full container pipeline (1_preprocess_image.sh,
# 2_ocr_image.sh, 3_extract_data.sh) over every *.jpg in a test-data
# directory, then compares the results against that directory's
# ground-truth spreadsheet (benzin_kosten.ods). Everything -
# preprocessing, OCR, structuring, and the comparison itself - runs
# inside the tooling container; nothing here depends on a host Python
# environment.
#
# For an input directory <path>/<name>, two sibling directories are
# created (mirroring <path>/<name>):
# <path>/<name>-scratch/<receipt>/ - intermediate step output
# (01_gray.png, 02_bilateral.png,
# 03_final.png, ocr.txt) for
# inspecting each step on its own
# <path>/<name>-result/<receipt>/ - final extracted.json per receipt,
# plus summary.txt with the overall
# ground-truth comparison
#
# Usage: ./test_batch.sh -in <test-data-dir>
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(pwd)"
fail() { echo "FAIL: $*" >&2; exit 1; }
IN_DIR=""
while [ $# -gt 0 ]; do
case "$1" in
-in) IN_DIR="${2:-}"; shift 2 ;;
*) fail "unknown argument: $1" ;;
esac
done
[ -n "$IN_DIR" ] || fail "usage: $0 -in <test-data-dir>"
[ -d "$IN_DIR" ] || fail "input directory not found: $IN_DIR"
IN_ABS="$(realpath "$IN_DIR")"
ODS_PATH="$(find "$IN_ABS" -maxdepth 1 -name '*.ods' | head -n1)"
[ -n "$ODS_PATH" ] || fail "no .ods ground-truth file found in $IN_ABS"
PARENT_DIR="$(dirname "$IN_ABS")"
BASE_NAME="$(basename "$IN_ABS")"
SCRATCH_DIR="$PARENT_DIR/$BASE_NAME-scratch"
RESULT_DIR="$PARENT_DIR/$BASE_NAME-result"
mkdir -p "$SCRATCH_DIR" "$RESULT_DIR"
shopt -s nullglob
IMAGES=("$IN_ABS"/*.jpg)
[ "${#IMAGES[@]}" -gt 0 ] || fail "no .jpg files found in $IN_ABS"
echo "== Running pipeline over ${#IMAGES[@]} receipts =="
for img in "${IMAGES[@]}"; do
name="$(basename "${img%.jpg}")"
receipt_scratch="$SCRATCH_DIR/$name"
receipt_result="$RESULT_DIR/$name"
mkdir -p "$receipt_scratch" "$receipt_result"
echo "--- $name ---"
./1_preprocess_image.sh -in "$img" -out "$receipt_scratch" >/dev/null
./2_ocr_image.sh -in "$receipt_scratch/03_final.png" -out "$receipt_scratch" >/dev/null
./3_extract_data.sh -in "$receipt_scratch/ocr.txt" -out "$receipt_result" >/dev/null
done
echo
echo "== Comparing against ground truth =="
IMAGE="${REGISTRY_IMAGE:-fuelish/tools}"
if [ -f "$ROOT/registry.env" ]; then
# shellcheck disable=SC1091
source "$ROOT/registry.env"
IMAGE="${REGISTRY_IMAGE:-$IMAGE}"
fi
VERSION="$(<"$ROOT/tooling-container/VERSION")"
IMAGE="$IMAGE:$VERSION"
ODS_DIR="$(dirname "$ODS_PATH")"
ODS_FILE="$(basename "$ODS_PATH")"
GROUP_ADD_ARGS=(--group-add "$(stat -c %g "$ODS_DIR")")
RESULT_GID="$(stat -c %g "$RESULT_DIR")"
[ "$RESULT_GID" = "$(stat -c %g "$ODS_DIR")" ] || GROUP_ADD_ARGS+=(--group-add "$RESULT_GID")
docker run --rm \
--user "$(id -u):$(id -g)" \
"${GROUP_ADD_ARGS[@]}" \
-v "$ODS_DIR:/data/gt:ro" \
-v "$RESULT_DIR:/data/results:ro" \
"$IMAGE" \
python3 /opt/app/src/compare_ground_truth.py -gt "/data/gt/$ODS_FILE" -results /data/results \
| tee "$RESULT_DIR/summary.txt"
echo
echo "== Done =="
echo "Intermediate step output: $SCRATCH_DIR/<receipt>/"
echo "Final results + summary: $RESULT_DIR/<receipt>/, $RESULT_DIR/summary.txt"
+23
View File
@@ -0,0 +1,23 @@
FROM python:3.12-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
tesseract-ocr \
tesseract-ocr-deu \
&& rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir \
opencv-python-headless==4.10.0.84 \
numpy==2.1.3 \
pillow==11.0.0 \
pytesseract==0.3.13 \
requests==2.32.3 \
odfpy==1.4.1 \
fastapi==0.115.5 \
uvicorn[standard]==0.32.1 \
python-multipart==0.0.17
COPY src/ /opt/app/src/
RUN chmod -R a+rX /opt/app/src
WORKDIR /data
ENTRYPOINT []
+1
View File
@@ -0,0 +1 @@
0.1.0
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Test-only tool: compare a directory of extracted.json results (produced
by running 1_preprocess_image.sh/2_ocr_image.sh/3_extract_data.sh over a
set of receipts) against the ground-truth spreadsheet, matching rows by
date and reporting per-field accuracy."""
import argparse
import glob
import json
import os
from odf.opendocument import load
from odf.table import Table, TableRow, TableCell
from odf.text import P
def load_ground_truth(ods_path: str) -> dict:
doc = load(ods_path)
table = doc.spreadsheet.getElementsByType(Table)[0]
rows = table.getElementsByType(TableRow)
gt = {}
for r in rows[1:]:
cells = r.getElementsByType(TableCell)
vals = []
for c in cells:
ps = c.getElementsByType(P)
vals.append(" ".join(str(p) for p in ps))
if not vals or not vals[0]:
continue
date = vals[0]
try:
gt[date] = {
"time": vals[1],
"price_per_litre": float(vals[2].replace(",", ".")) if vals[2] else None,
"litres": float(vals[3].replace(",", ".")) if vals[3] else None,
"discount": float(vals[4].replace("€", "").replace(",", ".").strip()) if vals[4] else None,
"total_price": float(vals[5].replace("€", "").replace(",", ".").strip()) if vals[5] else None,
}
except (ValueError, IndexError):
continue
return gt
def close(a, b, tol=0.05):
if a is None or b is None:
return a is None and b is None
return abs(abs(a) - abs(b)) <= tol
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-gt", dest="ods_path", required=True, help="path to ground-truth .ods")
parser.add_argument("-results", dest="results_dir", required=True,
help="directory containing one subdirectory per receipt, each with an extracted.json")
args = parser.parse_args()
gt = load_ground_truth(args.ods_path)
fields = ["price_per_litre", "litres", "discount", "total_price"]
field_ok = {k: 0 for k in fields}
field_total = {k: 0 for k in fields}
matched = 0
total = 0
for json_path in sorted(glob.glob(os.path.join(args.results_dir, "*", "extracted.json"))):
receipt = os.path.basename(os.path.dirname(json_path))
total += 1
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
truth = gt.get(data.get("date"))
if not truth:
print(f"{receipt}: NO DATE MATCH (extracted date={data.get('date')!r})")
continue
matched += 1
bad = []
for k in fields:
field_total[k] += 1
ok = close(data.get(k), truth[k])
if ok:
field_ok[k] += 1
else:
bad.append(k)
status = "OK" if not bad else f"WRONG FIELDS {bad}"
print(f"{receipt}: {status}")
print("\n=== SUMMARY ===")
print(f"Receipts matched to ground truth: {matched}/{total}")
for k in fields:
print(f" {k}: {field_ok[k]}/{field_total[k]} correct")
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Step 3: structure raw OCR text from a fuel receipt into JSON via a small
text-only LLM served by Ollama on the host (reached over --network host)."""
import argparse
import json
import os
import time
import requests
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434/api/chat")
MODEL = os.environ.get("OLLAMA_MODEL", "qwen2.5:3b")
SCHEMA = {
"type": "object",
"properties": {
"petrol_station": {"type": ["string", "null"]},
"transaction_number": {"type": ["string", "null"]},
"date": {"type": ["string", "null"], "description": "DD.MM.YYYY"},
"time": {"type": ["string", "null"], "description": "HH:MM:SS"},
"price_per_litre": {"type": ["number", "null"]},
"litres": {"type": ["number", "null"]},
"discount": {"type": ["number", "null"]},
"total_price": {"type": ["number", "null"]},
},
"required": [
"petrol_station", "transaction_number", "date", "time",
"price_per_litre", "litres", "discount", "total_price",
],
}
PROMPT_TEMPLATE = """The following is raw OCR text (with some noise/garbage from a security background pattern) extracted from a German fuel/petrol receipt. Extract these fields:
- petrol_station: the name of the petrol station / company (e.g. "Shell", "Aral", "JET")
- transaction_number: the transaction number (look for "Transaktions-Nr." specifically, not "Beleg-Nr."), as a string
- date: the receipt date, formatted DD.MM.YYYY
- time: the receipt time, formatted HH:MM:SS (24h)
- litres and price_per_litre: these two numbers appear together on one line, in this order:
"<litres> l <price_per_litre> EUR/l" (the "l" litre symbol is often misread as "1" or "|").
For example "23,50 l 1,749 EUR/l" means litres=23.50 and price_per_litre=1.749. These are
two different numbers on the same line - don't confuse them with each other or with the
total price/Gesamtbetrag.
- discount: total discount amount in EUR as a positive decimal number (0 if none). Look for
lines with words like "Rabatt", "Bonus", "Tankbonus", "Nachlass" followed by a negative EUR
amount, e.g. "Tankbonus -0,15 EUR" means discount=0.15 (drop the minus sign).
- total_price: the final total amount paid, in EUR, as a decimal number
Ignore garbled/nonsense words - they are OCR noise, not real data. If a field is not present, use null.
OCR TEXT:
---
{ocr_text}
---
Respond with ONLY the JSON object, no other text.
"""
def structure(ocr_text: str) -> dict:
payload = {
"model": MODEL,
"messages": [
{"role": "user", "content": PROMPT_TEMPLATE.format(ocr_text=ocr_text)},
],
"format": SCHEMA,
"stream": False,
"options": {"temperature": 0, "num_ctx": 3072},
}
start = time.time()
resp = requests.post(OLLAMA_URL, json=payload, timeout=300)
resp.raise_for_status()
result = resp.json()
elapsed = time.time() - start
content = result["message"]["content"]
parsed = json.loads(content)
parsed["_elapsed_seconds"] = round(elapsed, 1)
return parsed
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-in", dest="in_path", required=True)
parser.add_argument("-out", dest="out_dir", required=True)
args = parser.parse_args()
os.makedirs(args.out_dir, exist_ok=True)
with open(args.in_path, "r", encoding="utf-8") as f:
ocr_text = f.read()
data = structure(ocr_text)
out_path = os.path.join(args.out_dir, "extracted.json")
with open(out_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(out_path)
if __name__ == "__main__":
main()
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""Step 2: run Tesseract OCR (German) over a preprocessed receipt image,
writing the raw recognized text to the output directory for inspection
before it is handed to the structuring step."""
import argparse
import os
import pytesseract
from PIL import Image
def ocr(path: str, out_dir: str) -> str:
os.makedirs(out_dir, exist_ok=True)
img = Image.open(path)
text = pytesseract.image_to_string(img, lang="deu", config="--psm 3")
out_path = os.path.join(out_dir, "ocr.txt")
with open(out_path, "w", encoding="utf-8") as f:
f.write(text)
return out_path
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-in", dest="in_path", required=True)
parser.add_argument("-out", dest="out_dir", required=True)
args = parser.parse_args()
out_path = ocr(args.in_path, args.out_dir)
print(out_path)
if __name__ == "__main__":
main()
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Step 1: preprocess a receipt photo for OCR.
Applies a mild edge-preserving smoothing pass (to take the edge off the
receipt's dotted security background pattern) followed by a global
percentile-based contrast stretch. Every intermediate stage is written to
the output directory (01_gray, 02_bilateral, 03_final) so the effect of
each step can be inspected on its own before trusting the final image to
OCR.
Heavier processing (strong denoising, local/CLAHE contrast, unsharp
masking) was tried and tested worse: each one amplifies the security
background pattern into OCR noise rather than suppressing it. This
lighter two-step version was chosen because, across a set of receipts
that the plain-grayscale baseline OCR'd incorrectly, it recovered data
the baseline missed and never made a previously-correct read worse.
"""
import argparse
import os
import cv2
import numpy as np
from PIL import Image, ImageOps
def load_grayscale(path: str) -> np.ndarray:
img = Image.open(path)
img = ImageOps.exif_transpose(img).convert("L")
return np.array(img)
def autocontrast(gray: np.ndarray, low_pct=2, high_pct=98) -> np.ndarray:
lo, hi = np.percentile(gray, (low_pct, high_pct))
stretched = (gray.astype(np.float32) - lo) * 255.0 / (hi - lo)
return np.clip(stretched, 0, 255).astype(np.uint8)
def preprocess(path: str, out_dir: str) -> str:
os.makedirs(out_dir, exist_ok=True)
gray = load_grayscale(path)
cv2.imwrite(os.path.join(out_dir, "01_gray.png"), gray)
bilateral = cv2.bilateralFilter(gray, d=5, sigmaColor=50, sigmaSpace=50)
cv2.imwrite(os.path.join(out_dir, "02_bilateral.png"), bilateral)
final = autocontrast(bilateral)
final_path = os.path.join(out_dir, "03_final.png")
cv2.imwrite(final_path, final)
return final_path
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-in", dest="in_path", required=True)
parser.add_argument("-out", dest="out_dir", required=True)
args = parser.parse_args()
final_path = preprocess(args.in_path, args.out_dir)
print(final_path)
if __name__ == "__main__":
main()
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""HTTP API that serves the pipeline (preprocess -> ocr -> structure) to
the Android app. Runs the same in-process functions the numbered host
scripts drive via `docker run` per stage, but skips the per-stage
container start-up since a live server has no need for that
inspectability - the host scripts remain the way to inspect each stage
independently during pipeline development.
Jobs are processed asynchronously so the app can show real per-stage
progress: POST /jobs returns immediately with a job id; GET /jobs/{id}
reports which of preprocessing/ocr/extracting is currently running, and
the final result once done. Job state lives in memory only - this is a
personal, LAN-only, single-instance server with no need for persistence
here (the Android app is the system of record for confirmed receipts).
"""
import os
import shutil
import tempfile
import threading
import time
import uuid
import requests
from fastapi import FastAPI, HTTPException, UploadFile
from fastapi.responses import JSONResponse
from extract import structure
from ocr import ocr as run_ocr
from preprocess import preprocess
OLLAMA_BASE_URL = os.environ.get("OLLAMA_BASE_URL", "http://127.0.0.1:11434")
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen2.5:3b")
app = FastAPI(title="fuelish")
_jobs: dict[str, dict] = {}
_jobs_lock = threading.Lock()
def _set_job(job_id: str, **fields) -> None:
with _jobs_lock:
_jobs[job_id].update(fields)
def _ensure_model_pulled() -> None:
"""Best-effort: wait for Ollama to come up (compose starts `api` and
`ollama` together, with no ordering guarantee beyond container start)
and pull OLLAMA_MODEL if it isn't already present, so a bare `docker
compose up` is enough without a manual `ollama pull` step. Runs in a
background thread - jobs submitted before this finishes will simply
fail with a clear error from Ollama."""
tags = None
for _ in range(60):
try:
tags = requests.get(f"{OLLAMA_BASE_URL}/api/tags", timeout=5).json()
break
except requests.RequestException:
time.sleep(2)
if tags is None:
return
have = {m["name"] for m in tags.get("models", [])}
if OLLAMA_MODEL in have or any(m.startswith(OLLAMA_MODEL + ":") for m in have):
return
try:
requests.post(
f"{OLLAMA_BASE_URL}/api/pull",
json={"name": OLLAMA_MODEL},
timeout=1800,
)
except requests.RequestException:
pass
@app.on_event("startup")
def _on_startup() -> None:
threading.Thread(target=_ensure_model_pulled, daemon=True).start()
@app.get("/health")
def health() -> dict:
return {"status": "ok"}
def _process_job(job_id: str, image_path: str, scratch_dir: str) -> None:
try:
_set_job(job_id, status="preprocessing")
final_path = preprocess(image_path, scratch_dir)
_set_job(job_id, status="ocr")
ocr_txt_path = run_ocr(final_path, scratch_dir)
with open(ocr_txt_path, "r", encoding="utf-8") as f:
ocr_text = f.read()
_set_job(job_id, status="extracting")
result = structure(ocr_text)
_set_job(job_id, status="done", result=result)
except Exception as exc: # noqa: BLE001 - reported to the client, not swallowed
_set_job(job_id, status="error", error=str(exc))
finally:
shutil.rmtree(scratch_dir, ignore_errors=True)
@app.post("/jobs", status_code=201)
async def create_job(image: UploadFile) -> JSONResponse:
job_id = uuid.uuid4().hex
scratch_dir = tempfile.mkdtemp(prefix=f"fuelish-{job_id}-")
image_path = os.path.join(scratch_dir, "upload" + os.path.splitext(image.filename or "")[1])
with open(image_path, "wb") as f:
f.write(await image.read())
with _jobs_lock:
_jobs[job_id] = {"status": "queued", "result": None, "error": None, "_created": time.time()}
thread = threading.Thread(target=_process_job, args=(job_id, image_path, scratch_dir), daemon=True)
thread.start()
return JSONResponse({"job_id": job_id}, status_code=201)
@app.get("/jobs/{job_id}")
def get_job(job_id: str) -> dict:
with _jobs_lock:
job = _jobs.get(job_id)
if job is None:
raise HTTPException(status_code=404, detail="job not found")
return {"status": job["status"], "result": job["result"], "error": job["error"]}
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Pushes every image ./build-image.sh built locally - the fuelish tools
# image and the Android CI/release build image, each already verified
# (tools image with the numbered pipeline scripts, android-builder image
# with ./run-image.sh) - to a container registry, so the k3s cluster can
# pull the tools image and Gitea Actions can pull the android-builder
# image without rebuilding either.
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(pwd)"
fail() { echo "PREFLIGHT FAIL: $*" >&2; exit 1; }
command -v docker >/dev/null 2>&1 \
|| fail "docker not found in PATH"
[ -f "$ROOT/registry.env" ] \
|| fail "registry.env not found - copy registry.env.example to registry.env and fill in your registry credentials"
# shellcheck disable=SC1091
source "$ROOT/registry.env"
: "${REGISTRY:?registry.env must set REGISTRY}"
: "${REGISTRY_IMAGE:?registry.env must set REGISTRY_IMAGE}"
: "${REGISTRY_ANDROID_IMAGE:?registry.env must set REGISTRY_ANDROID_IMAGE}"
: "${REGISTRY_USER:?registry.env must set REGISTRY_USER}"
: "${REGISTRY_PASSWORD:?registry.env must set REGISTRY_PASSWORD}"
TOOLS_VERSION="$(<"$ROOT/tooling-container/VERSION")"
[ -n "$TOOLS_VERSION" ] || fail "tooling-container/VERSION is empty"
ANDROID_VERSION="$(<"$ROOT/build-image/VERSION")"
[ -n "$ANDROID_VERSION" ] || fail "build-image/VERSION is empty"
docker image inspect "$REGISTRY_IMAGE:$TOOLS_VERSION" >/dev/null 2>&1 \
|| fail "$REGISTRY_IMAGE:$TOOLS_VERSION not found locally - run ./build-image.sh first"
docker image inspect "$REGISTRY_ANDROID_IMAGE:$ANDROID_VERSION" >/dev/null 2>&1 \
|| fail "$REGISTRY_ANDROID_IMAGE:$ANDROID_VERSION not found locally - run ./build-image.sh first"
echo "== Logging in to $REGISTRY =="
echo "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
echo "== Pushing $REGISTRY_IMAGE:$TOOLS_VERSION and :latest =="
docker push "$REGISTRY_IMAGE:$TOOLS_VERSION"
docker push "$REGISTRY_IMAGE:latest"
echo "== Pushing $REGISTRY_ANDROID_IMAGE:$ANDROID_VERSION and :latest =="
docker push "$REGISTRY_ANDROID_IMAGE:$ANDROID_VERSION"
docker push "$REGISTRY_ANDROID_IMAGE:latest"
echo "== Done =="
echo "Images: $REGISTRY_IMAGE:$TOOLS_VERSION, $REGISTRY_ANDROID_IMAGE:$ANDROID_VERSION"