pibooth-gallery 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,205 @@
1
+ Metadata-Version: 2.4
2
+ Name: pibooth-gallery
3
+ Version: 1.3.0
4
+ Summary: pibooth plugin: thumbnails, thumbs.json manifest and static web gallery for event photobooths
5
+ Author: peteoheat
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/peteoheat/pibooth-gallery
8
+ Project-URL: Issues, https://github.com/peteoheat/pibooth-gallery/issues
9
+ Keywords: pibooth,photobooth,raspberrypi,gallery,thumbnails,plugin
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Environment :: Other Environment
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Multimedia :: Graphics
16
+ Requires-Python: >=3.7
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: pibooth>=2.0.0
20
+ Requires-Dist: Pillow
21
+ Dynamic: license-file
22
+
23
+ # pibooth-gallery
24
+
25
+ A plugin for [pibooth](https://github.com/pibooth/pibooth) that, after each final picture is saved:
26
+
27
+ 1. creates a thumbnail,
28
+ 2. creates/updates a `thumbs.json` manifest next to the pictures (newest first, with an optional QR code entry),
29
+ 3. optionally copies a static gallery HTML template beside the pictures as `gallery.html`.
30
+
31
+ It is designed to work with [pibooth-rclone-upload](https://github.com/peteoheat/pibooth-rclone-upload) (uploads the picture folder to a web host or S3) and my fork of [pibooth-qrcode](https://github.com/peteoheat/pibooth-qrcode).
32
+
33
+ Together they give you a workflow where:
34
+
35
+ 1. Final images are uploaded to a website or S3 bucket and are viewable in a browser.
36
+ 2. QR codes are created and uploaded with each image, enabling direct download.
37
+ 3. A web gallery lets guests scroll through all uploaded images for an event.
38
+
39
+ Optionally, [gallery-protect](https://github.com/peteoheat/gallery-protect) is a Cloudflare worker that password-protects the gallery so only people with the password can view/download images.
40
+
41
+ ## Installation
42
+
43
+ Requires Python 3.7+, `pibooth` and `Pillow` (both installed automatically by pip).
44
+
45
+ The plugin must be installed **into the same Python environment that pibooth runs from**. pibooth discovers it automatically through its `pibooth` entry point, so no extra configuration is needed to load it.
46
+
47
+ ### Raspberry Pi OS Bookworm / Trixie (virtual environment)
48
+
49
+ Since Bookworm, Raspberry Pi OS marks the system Python as "externally managed" (PEP 668), so `pip install` outside a virtual environment fails with `error: externally-managed-environment`. Do **not** work around this with `--break-system-packages`; install into the virtual environment that pibooth uses instead.
50
+
51
+ 1. Activate the virtual environment pibooth is installed in. Use whatever path you created it at; `~/venv` is used here as an example:
52
+
53
+ ```bash
54
+ source ~/venv/bin/activate
55
+ ```
56
+
57
+ Your prompt should now start with `(venv)`. To check that this is the right environment, `pip show pibooth` should print pibooth's details.
58
+
59
+ If you have not set up pibooth yet, create the environment first. `--system-site-packages` lets it use the Raspberry Pi camera libraries (`picamera2`) installed by apt:
60
+
61
+ ```bash
62
+ python3 -m venv --system-site-packages ~/venv
63
+ source ~/venv/bin/activate
64
+ pip install pibooth
65
+ ```
66
+
67
+ 2. Install the plugin from PyPI:
68
+
69
+ ```bash
70
+ pip install pibooth-gallery
71
+ ```
72
+
73
+ 3. Check that pibooth sees it:
74
+
75
+ ```bash
76
+ pibooth --diagnostic
77
+ ```
78
+
79
+ or start pibooth and look for `pibooth_gallery` in the loaded plugins list in the log.
80
+
81
+ To upgrade later (with the environment activated):
82
+
83
+ ```bash
84
+ pip install --upgrade pibooth-gallery
85
+ ```
86
+
87
+ If pibooth is launched automatically (autostart, systemd, cron), make sure the launcher uses the venv's interpreter, e.g. `~/venv/bin/pibooth`, otherwise the plugin will not be found.
88
+
89
+ ### Other systems
90
+
91
+ ```bash
92
+ pip install pibooth-gallery
93
+ ```
94
+
95
+ (inside a virtual environment, or on a system where pip is not externally managed).
96
+
97
+ ### From source
98
+
99
+ ```bash
100
+ git clone https://github.com/peteoheat/pibooth-gallery.git
101
+ pip install ./pibooth-gallery
102
+ ```
103
+
104
+ ### Gallery HTML templates
105
+
106
+ The HTML templates (`plain_gallery_template.html`, `seasonal_snowflake_gallery_auto_update_template.html`, `candy_cane_lane_gallery.html`) are not installed into Python's site-packages. Download the one you want from the [GitHub repository](https://github.com/peteoheat/pibooth-gallery), edit the event-specific values in it (e.g. `IMAGE_HOST_BASE`, titles), and point `template` at it in `pibooth.cfg`.
107
+
108
+ ## Configuration
109
+
110
+ After the first run, pibooth adds a `[GALLERY]` section to `~/.config/pibooth/pibooth.cfg` (you can also edit it with `pibooth --config`). Option names are lower case; there is no "enable" option. To disable the plugin, list `pibooth_gallery` in `[GENERAL]` `plugins_disabled`.
111
+
112
+ ```ini
113
+ [GALLERY]
114
+ size = 300x300
115
+ suffix = _thumb
116
+ quality = 85
117
+ output_folder =
118
+ keep_aspect = True
119
+
120
+ update_manifest = True
121
+ manifest_name = thumbs.json
122
+ manifest_include_base_url = True
123
+
124
+ template = /home/pi/gallery_template.html
125
+ output = gallery.html
126
+
127
+ base_url = https://example.com/event123/
128
+ ```
129
+
130
+ | Option | Default | Description |
131
+ |---|---|---|
132
+ | `size` | `300x300` | Thumbnail size as `WxH`. |
133
+ | `suffix` | `_thumb` | Suffix appended to the thumbnail filename. |
134
+ | `quality` | `85` | JPEG quality for thumbnails. |
135
+ | `output_folder` | *(empty)* | Optional subfolder for thumbnails. Leave empty when using pibooth-rclone-upload, which does not upload subfolders. |
136
+ | `keep_aspect` | `True` | Keep the aspect ratio when resizing. |
137
+ | `update_manifest` | `True` | Create/update the manifest after each picture. |
138
+ | `manifest_name` | `thumbs.json` | Manifest filename, written next to the pictures. |
139
+ | `manifest_include_base_url` | `True` | Prefix manifest entries with `base_url`. |
140
+ | `template` | *(empty)* | Optional path to a gallery HTML template to copy beside the pictures. |
141
+ | `output` | `gallery.html` | Filename for the copied template. |
142
+ | `base_url` | *(empty)* | Base URL for manifest entries. Falls back to `[DOWNLOADER]` `base_url`. |
143
+
144
+ ### QR code integration
145
+
146
+ This plugin never adds or modifies `[QRCODE]` settings. To find a picture's QR code it uses, in order:
147
+
148
+ 1. the `qrcode_path` recorded in pibooth's picture metadata, then
149
+ 2. `<picture name><suffix>.<ext>` (from `[QRCODE]` `suffix`/`ext`, default `_qrcode` / `png`), searched in `[QRCODE]` `save_path`, the `[GENERAL]` `directory` entries, then the picture's own folder.
150
+
151
+ The QR image is already on disk when this plugin runs, so no waiting is needed.
152
+
153
+ ## How it works
154
+
155
+ 1. pibooth saves the final picture.
156
+ 2. On leaving the processing state, pibooth-gallery (running before other plugins, so uploaders see its output):
157
+ * creates the thumbnail,
158
+ * sets `previous_thumbnail_file` on the pibooth app for other plugins,
159
+ * updates or creates `thumbs.json`,
160
+ * optionally writes `gallery.html` from the template.
161
+ 3. All files are written atomically, so an uploader never sees a partial file. A corrupt manifest is moved to `thumbs.json.bak` rather than overwritten. Errors are logged and never interrupt pibooth.
162
+
163
+ ## Manifest format
164
+
165
+ `thumbs.json` is a list, newest first:
166
+
167
+ ```json
168
+ [
169
+ {
170
+ "thumb": "IMG_001_thumb.jpg",
171
+ "full": "IMG_001.jpg",
172
+ "filename": "IMG_001.jpg",
173
+ "qrcode": "IMG_001_qrcode.png"
174
+ }
175
+ ]
176
+ ```
177
+
178
+ With `manifest_include_base_url = True` and a `base_url`, `thumb`, `full` and `qrcode` become absolute URLs such as `https://example.com/event123/IMG_001.jpg`.
179
+
180
+ ## Publishing to PyPI (maintainers)
181
+
182
+ The package version comes from `__version__` in `pibooth_gallery.py`.
183
+
184
+ ```bash
185
+ # 1. bump __version__ in pibooth_gallery.py, commit and tag
186
+ python -m pip install --upgrade build twine
187
+ python -m build # creates dist/*.tar.gz and dist/*.whl
188
+ python -m twine check dist/*
189
+
190
+ # 2. optional dry run on TestPyPI
191
+ python -m twine upload --repository testpypi dist/*
192
+
193
+ # 3. publish (use a PyPI API token: username __token__)
194
+ python -m twine upload dist/*
195
+ ```
196
+
197
+ PyPI never allows a version to be re-uploaded, so bump the version for every release.
198
+
199
+ ## Contributing
200
+
201
+ Pull requests are welcome. Please open an issue for feature requests or bug reports.
202
+
203
+ ## License
204
+
205
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,7 @@
1
+ pibooth_gallery.py,sha256=LW9avqZV7O_V3ZZYk0TxSTGcJygYJXmbPqDNKx5FuHU,14525
2
+ pibooth_gallery-1.3.0.dist-info/licenses/LICENSE,sha256=cvQX_B13Xa6SPcDCyo6v--01HkEIJ2TjBJzAquNbLf4,1087
3
+ pibooth_gallery-1.3.0.dist-info/METADATA,sha256=0__khJql1YX4nfU3J-TNADdPGoIUS-PJhOEAmX6E0BI,8362
4
+ pibooth_gallery-1.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
5
+ pibooth_gallery-1.3.0.dist-info/entry_points.txt,sha256=fJpwF966PcE3GvKV91VNzqGo3WoF6xmaGLu_IPBscgQ,44
6
+ pibooth_gallery-1.3.0.dist-info/top_level.txt,sha256=iQxfwz3auq7z4P5dQ-3LsqwVy0O_32DeIwB287BAiO8,16
7
+ pibooth_gallery-1.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [pibooth]
2
+ pibooth_gallery = pibooth_gallery
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 peteoheat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pibooth_gallery
pibooth_gallery.py ADDED
@@ -0,0 +1,379 @@
1
+ """
2
+ pibooth-gallery plugin
3
+
4
+ Creates a thumbnail for each final picture, maintains a ``thumbs.json`` manifest
5
+ next to the pictures and (optionally) copies a gallery HTML template beside it.
6
+ Designed to run alongside pibooth-qrcode and pibooth-rclone-upload.
7
+
8
+ Requires Pillow.
9
+
10
+ Hook ordering
11
+ -------------
12
+ ``state_processing_exit`` is registered ``tryfirst`` so the thumbnail and the
13
+ manifest exist before other plugins (e.g. rclone upload) scan the picture
14
+ folder. pibooth saves the final picture in ``state_processing_do``, so
15
+ ``app.previous_picture_file`` is already set when this hook runs.
16
+
17
+ Configuration
18
+ -------------
19
+ Options live in the [GALLERY] section. Names follow the pibooth convention: lower case,
20
+ words joined by ``_``, no plugin prefix, and no "enable" option (disable the plugin by
21
+ listing it in [GENERAL] ``plugins_disabled``).
22
+ Values are read once at startup into ``app.gallery_cfg`` (same pattern as
23
+ ``app.rclone_cfg`` in pibooth-rclone-upload). If a [QRCODE] section exists its
24
+ ``suffix``, ``ext`` and ``save_path`` keys are read to find the saved QR image;
25
+ this plugin never adds QRCODE options itself.
26
+
27
+ QR codes
28
+ --------
29
+ pibooth-qrcode generates and saves the QR image in ``state_processing_do``, which
30
+ always runs before ``state_processing_exit``, so the file already exists when this
31
+ hook runs and no waiting is needed. The file is looked up by name rather than by the
32
+ [QRCODE] ``save`` flag (see ``_find_qrcode``).
33
+
34
+ Error handling
35
+ --------------
36
+ Same policy as pibooth-rclone-upload: log through ``pibooth.utils.LOGGER`` and
37
+ never let an exception escape a hook (a failure here must not push pibooth into
38
+ its failsafe state). Every step is best-effort and independent of the others.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import json
44
+ import os
45
+ import tempfile
46
+ from pathlib import Path
47
+ from typing import Optional
48
+
49
+ import pibooth
50
+ from PIL import Image
51
+ from pibooth.utils import LOGGER
52
+
53
+ __version__ = "1.3.0"
54
+
55
+ SECTION = "GALLERY"
56
+
57
+ try:
58
+ _LANCZOS = Image.Resampling.LANCZOS
59
+ except AttributeError: # Pillow < 9.1
60
+ _LANCZOS = Image.LANCZOS
61
+
62
+
63
+ # --------------------------------------------------------------------------- #
64
+ # Configuration
65
+ # --------------------------------------------------------------------------- #
66
+
67
+ @pibooth.hookimpl
68
+ def pibooth_configure(cfg):
69
+ add = cfg.add_option
70
+
71
+ # Thumbnail settings
72
+ add(SECTION, "size", "300x300", "Thumbnail size WxH")
73
+ add(SECTION, "suffix", "_thumb", "Suffix for thumbnail files")
74
+ add(SECTION, "quality", "85", "JPEG quality for thumbnails (1-95)")
75
+ add(SECTION, "output_folder", "", "Optional subfolder near image to write thumbs "
76
+ "(leave empty when using pibooth-rclone-upload, "
77
+ "which does not upload subfolders)")
78
+ add(SECTION, "keep_aspect", "True", "Keep aspect ratio when resizing")
79
+
80
+ # Manifest settings
81
+ add(SECTION, "update_manifest", "True", "Update or create thumbs.json after thumbnail creation")
82
+ add(SECTION, "manifest_name", "thumbs.json", "Manifest filename to write/update in image directory")
83
+ add(SECTION, "manifest_include_base_url", "True",
84
+ "Include base_url (from [GALLERY] base_url or [DOWNLOADER]) when writing manifest entries")
85
+
86
+ # Gallery HTML settings
87
+ add(SECTION, "template", "", "Optional path to gallery_template.html")
88
+ add(SECTION, "output", "gallery.html", "Output filename for gallery HTML")
89
+
90
+ # Base URL
91
+ add(SECTION, "base_url", "", "Optional base URL to prefix thumb/full entries and gallery links")
92
+
93
+
94
+ def _opt(cfg, key, kind, default):
95
+ """Read a GALLERY option; on a bad value warn and use ``default`` instead of crashing startup."""
96
+ try:
97
+ if kind is bool:
98
+ return cfg.getboolean(SECTION, key)
99
+ if kind is int:
100
+ return cfg.getint(SECTION, key)
101
+ if kind is float:
102
+ return cfg.getfloat(SECTION, key)
103
+ return cfg.get(SECTION, key).strip()
104
+ except Exception as exc:
105
+ LOGGER.warning("gallery: bad value for %s (%s); using %r", key, exc, default)
106
+ return default
107
+
108
+
109
+ def _foreign(cfg, section, key):
110
+ """Read an option owned by another plugin. Returns None if absent or unreadable."""
111
+ try:
112
+ if cfg.has_section(section) and cfg.has_option(section, key):
113
+ value = cfg.get(section, key)
114
+ return value.strip() if isinstance(value, str) else value
115
+ except Exception as exc:
116
+ LOGGER.debug("gallery: could not read [%s] %s: %s", section, key, exc)
117
+ return None
118
+
119
+
120
+ def _parse_size(text: str):
121
+ try:
122
+ width, height = (int(v) for v in text.lower().split("x"))
123
+ if width > 0 and height > 0:
124
+ return width, height
125
+ except Exception:
126
+ pass
127
+ LOGGER.warning("gallery: invalid [GALLERY] size %r (expected WxH); using 300x300", text)
128
+ return 300, 300
129
+
130
+
131
+ @pibooth.hookimpl
132
+ def pibooth_startup(cfg, app):
133
+ template = _opt(cfg, "template", str, "")
134
+ if template and not Path(template).expanduser().is_file():
135
+ LOGGER.warning("gallery: [GALLERY] template %s is not a file; gallery page will not be written", template)
136
+
137
+ # Explicit gallery base URL first, then fall back to the DOWNLOADER plugin's.
138
+ base_url = _opt(cfg, "base_url", str, "") or _foreign(cfg, "DOWNLOADER", "base_url") or None
139
+
140
+ qr_suffix = _foreign(cfg, "QRCODE", "suffix") or "_qrcode"
141
+ qr_ext = (_foreign(cfg, "QRCODE", "ext") or "png").lstrip(".")
142
+ qr_save_path = _foreign(cfg, "QRCODE", "save_path") or None
143
+
144
+ # pibooth may save pictures to several directories (GENERAL/directory).
145
+ try:
146
+ save_dirs = [str(d) for d in cfg.gettuple("GENERAL", "directory", "path")]
147
+ except Exception as exc:
148
+ LOGGER.debug("gallery: could not read GENERAL/directory: %s", exc)
149
+ save_dirs = []
150
+
151
+ app.gallery_cfg = {
152
+ "size": _parse_size(_opt(cfg, "size", str, "300x300")),
153
+ "suffix": _opt(cfg, "suffix", str, "_thumb"),
154
+ "quality": max(1, min(95, _opt(cfg, "quality", int, 85))),
155
+ "output_folder": _opt(cfg, "output_folder", str, ""),
156
+ "keep_aspect": _opt(cfg, "keep_aspect", bool, True),
157
+ "update_manifest": _opt(cfg, "update_manifest", bool, True),
158
+ "manifest_name": _opt(cfg, "manifest_name", str, "thumbs.json"),
159
+ "include_base_url": _opt(cfg, "manifest_include_base_url", bool, True),
160
+ "template": template,
161
+ "output": _opt(cfg, "output", str, "gallery.html"),
162
+ "base_url": base_url,
163
+ "qrcode_suffix": qr_suffix,
164
+ "qrcode_ext": qr_ext,
165
+ "qrcode_save_path": qr_save_path,
166
+ "save_dirs": save_dirs,
167
+ }
168
+
169
+ LOGGER.info(
170
+ "gallery: startup configured (size=%s suffix=%s update_manifest=%s template=%s "
171
+ "base_url=%s)",
172
+ app.gallery_cfg["size"], app.gallery_cfg["suffix"],
173
+ app.gallery_cfg["update_manifest"], template or "-", base_url or "-",
174
+ )
175
+
176
+
177
+ # --------------------------------------------------------------------------- #
178
+ # Helpers
179
+ # --------------------------------------------------------------------------- #
180
+
181
+ def _safe(step: str, func, *args):
182
+ """Run one best-effort step: log failures, never raise, return None on failure."""
183
+ try:
184
+ return func(*args)
185
+ except Exception as exc:
186
+ LOGGER.warning("gallery: %s failed: %s", step, exc)
187
+ LOGGER.debug("gallery: %s traceback", step, exc_info=True)
188
+ return None
189
+
190
+
191
+ def _url_join(base: Optional[str], name: str) -> str:
192
+ return base.rstrip("/") + "/" + name if base else name
193
+
194
+
195
+ def _thumb_path(found: Path, suffix: str, output_folder: str) -> Path:
196
+ name = found.stem + suffix + found.suffix
197
+ if output_folder:
198
+ out_dir = found.parent / output_folder
199
+ out_dir.mkdir(parents=True, exist_ok=True)
200
+ return out_dir / name
201
+ return found.with_name(name)
202
+
203
+
204
+ def _make_thumbnail(src: Path, dst: Path, size, quality: int, keep_aspect: bool) -> None:
205
+ with Image.open(src) as im:
206
+ if dst.suffix.lower() in (".jpg", ".jpeg") and im.mode != "RGB":
207
+ im = im.convert("RGB") # JPEG cannot store alpha / palette modes
208
+ if keep_aspect:
209
+ im.thumbnail(size, _LANCZOS)
210
+ else:
211
+ im = im.resize(size, _LANCZOS)
212
+ im.save(dst, quality=quality)
213
+
214
+
215
+ def _atomic_write_text(path: Path, text: str) -> bool:
216
+ """Write ``path`` via a temp file + rename so readers (e.g. rclone) never see a partial file."""
217
+ tmp = None
218
+ try:
219
+ path.parent.mkdir(parents=True, exist_ok=True)
220
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=str(path.parent),
221
+ suffix=".tmp", delete=False) as fh:
222
+ tmp = Path(fh.name)
223
+ fh.write(text)
224
+ os.chmod(tmp, 0o644) # NamedTemporaryFile creates 0600; keep files readable by a web server
225
+ os.replace(tmp, path)
226
+ return True
227
+ except Exception as exc:
228
+ LOGGER.warning("gallery: failed to write %s: %s", path, exc)
229
+ if tmp is not None:
230
+ try:
231
+ tmp.unlink()
232
+ except OSError:
233
+ pass
234
+ return False
235
+
236
+
237
+ def _load_manifest(path: Path) -> list:
238
+ """Load the manifest. A corrupt file is moved aside (.bak) rather than silently overwritten."""
239
+ if not path.exists():
240
+ return []
241
+ try:
242
+ data = json.loads(path.read_text(encoding="utf-8"))
243
+ if isinstance(data, list):
244
+ return [entry for entry in data if isinstance(entry, dict)]
245
+ reason = "not a JSON list"
246
+ except Exception as exc:
247
+ reason = str(exc)
248
+
249
+ backup = path.with_name(path.name + ".bak")
250
+ try:
251
+ os.replace(path, backup)
252
+ LOGGER.warning("gallery: %s unreadable (%s); moved to %s and starting a new manifest",
253
+ path, reason, backup)
254
+ except OSError as exc:
255
+ LOGGER.warning("gallery: %s unreadable (%s) and could not be backed up (%s)", path, reason, exc)
256
+ return []
257
+
258
+
259
+ # --------------------------------------------------------------------------- #
260
+ # QR code lookup
261
+ # --------------------------------------------------------------------------- #
262
+
263
+ def _find_qrcode(found: Path, gcfg: dict, app) -> Optional[Path]:
264
+ """Locate the QR image pibooth-qrcode saved for ``found``, or None.
265
+
266
+ Deliberately does not consult the [QRCODE] ``save`` flag: the file's existence is
267
+ the truth (pibooth-qrcode currently treats the string "False" as enabled and
268
+ saves regardless, so the flag can disagree with what is on disk).
269
+ """
270
+ # Authoritative when present: pibooth-qrcode records the saved path here.
271
+ try:
272
+ metadata = getattr(app, "picture_metadata", None)
273
+ if isinstance(metadata, dict):
274
+ recorded = metadata.get(os.path.abspath(str(found)), {}).get("qrcode_path")
275
+ if recorded and Path(recorded).is_file():
276
+ return Path(recorded)
277
+ except (TypeError, AttributeError, OSError):
278
+ pass
279
+
280
+ # Otherwise rebuild the filename pibooth-qrcode uses: <picture stem><suffix>.<ext>
281
+ name = "{}{}.{}".format(found.stem, gcfg["qrcode_suffix"], gcfg["qrcode_ext"])
282
+ dirs = []
283
+ if gcfg["qrcode_save_path"]:
284
+ dirs.append(Path(gcfg["qrcode_save_path"]).expanduser())
285
+ dirs.extend(Path(d) for d in gcfg["save_dirs"])
286
+ dirs.append(found.parent)
287
+
288
+ for directory in dirs:
289
+ try:
290
+ candidate = directory / name
291
+ if candidate.is_file():
292
+ return candidate
293
+ except OSError:
294
+ continue
295
+ return None
296
+
297
+
298
+ # --------------------------------------------------------------------------- #
299
+ # Manifest and gallery page
300
+ # --------------------------------------------------------------------------- #
301
+
302
+ def _update_manifest(found: Path, thumb: Path, qrcode: Optional[Path], gcfg: dict) -> None:
303
+ manifest_path = found.parent / gcfg["manifest_name"]
304
+ base = gcfg["base_url"] if gcfg["include_base_url"] else None
305
+
306
+ def url_for(path: Path) -> str:
307
+ try:
308
+ name = path.relative_to(found.parent).as_posix()
309
+ except ValueError:
310
+ name = path.name
311
+ return _url_join(base, name)
312
+
313
+ full_rel = found.name
314
+ full_url = _url_join(base, full_rel)
315
+ entry = {"thumb": url_for(thumb), "full": full_url, "filename": full_rel}
316
+ if qrcode:
317
+ entry["qrcode"] = url_for(qrcode)
318
+
319
+ manifest = [e for e in _load_manifest(manifest_path)
320
+ if e.get("filename") != full_rel and e.get("full") != full_url]
321
+ manifest.insert(0, entry)
322
+
323
+ if _atomic_write_text(manifest_path, json.dumps(manifest, indent=2)):
324
+ LOGGER.info("gallery: manifest updated %s (entries=%d)", manifest_path, len(manifest))
325
+
326
+
327
+ def _copy_template(found: Path, gcfg: dict) -> None:
328
+ if not gcfg["template"]:
329
+ return
330
+ template = Path(gcfg["template"]).expanduser()
331
+ if not template.is_file(): # already warned about at startup
332
+ return
333
+ destination = found.parent / gcfg["output"]
334
+ if _atomic_write_text(destination, template.read_text(encoding="utf-8")):
335
+ LOGGER.info("gallery: gallery page written %s -> %s", template, destination)
336
+
337
+
338
+ # --------------------------------------------------------------------------- #
339
+ # Hook
340
+ # --------------------------------------------------------------------------- #
341
+
342
+ def _process_picture(app) -> None:
343
+ gcfg = getattr(app, "gallery_cfg", None)
344
+ if not gcfg:
345
+ return
346
+
347
+ filename = getattr(app, "previous_picture_file", None)
348
+ if not filename:
349
+ LOGGER.debug("gallery: no previous_picture_file; skipping")
350
+ return
351
+
352
+ found = Path(filename)
353
+ if not found.is_file():
354
+ LOGGER.debug("gallery: picture not found %s; skipping", found)
355
+ return
356
+
357
+ def make() -> Path:
358
+ thumb_path = _thumb_path(found, gcfg["suffix"], gcfg["output_folder"])
359
+ _make_thumbnail(found, thumb_path, gcfg["size"], gcfg["quality"], gcfg["keep_aspect"])
360
+ return thumb_path
361
+
362
+ thumb = _safe("thumbnail creation", make)
363
+ if thumb is None:
364
+ return
365
+ LOGGER.info("gallery: thumbnail created %s", thumb)
366
+
367
+ # Let other plugins know where the thumbnail is.
368
+ app.previous_thumbnail_file = str(thumb)
369
+
370
+ if gcfg["update_manifest"]:
371
+ qrcode = _safe("qrcode lookup", _find_qrcode, found, gcfg, app)
372
+ _safe("manifest update", _update_manifest, found, thumb, qrcode, gcfg)
373
+
374
+ _safe("gallery page copy", _copy_template, found, gcfg)
375
+
376
+
377
+ @pibooth.hookimpl(tryfirst=True)
378
+ def state_processing_exit(app):
379
+ _safe("processing", _process_picture, app)