From 668547d71fd1c1c8493c39f30532e0d10bb28b17 Mon Sep 17 00:00:00 2001 From: somepoi <46904988+somepoi@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:27:53 +0300 Subject: [PATCH 1/5] feature: community sprites --- README.md | 55 ++++++ app/routes/res.py | 23 ++- app/routes/resources.py | 14 +- app/utils/config.py | 3 + app/utils/lifespan/community_sprites.py | 149 ++++++++++++++ app/utils/lifespan/refresh.py | 1 + app/utils/lifespan/resources_cache.py | 10 +- app/utils/lifespan/sprites_cache.py | 22 ++- app/utils/lifespan/thumbs_cache.py | 2 + docs/plans/2026-10-16-community-sprites.md | 31 +++ static/js/resources.js | 7 +- templates/resources_list.html | 46 ++++- tests/test_community_sprites.py | 215 +++++++++++++++++++++ 13 files changed, 551 insertions(+), 27 deletions(-) create mode 100644 app/utils/lifespan/community_sprites.py create mode 100644 docs/plans/2026-10-16-community-sprites.md create mode 100644 tests/test_community_sprites.py diff --git a/README.md b/README.md index 6ed57ba..e4fb121 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,61 @@ notices: задайте `notices: []` или удалите файл. Все объявления — обычные ссылки, которые открываются без JavaScript. +## Пользовательские спрайты + +Слоистые спрайты сообщества задаются в `community-sprites.json` в корне +**es-doc-assets**. Формат: `groups` → название группы → `variations` → +вариант с `name` и `distances`. Каждая дистанция (`normal`, `close`, `far`) +содержит непустой массив путей к слоям, от нижнего к верхнему. + +```json +{ + "groups": { + "Лена в полицейской форме": { + "author": {"name": "Имя художника", "link": "https://example.com/artist"}, + "description": "Спрайт из модификации «Главный Атрибут Пионера»", + "variations": [ + { + "name": "Улыбается", + "distances": { + "normal": [ + "/resource/raw/images/sprites/normal/un/un_1_body.png", + "sprites/lena_police/normal/clothes.png", + "sprites/lena_police/normal/smile.png" + ], + "close": ["sprites/lena_police/close/smile.png"], + "far": ["sprites/lena_police/far/smile.png"] + } + } + ] + } + } +} +``` + +Это пример структуры: пользовательские файлы нужно добавить в репозиторий. +Относительные пути отсчитываются от `community/`; +`/resource/community/…` адресует ту же папку, `/resource/raw/…` — `game/`. +Используйте `/` в путях. Внешние ссылки и выход за пределы этих папок запрещены. +Поддерживаются PNG, WebP и JPG; для прозрачных слоёв используйте PNG или WebP. +Все слои одной дистанции должны иметь одинаковые размеры и совмещаться +от левого верхнего угла. Один готовый спрайт — массив из одного файла. + +Необязательно задавать все дистанции: показываются только перечисленные. +Первой выбирается `normal`, затем `close`, затем `far`. Названия вариантов +внутри группы должны быть уникальны. `author` и `description` необязательны; +пустые поля не выводятся, ссылка автора поддерживает HTTP(S). +В JSON нельзя писать комментарии `//`. + +Группы доступны на `/resources/community/sprites`, участвуют в поиске, +поддерживают выбор дистанции, просмотр и скачивание собранного WebP. +Сборка и миниатюры создаются при первом обращении и кэшируются. +Изменения JSON и изображений подхватываются без перезапуска. Некорректные +дистанции пропускаются с предупреждением в журнале; при ошибке синтаксиса +JSON сохраняется предыдущий каталог. `{"groups": {}}` или удаление файла +очищает каталог. Отдельные спрайты продолжают находиться автоматически; +слои, использованные в каталоге, повторно отдельными картинками не выводятся. + ## Каталог специалистов Страница `/specialists` объединяет художников, нейрохудожников, композиторов, diff --git a/app/routes/res.py b/app/routes/res.py index 5a2c101..590edad 100644 --- a/app/routes/res.py +++ b/app/routes/res.py @@ -48,18 +48,18 @@ def _artist_img_lock(url, kind): lock = _artist_img_locks[(url, kind)] = asyncio.Lock() return lock -async def _ensure_composed(sprite): +async def _ensure_composed(sprite, community=False): - if sprite not in CONFIG.sprite_layers: + if sprite not in (CONFIG.community_sprite_layers if community else CONFIG.sprite_layers): raise HTTPException(404, f'Спрайт "{sprite}" не существует.') - if not is_composed(sprite): + if not is_composed(sprite, community): async with compose_lock: # Re-check: the request holding the lock before us may have # composed this very sprite. - if not is_composed(sprite): + if not is_composed(sprite, community): try: - await asyncio.to_thread(compose_sprite, sprite) + await asyncio.to_thread(compose_sprite, sprite, community) except Exception: logger.exception(f'Composing sprite "{sprite}" failed.') raise HTTPException(500, f'Не удалось собрать спрайт "{sprite}".') from None @@ -71,6 +71,13 @@ async def sprite_page(sprite, request: Request): return FileResponse(str(sprite_file(sprite)), media_type='image/webp', headers=cache_headers(precompressed=True)) + +@router.get('/community-sprite/{sprite}') +async def community_sprite_page(sprite: str): + await _ensure_composed(sprite, community=True) + return FileResponse(str(sprite_file(sprite, community=True)), media_type='image/webp', + headers=cache_headers(precompressed=True)) + def _find_tinted(kind, name): return next((i for collection in CONFIG.resources.values() for i in collection.get(kind, []) @@ -110,12 +117,12 @@ async def tinted_page(kind, name, request: Request): @router.get('/thumb/{kind}/{name:path}') async def thumb_page(kind, name, request: Request): - if kind not in ('bg', 'cg', 'anim', 'sprite', 'community'): + if kind not in ('bg', 'cg', 'anim', 'sprite', 'community', 'community-sprite'): raise HTTPException(404, f'Категория "{kind}" не существует.') - if kind == 'sprite': + if kind in ('sprite', 'community-sprite'): # A sprite thumb derives from the composed sprite, so compose first. - await _ensure_composed(name) + await _ensure_composed(name, community=kind == 'community-sprite') elif kind == 'community': if not any(i['file'] == name and i['thumb'] for items in CONFIG.resources.get('community', {}).values() diff --git a/app/routes/resources.py b/app/routes/resources.py index b37ad5a..9e4665c 100644 --- a/app/routes/resources.py +++ b/app/routes/resources.py @@ -83,6 +83,8 @@ def _count(category, items): # sit behind their toggle and are not part of the headline numbers. if category == 'sprites' and items and 'sprites' in items[0]: return sum(len(group['sprites']) for group in items) + if category == 'sprites': + return sum(len(item.get('variants', [item])) for item in items) return sum(1 for i in items if i['declared']) @@ -309,6 +311,14 @@ async def listing(collection, category, request: Request): present = {i['time'] for i in items} bg_times = [(key, label) for key, label in BG_TIME_LABELS.items() if key in present] + community_sprite_groups = {} + if category == 'sprites' and collection == 'community': + for item in items: + group = item.get('sprite_group') + if group: + entry = community_sprite_groups.setdefault(group['rid'], {**group, 'families': []}) + entry['families'].append(item) + return templates.TemplateResponse(request, 'resources_list.html', { 'collection': collection, 'collection_meta': COLLECTIONS[collection], @@ -317,8 +327,8 @@ async def listing(collection, category, request: Request): 'categories': switcher, 'items': items, 'count': _count(category, items), - 'count_all': (len(items) if category != 'sprites' or collection == 'community' - else sum(len(g['sprites']) for g in items)), + 'count_all': _count(category, items) if category == 'sprites' else len(items), + 'community_sprite_groups': list(community_sprite_groups.values()), 'has_undeclared': (category != 'sprites' and any(not i['declared'] for i in items)), 'other_href': other_href, diff --git a/app/utils/config.py b/app/utils/config.py index 2c0546d..caac939 100644 --- a/app/utils/config.py +++ b/app/utils/config.py @@ -212,6 +212,9 @@ def __init__(self): # Sprites are composed lazily on first request and cached on disk. self.sprite_layers = {} + # Catalogue key -> validated local layer Paths, separate from game sprites. + self.community_sprite_layers = {} + # {'original': {category: items}, 'community': {...}} from the game's # declarations and community files (see lifespan/resources_cache.py). self.resources = {} diff --git a/app/utils/lifespan/community_sprites.py b/app/utils/lifespan/community_sprites.py new file mode 100644 index 0000000..6c9ab29 --- /dev/null +++ b/app/utils/lifespan/community_sprites.py @@ -0,0 +1,149 @@ +"""Local, layered community sprites declared in the assets catalogue.""" + +import hashlib +import json +import re +from pathlib import PureWindowsPath +from urllib.parse import unquote, urlsplit + +from ..config import CONFIG +from ..logging import root_logger + +logger = root_logger.getChild('lifespan').getChild('community-sprites') +DISTANCES = ('normal', 'close', 'far') +IMAGE_EXTS = {'.png', '.webp', '.jpg', '.jpeg'} + + +def layer_path(value): + """Resolve a declared image within game/ or community/, never arbitrary files.""" + if not isinstance(value, str) or not value.strip(): + raise ValueError('A layer must be a non-empty local image path') + value = value.strip() + root = CONFIG.res_path.parent / 'community' + for prefix, directory in ( + ('/resource/raw/', CONFIG.res_path), + ('/resource/community/', root), + ): + if value.startswith(prefix): + root, value = directory, unquote(value[len(prefix):]) + break + if ('\\' in value or '\x00' in value or ':' in value + or value.startswith('/') or '..' in value.split('/') + or PureWindowsPath(value).drive): + raise ValueError('Layer paths must stay inside game/ or community/') + path = (root / value).resolve() + if not path.is_relative_to(root.resolve()) or path.suffix.lower() not in IMAGE_EXTS: + raise ValueError('Layer must be an image inside game/ or community/') + if not path.is_file(): + raise ValueError(f'Layer does not exist: {value}') + return path + + +def _text(value): + return value.strip() if isinstance(value, str) else '' + + +def _layer_reference(path): + for folder, root in (('game', CONFIG.res_path), + ('community', CONFIG.res_path.parent / 'community')): + if path.is_relative_to(root.resolve()): + return folder + '/' + path.relative_to(root.resolve()).as_posix() + raise ValueError('Layer is outside the resource directories') + + +def _author(value): + value = value if isinstance(value, dict) else {} + link = _text(value.get('link')) + try: + parsed = urlsplit(link) + safe = (parsed.scheme in ('http', 'https') and parsed.netloc + and not any(c.isspace() or ord(c) < 32 for c in link)) + except ValueError: + safe = False + if not safe: + link = '' + return {'name': _text(value.get('name')), 'link': link} + + +def parse_community_sprites(): + """Return flat families plus their layer map; malformed JSON keeps the last catalogue.""" + manifest = CONFIG.res_path.parent / 'community-sprites.json' + if not manifest.exists(): + return [], {} + try: + data = json.loads(manifest.read_text('utf-8-sig')) + if not isinstance(data, dict) or not isinstance(data.get('groups'), dict): + raise TypeError('The catalogue must contain a groups object') + except (OSError, ValueError, TypeError): + logger.exception('Invalid community-sprites.json; keeping the previous catalogue.') + previous = CONFIG.resources.get('community', {}).get('sprites', []) + return [i for i in previous if i.get('sprite_group')], CONFIG.community_sprite_layers + + families, layer_map = [], {} + for title, group in data['groups'].items(): + if (not _text(title) or not isinstance(group, dict) + or not isinstance(group.get('variations'), list)): + logger.warning('Invalid sprite group %r; skipping it.', title) + continue + title = title.strip() + group_meta = { + 'title': title, 'desc': _text(group.get('description')), + 'author': _author(group.get('author')), + 'rid': 'sprite-group-' + hashlib.sha256(title.encode()).hexdigest()[:20], + } + seen = set() + for variation in group['variations']: + if not isinstance(variation, dict): + logger.warning('Invalid variation in %s; skipping it.', title) + continue + name = _text(variation.get('name')) + distances = variation.get('distances') + if not name or name in seen or not isinstance(distances, dict): + logger.warning('Invalid or duplicate variation %r in %s; skipping it.', name, title) + continue + seen.add(name) + variants = [] + layer_files = [] + for distance in DISTANCES: + if distance not in distances: + continue + try: + layers = distances[distance] + if not isinstance(layers, list) or not layers: + raise ValueError('A distance must contain at least one layer') + paths = [layer_path(layer) for layer in layers] + except (ValueError, OSError) as exc: + logger.warning('Invalid sprite %s / %s / %s: %s', title, name, distance, exc) + continue + # Include source versions so browser caches refresh too. Logical + # paths keep URLs independent of the installation directory. + versions = [(_layer_reference(p), p.stat().st_mtime_ns, p.stat().st_size) + for p in paths] + identity = json.dumps([title, name, distance, versions]) + key = hashlib.sha256(identity.encode()).hexdigest() + anchor = hashlib.sha256(json.dumps([title, name, distance]).encode()).hexdigest() + layer_map[key] = paths + layer_files.extend(paths) + filename = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', f'{title} — {name} {distance}') + variants.append({ + 'name': filename, 'code': name, 'title': name, + 'rid': 'r-community-sprite-' + anchor, + 'distance': distance, + 'raw': f'/resource/community-sprite/{key}', + 'thumb': f'/resource/thumb/community-sprite/{key}', + }) + if not variants: + continue + primary = variants[0] + search = ' '.join([group_meta['desc'], group_meta['author']['name'], + *(f"{title} {name} {v['distance']}" for v in variants), + *(_layer_reference(p) for p in layer_files)]) + families.append({ + 'name': name, 'title': f'{title} — {name}', 'code': None, + 'file': '', 'declared': True, 'captions': [], + 'rid': primary['rid'], 'raw': primary['raw'], 'thumb': primary['thumb'], + 'desc': group_meta['desc'], 'sprite_group': group_meta, + 'variants': variants, 'primary': primary, 'search': search, + 'layer_files': layer_files, + }) + return families, layer_map diff --git a/app/utils/lifespan/refresh.py b/app/utils/lifespan/refresh.py index 48c129a..84fc1c8 100644 --- a/app/utils/lifespan/refresh.py +++ b/app/utils/lifespan/refresh.py @@ -102,6 +102,7 @@ def _watchers(): res / 'media.rpy', assets / 'descriptions.yaml', assets / 'community-descriptions.yaml', + assets / 'community-sprites.json', assets / 'nsfw.yaml', ) community_files = _under(assets / 'community') diff --git a/app/utils/lifespan/resources_cache.py b/app/utils/lifespan/resources_cache.py index 597d432..102f642 100644 --- a/app/utils/lifespan/resources_cache.py +++ b/app/utils/lifespan/resources_cache.py @@ -6,6 +6,7 @@ from ..config import CONFIG from ..logging import root_logger +from .community_sprites import parse_community_sprites logger = root_logger.getChild('lifespan').getChild('resources-cache') @@ -706,7 +707,7 @@ def _build_search_items(collection, collection_name='original'): } if collection_name == 'community': row['context'] = 'Ресурсы сообщества / ' + row['context'] - row['keywords'] = ' '.join([item['file'], *item.get('captions', [])]) + row['keywords'] = ' '.join([item['file'], item.get('search', ''), *item.get('captions', [])]) # Real descriptions (auto bg/music or hand-written) are searchable # too; the "уточняется" placeholder would only add noise. if item['desc'] and item['desc'] not in (PLACEHOLDER_DESC, UNDECLARED_DESC): @@ -731,11 +732,18 @@ def parse_resources(): # Community files are independent of the game's Ren'Py declarations. community_root = CONFIG.res_path.parent / 'community' community = _parse_community(community_root, _load_community_descriptions()) + custom_sprites, custom_layers = parse_community_sprites() + used_layers = {path for item in custom_sprites for path in item['layer_files']} + community['sprites'] = custom_sprites + [ + item for item in community['sprites'] + if (community_root / item['file']).resolve() not in used_layers + ] # NSFW CG declarations are cut from the original collection and are not # listed in the community collection either. original['cg'] = [i for i in original['cg'] if not i['nsfw']] + CONFIG.community_sprite_layers = custom_layers CONFIG.resources = {'original': original, 'community': community} # Merged into CONFIG.search_items at startup and after assets refreshes. CONFIG.resource_search_items = ( diff --git a/app/utils/lifespan/sprites_cache.py b/app/utils/lifespan/sprites_cache.py index a00cac2..eb837a3 100644 --- a/app/utils/lifespan/sprites_cache.py +++ b/app/utils/lifespan/sprites_cache.py @@ -35,16 +35,17 @@ def parse_sprites(): CONFIG.sprite_layers = sprites logger.info(f'{len(sprites)} sprite combinations found.') -def sprite_file(name): - return sprites_path() / f'{name}.webp' +def sprite_file(name, community=False): + root = CONFIG.cache_path / 'community-sprites' if community else sprites_path() + return root / f'{name}.webp' -def is_composed(name): +def is_composed(name, community=False): # Both the declaration and every layer contribute to the composed bytes. - path = sprite_file(name) - layers = CONFIG.sprite_layers.get(name) + path = sprite_file(name, community) + layers = (CONFIG.community_sprite_layers if community else CONFIG.sprite_layers).get(name) if not path.is_file() or not layers: return False - sources = [p for p in _sprite_sources() if p.exists()] + sources = [] if community else [p for p in _sprite_sources() if p.exists()] sources.extend(CONFIG.res_path / layer for layer in layers) try: newest = max(source.stat().st_mtime_ns for source in sources) @@ -52,9 +53,9 @@ def is_composed(name): except OSError: return False -def compose_sprite(name): +def compose_sprite(name, community=False): - layers = CONFIG.sprite_layers[name] + layers = (CONFIG.community_sprite_layers if community else CONFIG.sprite_layers)[name] starttime = time.time() @@ -63,11 +64,14 @@ def compose_sprite(name): for layer in layers[1:]: with Image.open(CONFIG.res_path / layer) as overlay: + if community and overlay.size != img.size: + raise ValueError('All layers of a community sprite must have the same dimensions') img.alpha_composite(overlay.convert('RGBA')) # Write to a temp name and swap it in, so a request that arrives while a # compose is in flight never sees a half-written file. - path = sprite_file(name) + path = sprite_file(name, community) + path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix('.webp.tmp') img.save(tmp, 'WEBP', quality=CONFIG.setting('images.sprite-quality')) os.replace(tmp, path) diff --git a/app/utils/lifespan/thumbs_cache.py b/app/utils/lifespan/thumbs_cache.py index 363378f..a38df30 100644 --- a/app/utils/lifespan/thumbs_cache.py +++ b/app/utils/lifespan/thumbs_cache.py @@ -28,6 +28,8 @@ def _source_file(kind, name): # or the community drop-in folder next to it. if kind == 'sprite': return sprite_file(name) + if kind == 'community-sprite': + return sprite_file(name, community=True) if name in CONFIG.community_sprite_layers else None if kind == 'community': listed = any(i['file'] == name and i['thumb'] for category in CONFIG.resources.get('community', {}).values() diff --git a/docs/plans/2026-10-16-community-sprites.md b/docs/plans/2026-10-16-community-sprites.md new file mode 100644 index 0000000..de82145 --- /dev/null +++ b/docs/plans/2026-10-16-community-sprites.md @@ -0,0 +1,31 @@ +# Пользовательские спрайты + +**Цель:** каталог `community-sprites.json` в es-doc-assets с форматом +`groups → variations → distances → [слои]`, предложенным пользователем. + +**Решение:** сохранить плоский список ресурсов сообщества, добавив записи +вариантов с метаданными группы и дистанциями. Показывать их в группах на +существующей странице спрайтов. Отдельные изображения остаются совместимыми; +слои, используемые каталогом, не выводятся повторно отдельными спрайтами. +Автор и описание принадлежат группе. Используется существующий выбор дистанции. + +**Пути:** пользователь подтвердил только локальные файлы es-doc-assets. +Относительный путь считается от community/. `/resource/raw/` адресует game/, +`/resource/community/` адресует community/. Выход за пределы этих папок запрещён. +Слои одной дистанции имеют одинаковые размеры и накладываются в порядке массива. + +**План реализации:** + +1. Добавить интеграционные тесты загрузки JSON, групп, поиска, порядка слоёв, + дистанций, безопасности путей, обновления кэша и совместимости одиночных файлов. + Запустить и подтвердить отсутствие новой функциональности. +2. Добавить загрузчик каталога и карту слоёв в CONFIG. Некорректные записи + пропускать с предупреждением; при повреждённом JSON сохранять прежний каталог. +3. Расширить существующий конвейер сборки и миниатюр отдельным пространством + кэша и маршрутами пользовательских спрайтов. Обновлять при изменении слоёв. +4. Добавить группировку на странице, автора и описание, переиспользуя выбор + дистанции, просмотр, скачивание, фильтрацию и поиск. +5. Добавить документацию и пустой каталог в репозиторий ассетов. Запустить + Python- и JavaScript-тесты, проверки синтаксиса и diff; проверить страницу. + +**Технологии:** Python / FastAPI / Pillow, Jinja, существующий JavaScript. diff --git a/static/js/resources.js b/static/js/resources.js index af6c509..3f41cbe 100644 --- a/static/js/resources.js +++ b/static/js/resources.js @@ -139,6 +139,7 @@ const raw = option.dataset.raw || ''; const thumb = option.dataset.thumb || ''; const file = option.dataset.file || ''; + const label = option.dataset.label || code; name.textContent = code; distance.textContent = option.dataset.distance; @@ -146,9 +147,9 @@ if (imageLink && image && raw && thumb) { imageLink.href = raw; - imageLink.dataset.zoom = code; + imageLink.dataset.zoom = label; imageLink.dataset.file = file; - imageLink.setAttribute('aria-label', `Открыть «${code}» в полном размере`); + imageLink.setAttribute('aria-label', `Открыть «${label}» в полном размере`); image.src = thumb; image.alt = ''; } @@ -229,7 +230,7 @@ row.addEventListener('res:sprite-filter', event => { const query = event.detail.query; const match = query - ? options.find(option => option.dataset.code.toLowerCase().includes(query)) + ? options.find(option => `${option.dataset.code} ${option.dataset.distance}`.toLowerCase().includes(query)) : options[0]; if (match) { select(match); diff --git a/templates/resources_list.html b/templates/resources_list.html index 11256a4..9f498c0 100644 --- a/templates/resources_list.html +++ b/templates/resources_list.html @@ -54,8 +54,8 @@ data-variant-count="{{ family.variants|length }}"> {% if primary.thumb %} + data-media-surface data-zoom="{{ family.title or primary.code }}" data-file="{{ primary.name }}.webp" + aria-label="Открыть «{{ family.title or primary.code }}» в полном размере"> {% else %} @@ -66,7 +66,8 @@ @@ -75,6 +76,7 @@ {% if variant.rid != primary.rid %}id="{{ variant.rid }}"{% endif %} data-code="{{ variant.code }}" data-name="{{ variant.name }}" data-distance="{{ variant.distance }}" + data-label="{{ family.title or variant.code }}" {% if variant.raw %}data-raw="{{ variant.raw }}"{% endif %} {% if variant.thumb %}data-thumb="{{ variant.thumb }}"{% endif %} data-file="{{ variant.name }}.webp" @@ -87,7 +89,7 @@
- {{ res.copy_button(primary.code) }} + {% if collection == 'original' %}{{ res.copy_button(primary.code) }}{% endif %} {% if primary.raw %}{{ res.dl_button(primary.raw, primary.name + '.webp') }}{% endif %}
@@ -227,6 +229,42 @@

{% endfor %} + {% elif category_meta.media == 'sprites' and collection == 'community' %} + {% if community_sprite_groups %} + + {% for group in community_sprite_groups %} +
+

{{ group.title }}

+ {% if group.desc %}

{{ group.desc }}

{% endif %} + {% if group.author.name %} +

Автор: + {% if group.author.link %}{{ group.author.name }} + {% else %}{{ group.author.name }}{% endif %} +

+ {% endif %} +
    + {% for family in group.families %}{{ sprite_row(family) }}{% endfor %} +
+
+ {% endfor %} + {% endif %} + {% set plain_sprites = items|rejectattr('sprite_group')|list %} + {% if plain_sprites %} +
+ {% if community_sprite_groups %}

Отдельные изображения

+ {% else %}

Спрайты

{% endif %} +
    + {% for item in plain_sprites %}{{ image_row(item, sprite=true) }}{% endfor %} +
+
+ {% endif %} + {% elif category_meta.media == 'characters' %}