Add wallpaper picker and compression script
This commit is contained in:
1 parent
d81ec1b057
commit
8342304354
11 files changed
+392
-7
No files matched your search
@@ -17,7 +17,7 @@ The site recreates my [blomarchy](https://git.sirblob.co/SirBlob/blomarchy) setu
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Tiling windows** - every page opens as a window that tiles like Hyprland's dwindle layout, with gradient borders.
|
- **Tiling windows** - every page opens as a window that tiles like Hyprland's dwindle layout, with gradient borders.
|
||||||
- **Quickshell bar** - app launcher, workspaces, clock, music player, live Discord status, battery details and a theme picker.
|
- **Quickshell bar** - app launcher, workspaces, clock, music player, live Discord status, battery details, a theme picker and a wallpaper picker.
|
||||||
- **Music player** - plays a random song from a YouTube playlist, muted until you unmute it, with seek, skip, repeat, volume and a playlist view.
|
- **Music player** - plays a random song from a YouTube playlist, muted until you unmute it, with seek, skip, repeat, volume and a playlist view.
|
||||||
- **Floating windows** - Alt + V or the title bar button pops a window out of the tiling layout so it can be dragged and resized.
|
- **Floating windows** - Alt + V or the title bar button pops a window out of the tiling layout so it can be dragged and resized.
|
||||||
- **btop** - a system monitor window with my real GitHub commit graph, repos as processes and some very scientific CPU and caffeine readings.
|
- **btop** - a system monitor window with my real GitHub commit graph, repos as processes and some very scientific CPU and caffeine readings.
|
||||||
@@ -111,7 +111,7 @@ bun run content:setup
|
|||||||
bun run content
|
bun run content
|
||||||
```
|
```
|
||||||
|
|
||||||
`content:setup` creates a virtual environment in `tools/content/.venv` and installs Textual. Run it once.
|
`content:setup` creates a virtual environment in `tools/content/.venv` and installs Textual and Pillow. Run it once.
|
||||||
|
|
||||||
| Key | Action |
|
| Key | Action |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -138,6 +138,15 @@ Show and movie titles are looked up on OMDb with `OMDB_API_KEY` from `.env`; fil
|
|||||||
| `projects/*.json` | Open source, packages, hackathons, research groups and organizations |
|
| `projects/*.json` | Open source, packages, hackathons, research groups and organizations |
|
||||||
| `music.json` | YouTube links for the music player |
|
| `music.json` | YouTube links for the music player |
|
||||||
| `books.json` | Books scraped from Goodreads for the about page |
|
| `books.json` | Books scraped from Goodreads for the about page |
|
||||||
|
| `wallpapers.json` | Wallpapers for the picker, written by `bun run wallpapers` |
|
||||||
| `desktop.json` | Workspaces, desktop icons, the startup command and the default theme |
|
| `desktop.json` | Workspaces, desktop icons, the startup command and the default theme |
|
||||||
| `themes.json` | Color themes for the site and the content editor |
|
| `themes.json` | Color themes for the site and the content editor |
|
||||||
| `blog/*.md` | Blog posts |
|
| `blog/*.md` | Blog posts |
|
||||||
|
|
||||||
|
### Wallpapers
|
||||||
|
|
||||||
|
```sh
|
||||||
|
bun run wallpapers
|
||||||
|
```
|
||||||
|
|
||||||
|
Converts every image in `~/dotfiles/wallpapers` into a compressed JPEG in `static/wallpapers/gallery`, with a small thumbnail for the picker, and writes the list to `content/wallpapers.json`. Unchanged wallpapers are skipped, so run it again whenever the dotfiles change. Pass a folder to use a different source, or `--force` to convert everything again.
|
||||||
+2
-1
@@ -9,7 +9,8 @@
|
|||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"start": "bun --bun vite build && bun ./build/index.js",
|
"start": "bun --bun vite build && bun ./build/index.js",
|
||||||
"content": "tools/content/.venv/bin/python tools/content/app.py",
|
"content": "tools/content/.venv/bin/python tools/content/app.py",
|
||||||
"content:setup": "python3 -m venv tools/content/.venv && tools/content/.venv/bin/pip install -r tools/content/requirements.txt",
|
"wallpapers": "tools/content/.venv/bin/python tools/content/wallpapers.py",
|
||||||
|
"content:setup":"python3 -m venv tools/content/.venv && tools/content/.venv/bin/pip install -r tools/content/requirements.txt",
|
||||||
"prepare": "svelte-kit sync || echo ''",
|
"prepare": "svelte-kit sync || echo ''",
|
||||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
import Clock from './Clock.svelte';
|
import Clock from './Clock.svelte';
|
||||||
import Workspaces from './Workspaces.svelte';
|
import Workspaces from './Workspaces.svelte';
|
||||||
import ThemeMenu from './ThemeMenu.svelte';
|
import ThemeMenu from './ThemeMenu.svelte';
|
||||||
|
import WallpaperMenu from './WallpaperMenu.svelte';
|
||||||
import DiscordStatus from './DiscordStatus.svelte';
|
import DiscordStatus from './DiscordStatus.svelte';
|
||||||
import Battery from './Battery.svelte';
|
import Battery from './Battery.svelte';
|
||||||
import Music from './Music.svelte';
|
import Music from './Music.svelte';
|
||||||
@@ -27,6 +28,7 @@
|
|||||||
<DiscordStatus />
|
<DiscordStatus />
|
||||||
<Battery />
|
<Battery />
|
||||||
<Donate />
|
<Donate />
|
||||||
|
<WallpaperMenu />
|
||||||
<ThemeMenu />
|
<ThemeMenu />
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@@ -2,7 +2,12 @@
|
|||||||
import { focusTrap } from '#lib/ui/focusTrap';
|
import { focusTrap } from '#lib/ui/focusTrap';
|
||||||
import type { Snippet } from 'svelte';
|
import type { Snippet } from 'svelte';
|
||||||
|
|
||||||
let { title, onclose, children }: { title: string; onclose: () => void; children: Snippet } = $props();
|
let {
|
||||||
|
title,
|
||||||
|
wide = false,
|
||||||
|
onclose,
|
||||||
|
children
|
||||||
|
}: { title: string; wide?: boolean; onclose: () => void; children: Snippet } = $props();
|
||||||
|
|
||||||
function handleKeydown(event: KeyboardEvent) {
|
function handleKeydown(event: KeyboardEvent) {
|
||||||
if (event.key === 'Escape') onclose();
|
if (event.key === 'Escape') onclose();
|
||||||
@@ -12,7 +17,7 @@
|
|||||||
<svelte:window onkeydown={handleKeydown} />
|
<svelte:window onkeydown={handleKeydown} />
|
||||||
|
|
||||||
<button class="backdrop" aria-label="Close {title}" onclick={onclose}></button>
|
<button class="backdrop" aria-label="Close {title}" onclick={onclose}></button>
|
||||||
<div class="popup" role="dialog" aria-modal="true" aria-label={title} tabindex="-1" use:focusTrap>
|
<div class="popup" class:wide role="dialog" aria-modal="true" aria-label={title} tabindex="-1" use:focusTrap>
|
||||||
<div class="popup-title">{title}</div>
|
<div class="popup-title">{title}</div>
|
||||||
<div class="popup-body">
|
<div class="popup-body">
|
||||||
{@render children()}
|
{@render children()}
|
||||||
@@ -42,6 +47,10 @@
|
|||||||
animation: window-pop-in 0.15s ease-out;
|
animation: window-pop-in 0.15s ease-out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.popup.wide {
|
||||||
|
width: 560px;
|
||||||
|
}
|
||||||
|
|
||||||
.popup-title {
|
.popup-title {
|
||||||
padding: 0.4rem 0.6rem;
|
padding: 0.4rem 0.6rem;
|
||||||
background: var(--background);
|
background: var(--background);
|
||||||
@@ -58,7 +67,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 640px) {
|
||||||
.popup {
|
.popup,
|
||||||
|
.popup.wide {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
top: calc(var(--bar-height) + 6px);
|
top: calc(var(--bar-height) + 6px);
|
||||||
right: 8px;
|
right: 8px;
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Icon from '@iconify/svelte';
|
||||||
|
import { wallpapers } from '#lib/content';
|
||||||
|
import { wallpaperState } from '#lib/theme/wallpaper.svelte';
|
||||||
|
import PopupCard from './PopupCard.svelte';
|
||||||
|
|
||||||
|
let open = $state(false);
|
||||||
|
let search = $state('');
|
||||||
|
|
||||||
|
const filtered = $derived(
|
||||||
|
wallpapers.filter((wallpaper) => wallpaper.name.toLowerCase().includes(search.trim().toLowerCase()))
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if wallpapers.length}
|
||||||
|
<div class="wallpaper-menu">
|
||||||
|
<button class="tray-button" title="Wallpaper" aria-expanded={open} onclick={() => (open = !open)}>
|
||||||
|
<Icon icon="mdi:image-multiple-outline" width="18" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{#if open}
|
||||||
|
<PopupCard title="Wallpapers ({wallpapers.length})" wide onclose={() => (open = false)}>
|
||||||
|
<div class="toolbar">
|
||||||
|
<input class="search" type="search" placeholder="search wallpapers" bind:value={search} />
|
||||||
|
<button class="tool" title="Random wallpaper" onclick={() => wallpaperState.shuffle()}>
|
||||||
|
<Icon icon="mdi:shuffle-variant" width="16" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="tool"
|
||||||
|
class:selected={wallpaperState.currentId === null}
|
||||||
|
title="Use the theme's wallpaper"
|
||||||
|
onclick={() => wallpaperState.set(null)}
|
||||||
|
>
|
||||||
|
<Icon icon="mdi:palette-outline" width="16" />
|
||||||
|
<span>theme</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid">
|
||||||
|
{#each filtered as wallpaper (wallpaper.id)}
|
||||||
|
<button
|
||||||
|
class="thumb"
|
||||||
|
class:selected={wallpaper.id === wallpaperState.currentId}
|
||||||
|
title={wallpaper.name}
|
||||||
|
onclick={() => wallpaperState.set(wallpaper.id)}
|
||||||
|
>
|
||||||
|
<img src={wallpaper.thumb} alt={wallpaper.name} loading="lazy" decoding="async" />
|
||||||
|
<span class="name">{wallpaper.name}</span>
|
||||||
|
</button>
|
||||||
|
{:else}
|
||||||
|
<span class="empty muted">No wallpapers match "{search}"</span>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</PopupCard>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.wallpaper-menu {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.35rem;
|
||||||
|
margin-bottom: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 0.3rem 0.5rem;
|
||||||
|
background: var(--dark-background);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--foreground) 25%, transparent);
|
||||||
|
color: var(--foreground);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search:focus {
|
||||||
|
border-color: var(--accent);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
padding: 0 0.5rem;
|
||||||
|
background: none;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--foreground) 25%, transparent);
|
||||||
|
color: var(--foreground);
|
||||||
|
font-size: 0.78rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool:hover,
|
||||||
|
.tool.selected {
|
||||||
|
border-color: var(--accent);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||||
|
gap: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thumb {
|
||||||
|
position: relative;
|
||||||
|
aspect-ratio: 16 / 9;
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--dark-background);
|
||||||
|
border: 2px solid transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thumb:hover {
|
||||||
|
border-color: color-mix(in srgb, var(--accent) 60%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thumb.selected {
|
||||||
|
border-color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thumb img {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.name {
|
||||||
|
position: absolute;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
padding: 0.1rem 0.35rem;
|
||||||
|
background: color-mix(in srgb, var(--background) 85%, transparent);
|
||||||
|
font-size: 0.68rem;
|
||||||
|
text-align: left;
|
||||||
|
white-space: nowrap;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thumb:hover .name,
|
||||||
|
.thumb:focus-visible .name,
|
||||||
|
.thumb.selected .name {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
padding: 0.5rem;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.grid {
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -12,6 +12,7 @@ import researchData from '#content/projects/research.json';
|
|||||||
import organizationsData from '#content/projects/organizations.json';
|
import organizationsData from '#content/projects/organizations.json';
|
||||||
import tcgDecksData from '#content/tcgDecks.json';
|
import tcgDecksData from '#content/tcgDecks.json';
|
||||||
import booksData from '#content/books.json';
|
import booksData from '#content/books.json';
|
||||||
|
import wallpapersData from '#content/wallpapers.json';
|
||||||
import type {
|
import type {
|
||||||
AboutContent,
|
AboutContent,
|
||||||
BlogSettings,
|
BlogSettings,
|
||||||
@@ -25,7 +26,8 @@ import type {
|
|||||||
ProjectCategory,
|
ProjectCategory,
|
||||||
ProjectCategoryId,
|
ProjectCategoryId,
|
||||||
ResearchGroup,
|
ResearchGroup,
|
||||||
TcgDeck
|
TcgDeck,
|
||||||
|
Wallpaper
|
||||||
} from './types';
|
} from './types';
|
||||||
|
|
||||||
export type * from './types';
|
export type * from './types';
|
||||||
@@ -40,6 +42,7 @@ export const playlist: Playlist = musicData;
|
|||||||
export const researchGroups: ResearchGroup[] = researchData;
|
export const researchGroups: ResearchGroup[] = researchData;
|
||||||
export const tcgDecks: TcgDeck[] = tcgDecksData as TcgDeck[];
|
export const tcgDecks: TcgDeck[] = tcgDecksData as TcgDeck[];
|
||||||
export const books: Book[] = booksData as Book[];
|
export const books: Book[] = booksData as Book[];
|
||||||
|
export const wallpapers: Wallpaper[] = wallpapersData as Wallpaper[];
|
||||||
|
|
||||||
function featuredFirst(projects: Project[]): Project[] {
|
function featuredFirst(projects: Project[]): Project[] {
|
||||||
return [...projects].sort((first, second) => Number(!!second.featured) - Number(!!first.featured));
|
return [...projects].sort((first, second) => Number(!!second.featured) - Number(!!first.featured));
|
||||||
|
|||||||
@@ -251,3 +251,10 @@ export interface TcgDeck {
|
|||||||
name: string;
|
name: string;
|
||||||
cards: DeckCard[];
|
cards: DeckCard[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface Wallpaper {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
image: string;
|
||||||
|
thumb: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { wallpapers, type Wallpaper } from '#lib/content';
|
||||||
|
|
||||||
|
const wallpaperStorageKey = 'wallpaper';
|
||||||
|
|
||||||
|
function readStoredWallpaperId(): string | null {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(wallpaperStorageKey);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function storeWallpaperId(wallpaperId: string | null) {
|
||||||
|
try {
|
||||||
|
if (wallpaperId) localStorage.setItem(wallpaperStorageKey, wallpaperId);
|
||||||
|
else localStorage.removeItem(wallpaperStorageKey);
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function findWallpaper(wallpaperId: string | null): Wallpaper | null {
|
||||||
|
return wallpapers.find((wallpaper) => wallpaper.id === wallpaperId) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyWallpaper(wallpaper: Wallpaper | null) {
|
||||||
|
const rootStyle = document.documentElement.style;
|
||||||
|
if (wallpaper) rootStyle.setProperty('--wallpaper', `url('${wallpaper.image}')`);
|
||||||
|
else rootStyle.removeProperty('--wallpaper');
|
||||||
|
}
|
||||||
|
|
||||||
|
class WallpaperState {
|
||||||
|
currentId = $state<string | null>(null);
|
||||||
|
|
||||||
|
restore() {
|
||||||
|
const stored = findWallpaper(readStoredWallpaperId());
|
||||||
|
this.currentId = stored?.id ?? null;
|
||||||
|
applyWallpaper(stored);
|
||||||
|
}
|
||||||
|
|
||||||
|
set(wallpaperId: string | null) {
|
||||||
|
const wallpaper = findWallpaper(wallpaperId);
|
||||||
|
this.currentId = wallpaper?.id ?? null;
|
||||||
|
applyWallpaper(wallpaper);
|
||||||
|
storeWallpaperId(this.currentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
shuffle() {
|
||||||
|
const choices = wallpapers.filter((wallpaper) => wallpaper.id !== this.currentId);
|
||||||
|
if (choices.length) this.set(choices[Math.floor(Math.random() * choices.length)].id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const wallpaperState = new WallpaperState();
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
import { desktop, profile } from '#lib/content';
|
import { desktop, profile } from '#lib/content';
|
||||||
import { buildThemeStylesheet } from '#lib/theme/stylesheet';
|
import { buildThemeStylesheet } from '#lib/theme/stylesheet';
|
||||||
import { themeState } from '#lib/theme/theme.svelte';
|
import { themeState } from '#lib/theme/theme.svelte';
|
||||||
|
import { wallpaperState } from '#lib/theme/wallpaper.svelte';
|
||||||
import { pageWindowId, windowManager } from '#lib/desktop/windows.svelte';
|
import { pageWindowId, windowManager } from '#lib/desktop/windows.svelte';
|
||||||
import { handleKeybind } from '#lib/desktop/keybinds';
|
import { handleKeybind } from '#lib/desktop/keybinds';
|
||||||
import { handleImageClick } from '#lib/desktop/imageViewer';
|
import { handleImageClick } from '#lib/desktop/imageViewer';
|
||||||
@@ -27,6 +28,7 @@
|
|||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
themeState.restore();
|
themeState.restore();
|
||||||
|
wallpaperState.restore();
|
||||||
const isWideScreen = window.innerWidth >= 768;
|
const isWideScreen = window.innerWidth >= 768;
|
||||||
if (!pageOpen && isWideScreen && desktop.startupCommand) windowManager.openTerminal(desktop.startupCommand, { floating: true });
|
if (!pageOpen && isWideScreen && desktop.startupCommand) windowManager.openTerminal(desktop.startupCommand, { floating: true });
|
||||||
window.addEventListener('click', handleImageClick, true);
|
window.addEventListener('click', handleImageClick, true);
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
textual>=8.2,<9
|
textual>=8.2,<9
|
||||||
|
pillow>=11
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import argparse
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
import jsonfile
|
||||||
|
from jsonfile import PROJECT_ROOT
|
||||||
|
|
||||||
|
SOURCE_DIR = Path.home() / "dotfiles" / "wallpapers"
|
||||||
|
OUTPUT_DIR = PROJECT_ROOT / "static" / "wallpapers" / "gallery"
|
||||||
|
THUMB_DIR = OUTPUT_DIR / "thumbs"
|
||||||
|
PUBLIC_PATH = "/wallpapers/gallery"
|
||||||
|
MANIFEST_FILE = "wallpapers.json"
|
||||||
|
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
|
||||||
|
FULL_SIZE = (2560, 1440)
|
||||||
|
THUMB_SIZE = (480, 270)
|
||||||
|
FULL_QUALITY = 82
|
||||||
|
THUMB_QUALITY = 70
|
||||||
|
SMALL_IMAGE_EDGE = 1000
|
||||||
|
|
||||||
|
|
||||||
|
def slug_of(path: Path) -> str:
|
||||||
|
return re.sub(r"[^a-z0-9]+", "-", path.stem.lower()).strip("-")
|
||||||
|
|
||||||
|
|
||||||
|
def display_name(path: Path) -> str:
|
||||||
|
words = re.sub(r"[_\-]+", " ", path.stem).strip()
|
||||||
|
return re.sub(r"^\d+\s+", "", words).title()
|
||||||
|
|
||||||
|
|
||||||
|
def source_images(source_dir: Path) -> list[Path]:
|
||||||
|
return sorted(path for path in source_dir.iterdir() if path.suffix.lower() in IMAGE_EXTENSIONS and path.is_file())
|
||||||
|
|
||||||
|
|
||||||
|
def flatten(image: Image.Image) -> Image.Image:
|
||||||
|
image = ImageOps.exif_transpose(image)
|
||||||
|
if image.mode in ("RGBA", "LA", "P"):
|
||||||
|
image = image.convert("RGBA")
|
||||||
|
background = Image.new("RGB", image.size, (0, 0, 0))
|
||||||
|
background.paste(image, mask=image.getchannel("A"))
|
||||||
|
return background
|
||||||
|
return image.convert("RGB")
|
||||||
|
|
||||||
|
|
||||||
|
def resample_for(image: Image.Image) -> int:
|
||||||
|
is_pixel_art = max(image.size) <= SMALL_IMAGE_EDGE
|
||||||
|
return Image.Resampling.NEAREST if is_pixel_art else Image.Resampling.LANCZOS
|
||||||
|
|
||||||
|
|
||||||
|
def fit_within(image: Image.Image, size: tuple[int, int]) -> Image.Image:
|
||||||
|
scale = min(size[0] / image.width, size[1] / image.height)
|
||||||
|
if scale >= 1 and max(image.size) > SMALL_IMAGE_EDGE:
|
||||||
|
return image
|
||||||
|
target = (max(1, round(image.width * scale)), max(1, round(image.height * scale)))
|
||||||
|
return image.resize(target, resample_for(image))
|
||||||
|
|
||||||
|
|
||||||
|
def save_jpeg(image: Image.Image, path: Path, quality: int):
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
image.save(path, "JPEG", quality=quality, optimize=True, progressive=True)
|
||||||
|
|
||||||
|
|
||||||
|
def is_up_to_date(source: Path, outputs: list[Path]) -> bool:
|
||||||
|
return all(output.exists() and output.stat().st_mtime >= source.stat().st_mtime for output in outputs)
|
||||||
|
|
||||||
|
|
||||||
|
def convert(source: Path, force: bool) -> dict:
|
||||||
|
slug = slug_of(source)
|
||||||
|
full_path = OUTPUT_DIR / f"{slug}.jpg"
|
||||||
|
thumb_path = THUMB_DIR / f"{slug}.jpg"
|
||||||
|
|
||||||
|
if force or not is_up_to_date(source, [full_path, thumb_path]):
|
||||||
|
with Image.open(source) as opened:
|
||||||
|
image = flatten(opened)
|
||||||
|
save_jpeg(fit_within(image, FULL_SIZE), full_path, FULL_QUALITY)
|
||||||
|
save_jpeg(ImageOps.fit(image, THUMB_SIZE, resample_for(image)), thumb_path, THUMB_QUALITY)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": slug,
|
||||||
|
"name": display_name(source),
|
||||||
|
"image": f"{PUBLIC_PATH}/{slug}.jpg",
|
||||||
|
"thumb": f"{PUBLIC_PATH}/thumbs/{slug}.jpg",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def remove_stale(kept_slugs: set[str]) -> int:
|
||||||
|
removed = 0
|
||||||
|
for folder in (OUTPUT_DIR, THUMB_DIR):
|
||||||
|
for path in folder.glob("*.jpg"):
|
||||||
|
if path.stem not in kept_slugs:
|
||||||
|
path.unlink()
|
||||||
|
removed += 1
|
||||||
|
return removed
|
||||||
|
|
||||||
|
|
||||||
|
def folder_size(folder: Path) -> int:
|
||||||
|
return sum(path.stat().st_size for path in folder.rglob("*") if path.is_file())
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="Compress wallpapers from the dotfiles repo into JPEGs for the website")
|
||||||
|
parser.add_argument("source", nargs="?", default=str(SOURCE_DIR), help="folder with the original wallpapers")
|
||||||
|
parser.add_argument("--force", action="store_true", help="convert every wallpaper again")
|
||||||
|
arguments = parser.parse_args()
|
||||||
|
|
||||||
|
source_dir = Path(arguments.source).expanduser()
|
||||||
|
if not source_dir.is_dir():
|
||||||
|
print(f"{source_dir} is not a folder", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
wallpapers = []
|
||||||
|
for source in source_images(source_dir):
|
||||||
|
try:
|
||||||
|
wallpapers.append(convert(source, arguments.force))
|
||||||
|
print(f"ok {source.name}")
|
||||||
|
except OSError as error:
|
||||||
|
print(f"skipped {source.name}: {error}", file=sys.stderr)
|
||||||
|
|
||||||
|
removed = remove_stale({wallpaper["id"] for wallpaper in wallpapers})
|
||||||
|
jsonfile.save(MANIFEST_FILE, wallpapers)
|
||||||
|
|
||||||
|
original_size = sum(path.stat().st_size for path in source_images(source_dir))
|
||||||
|
compressed_size = folder_size(OUTPUT_DIR)
|
||||||
|
print(f"\n{len(wallpapers)} wallpapers, {removed} stale files removed")
|
||||||
|
print(f"{original_size / 1024 / 1024:.1f} MB -> {compressed_size / 1024 / 1024:.1f} MB (including thumbnails)")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
Reference in new issue
Block a user