| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246 |
- """Streaming GIF / WebM extraction. No GUI dependency."""
- from dataclasses import dataclass
- from pathlib import Path
- import math
- import re
- import json
- from io import BytesIO
- from typing import Callable, Optional
- from PIL import Image, ImageOps
- class Cancelled(Exception):
- pass
- @dataclass(frozen=True)
- class Options:
- count: int = 16
- prefix: str = "frame"
- left: float = 0
- right: float = 100
- top: float = 0
- bottom: float = 100
- scale_axis: str = "none"
- target: int = 256
- def validate(self):
- if self.count < 1:
- raise ValueError("采样帧数必须大于 0。")
- if (not self.prefix or self.prefix != self.prefix.strip()
- or re.search(r'[<>:"/\\|?*\x00-\x1f]', self.prefix)
- or self.prefix.endswith('.')):
- raise ValueError("前缀不能为空,不能含路径或 Windows 文件名非法字符。")
- if not all(math.isfinite(x) for x in (self.left, self.right, self.top, self.bottom)):
- raise ValueError("裁剪位置必须是有效数字。")
- if not (0 <= self.left < self.right <= 100 and 0 <= self.top < self.bottom <= 100):
- raise ValueError("裁剪范围必须满足:0 ≤ 左 < 右 ≤ 100,0 ≤ 上 < 下 ≤ 100。")
- if self.scale_axis not in ("none", "width", "height"):
- raise ValueError("无效缩放方式。")
- if self.scale_axis != "none" and self.target < 1:
- raise ValueError("目标像素必须大于 0。")
- @dataclass(frozen=True)
- class MediaInfo:
- count: int
- size: tuple
- first: Image.Image
- @dataclass(frozen=True)
- class FrameConfig:
- name: str
- cx: int = 0
- cy: int = 0
- source_direction: int = 0
- interval: int = 200
- mirror: bool = True
- def validate(self, prefix):
- if not self.name.strip():
- raise ValueError('配置 NAME 不能为空。')
- if self.source_direction not in (0, 1) or self.interval < 1:
- raise ValueError('朝向须为 0 或 1,INTERVAL 须为正整数。')
- if re.fullmatch(r'(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?', prefix):
- raise ValueError('配置文件前缀不能使用 Windows 保留名。')
- def build_frame_config(info, options, config):
- config.validate(options.prefix)
- _, (width, height) = geometry(info.size, options)
- data = {'NAME': config.name, 'HEAD_POS': [-max(0, width // 2 - 15), -max(0, height // 4 - 15)]}
- for action in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'):
- direction = 0 if action.endswith(('R', 'D')) else 1
- # Mirror [cx, cx + width) about the character anchor (x = 0).
- cx = config.cx if not config.mirror or direction == config.source_direction else -config.cx - width
- image_prefix = f'{options.prefix}_{direction if config.mirror else 0}'
- data[action] = {'Len': options.count, 'Cx': cx, 'Cy': config.cy,
- 'Cloth': {'IMG': [f'{image_prefix}_{i}.png' for i in range(options.count)],
- 'CX': [0] * options.count, 'CY': [0] * options.count}}
- data['INTERVAL'] = config.interval
- return data
- def frames(path: Path):
- """Decode sequentially, allowing Pillow to composite GIF disposal frames."""
- path = Path(path)
- if path.suffix.lower() == '.gif':
- with Image.open(path) as source:
- for idx in range(source.n_frames):
- source.seek(idx)
- yield source.convert('RGBA')
- elif path.suffix.lower() == '.webm':
- import imageio_ffmpeg
- reader = imageio_ffmpeg.read_frames(str(path), pix_fmt='rgba', bits_per_pixel=32)
- try:
- meta = next(reader)
- for data in reader:
- yield Image.frombytes('RGBA', meta['size'], data)
- finally:
- reader.close()
- else:
- raise ValueError("请选择 GIF 或 WebM 文件。")
- def inspect_media(path: Path, cancelled=lambda: False) -> MediaInfo:
- first = None
- count = 0
- stream = frames(path)
- try:
- for frame in stream:
- if cancelled():
- raise Cancelled()
- if first is None:
- first = frame.copy()
- count += 1
- finally:
- stream.close()
- if first is None:
- raise ValueError("文件中没有可读取的帧。")
- return MediaInfo(count, first.size, first)
- def sample_indices(total: int, count: int):
- if not 1 <= count <= total:
- raise ValueError(f"采样帧数必须在 1 到 {total} 之间。")
- if count == 1:
- return [0]
- # Include first and last frame. Integer arithmetic avoids float rounding drift.
- return [(i * (total - 1) * 2 + count - 1) // (2 * (count - 1)) for i in range(count)]
- def geometry(size, options: Options):
- options.validate()
- width, height = size
- box = (round(width * options.left / 100), round(height * options.top / 100),
- round(width * options.right / 100), round(height * options.bottom / 100))
- w, h = box[2] - box[0], box[3] - box[1]
- if min(w, h) < 1:
- raise ValueError("裁剪区域不足 1 像素,请扩大裁剪范围。")
- if options.scale_axis == 'width':
- output = (options.target, max(1, round(h * options.target / w)))
- elif options.scale_axis == 'height':
- output = (max(1, round(w * options.target / h)), options.target)
- else:
- output = (w, h)
- return box, output
- def transform(frame: Image.Image, options: Options):
- box, size = geometry(frame.size, options)
- result = frame.crop(box)
- if result.size != size:
- result = result.resize(size, Image.Resampling.LANCZOS)
- return result
- @dataclass(frozen=True)
- class PreviewFrame:
- size: tuple
- png: bytes
- def copy(self):
- with Image.open(BytesIO(self.png)) as image:
- return image.convert('RGBA')
- def preview_samples(path, info, options, bounds=None, cancelled=lambda: False):
- """Cache selected output frames losslessly, compressed instead of raw RGBA."""
- indices = sample_indices(info.count, options.count)
- geometry(info.size, options)
- samples = []
- stream = frames(path)
- try:
- for index, frame in enumerate(stream):
- if cancelled():
- raise Cancelled()
- if index == indices[len(samples)]:
- image = transform(frame, options)
- buffer = BytesIO()
- image.save(buffer, format='PNG')
- samples.append(PreviewFrame(image.size, buffer.getvalue()))
- if len(samples) == len(indices):
- return indices, samples
- raise ValueError('源文件帧数发生变化,请重新选择文件。')
- finally:
- stream.close()
- def export_frames(path: Path, directory: Path, info: MediaInfo, options: Options,
- progress: Optional[Callable] = None, cancelled=lambda: False, config=None):
- options.validate()
- geometry(info.size, options)
- indices = sample_indices(info.count, options.count)
- directory = Path(directory)
- directory.mkdir(parents=True, exist_ok=True)
- outputs = [directory / f'{options.prefix}_{i}.png' for i in range(options.count)]
- configuration = None
- if config is not None:
- configuration = build_frame_config(info, options, config)
- output_directions = (0, 1) if config.mirror else (0,)
- outputs = [directory / f'{options.prefix}_{d}_{i}.png' for d in output_directions for i in range(options.count)]
- config_path = directory / f'{options.prefix}.json'
- for output in outputs + ([config_path] if configuration is not None else []):
- if output.exists():
- raise ValueError(f"文件已存在,请更换前缀或输出目录:\n{output}")
- created = []
- stream = frames(path)
- try:
- selected = 0
- for index, frame in enumerate(stream):
- if cancelled():
- raise Cancelled()
- if index != indices[selected]:
- continue
- result = transform(frame, options)
- directions = ((0, 1) if config.mirror else (0,)) if config is not None else (None,)
- for direction in directions:
- output = (directory / f'{options.prefix}_{direction}_{selected}.png' if direction is not None else outputs[selected])
- image = ImageOps.mirror(result) if config is not None and config.mirror and direction != config.source_direction else result
- with output.open('xb') as handle:
- created.append(output)
- image.save(handle, format='PNG')
- selected += 1
- if progress:
- progress(selected, options.count)
- if selected == options.count:
- break
- if selected != options.count:
- raise ValueError("源文件帧数发生变化,请重新选择文件。")
- if cancelled():
- raise Cancelled()
- if configuration is not None:
- with config_path.open('x', encoding='utf-8') as handle:
- created.append(config_path)
- json.dump(configuration, handle, ensure_ascii=False, indent=4)
- handle.write('\n')
- return outputs
- except Exception:
- # Roll back only files created by this run; never remove existing files.
- for output in created:
- output.unlink(missing_ok=True)
- raise
- finally:
- stream.close()
|