core.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. """Streaming GIF / WebM extraction. No GUI dependency."""
  2. from dataclasses import dataclass
  3. from pathlib import Path
  4. import math
  5. import re
  6. import json
  7. from io import BytesIO
  8. from typing import Callable, Optional
  9. from PIL import Image, ImageOps
  10. class Cancelled(Exception):
  11. pass
  12. @dataclass(frozen=True)
  13. class Options:
  14. count: int = 16
  15. prefix: str = "frame"
  16. left: float = 0
  17. right: float = 100
  18. top: float = 0
  19. bottom: float = 100
  20. scale_axis: str = "none"
  21. target: int = 256
  22. def validate(self):
  23. if self.count < 1:
  24. raise ValueError("采样帧数必须大于 0。")
  25. if (not self.prefix or self.prefix != self.prefix.strip()
  26. or re.search(r'[<>:"/\\|?*\x00-\x1f]', self.prefix)
  27. or self.prefix.endswith('.')):
  28. raise ValueError("前缀不能为空,不能含路径或 Windows 文件名非法字符。")
  29. if not all(math.isfinite(x) for x in (self.left, self.right, self.top, self.bottom)):
  30. raise ValueError("裁剪位置必须是有效数字。")
  31. if not (0 <= self.left < self.right <= 100 and 0 <= self.top < self.bottom <= 100):
  32. raise ValueError("裁剪范围必须满足:0 ≤ 左 < 右 ≤ 100,0 ≤ 上 < 下 ≤ 100。")
  33. if self.scale_axis not in ("none", "width", "height"):
  34. raise ValueError("无效缩放方式。")
  35. if self.scale_axis != "none" and self.target < 1:
  36. raise ValueError("目标像素必须大于 0。")
  37. @dataclass(frozen=True)
  38. class MediaInfo:
  39. count: int
  40. size: tuple
  41. first: Image.Image
  42. @dataclass(frozen=True)
  43. class FrameConfig:
  44. name: str
  45. cx: int = 0
  46. cy: int = 0
  47. source_direction: int = 0
  48. interval: int = 200
  49. mirror: bool = True
  50. def validate(self, prefix):
  51. if not self.name.strip():
  52. raise ValueError('配置 NAME 不能为空。')
  53. if self.source_direction not in (0, 1) or self.interval < 1:
  54. raise ValueError('朝向须为 0 或 1,INTERVAL 须为正整数。')
  55. if re.fullmatch(r'(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?', prefix):
  56. raise ValueError('配置文件前缀不能使用 Windows 保留名。')
  57. def build_frame_config(info, options, config):
  58. config.validate(options.prefix)
  59. _, (width, height) = geometry(info.size, options)
  60. data = {'NAME': config.name, 'HEAD_POS': [-max(0, width // 2 - 15), -max(0, height // 4 - 15)]}
  61. for action in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'):
  62. direction = 0 if action.endswith(('R', 'D')) else 1
  63. # Mirror [cx, cx + width) about the character anchor (x = 0).
  64. cx = config.cx if not config.mirror or direction == config.source_direction else -config.cx - width
  65. image_prefix = f'{options.prefix}_{direction if config.mirror else 0}'
  66. data[action] = {'Len': options.count, 'Cx': cx, 'Cy': config.cy,
  67. 'Cloth': {'IMG': [f'{image_prefix}_{i}.png' for i in range(options.count)],
  68. 'CX': [0] * options.count, 'CY': [0] * options.count}}
  69. data['INTERVAL'] = config.interval
  70. return data
  71. def frames(path: Path):
  72. """Decode sequentially, allowing Pillow to composite GIF disposal frames."""
  73. path = Path(path)
  74. if path.suffix.lower() == '.gif':
  75. with Image.open(path) as source:
  76. for idx in range(source.n_frames):
  77. source.seek(idx)
  78. yield source.convert('RGBA')
  79. elif path.suffix.lower() == '.webm':
  80. import imageio_ffmpeg
  81. reader = imageio_ffmpeg.read_frames(str(path), pix_fmt='rgba', bits_per_pixel=32)
  82. try:
  83. meta = next(reader)
  84. for data in reader:
  85. yield Image.frombytes('RGBA', meta['size'], data)
  86. finally:
  87. reader.close()
  88. else:
  89. raise ValueError("请选择 GIF 或 WebM 文件。")
  90. def inspect_media(path: Path, cancelled=lambda: False) -> MediaInfo:
  91. first = None
  92. count = 0
  93. stream = frames(path)
  94. try:
  95. for frame in stream:
  96. if cancelled():
  97. raise Cancelled()
  98. if first is None:
  99. first = frame.copy()
  100. count += 1
  101. finally:
  102. stream.close()
  103. if first is None:
  104. raise ValueError("文件中没有可读取的帧。")
  105. return MediaInfo(count, first.size, first)
  106. def sample_indices(total: int, count: int):
  107. if not 1 <= count <= total:
  108. raise ValueError(f"采样帧数必须在 1 到 {total} 之间。")
  109. if count == 1:
  110. return [0]
  111. # Include first and last frame. Integer arithmetic avoids float rounding drift.
  112. return [(i * (total - 1) * 2 + count - 1) // (2 * (count - 1)) for i in range(count)]
  113. def geometry(size, options: Options):
  114. options.validate()
  115. width, height = size
  116. box = (round(width * options.left / 100), round(height * options.top / 100),
  117. round(width * options.right / 100), round(height * options.bottom / 100))
  118. w, h = box[2] - box[0], box[3] - box[1]
  119. if min(w, h) < 1:
  120. raise ValueError("裁剪区域不足 1 像素,请扩大裁剪范围。")
  121. if options.scale_axis == 'width':
  122. output = (options.target, max(1, round(h * options.target / w)))
  123. elif options.scale_axis == 'height':
  124. output = (max(1, round(w * options.target / h)), options.target)
  125. else:
  126. output = (w, h)
  127. return box, output
  128. def transform(frame: Image.Image, options: Options):
  129. box, size = geometry(frame.size, options)
  130. result = frame.crop(box)
  131. if result.size != size:
  132. result = result.resize(size, Image.Resampling.LANCZOS)
  133. return result
  134. @dataclass(frozen=True)
  135. class PreviewFrame:
  136. size: tuple
  137. png: bytes
  138. def copy(self):
  139. with Image.open(BytesIO(self.png)) as image:
  140. return image.convert('RGBA')
  141. def preview_samples(path, info, options, bounds=None, cancelled=lambda: False):
  142. """Cache selected output frames losslessly, compressed instead of raw RGBA."""
  143. indices = sample_indices(info.count, options.count)
  144. geometry(info.size, options)
  145. samples = []
  146. stream = frames(path)
  147. try:
  148. for index, frame in enumerate(stream):
  149. if cancelled():
  150. raise Cancelled()
  151. if index == indices[len(samples)]:
  152. image = transform(frame, options)
  153. buffer = BytesIO()
  154. image.save(buffer, format='PNG')
  155. samples.append(PreviewFrame(image.size, buffer.getvalue()))
  156. if len(samples) == len(indices):
  157. return indices, samples
  158. raise ValueError('源文件帧数发生变化,请重新选择文件。')
  159. finally:
  160. stream.close()
  161. def export_frames(path: Path, directory: Path, info: MediaInfo, options: Options,
  162. progress: Optional[Callable] = None, cancelled=lambda: False, config=None):
  163. options.validate()
  164. geometry(info.size, options)
  165. indices = sample_indices(info.count, options.count)
  166. directory = Path(directory)
  167. directory.mkdir(parents=True, exist_ok=True)
  168. outputs = [directory / f'{options.prefix}_{i}.png' for i in range(options.count)]
  169. configuration = None
  170. if config is not None:
  171. configuration = build_frame_config(info, options, config)
  172. output_directions = (0, 1) if config.mirror else (0,)
  173. outputs = [directory / f'{options.prefix}_{d}_{i}.png' for d in output_directions for i in range(options.count)]
  174. config_path = directory / f'{options.prefix}.json'
  175. for output in outputs + ([config_path] if configuration is not None else []):
  176. if output.exists():
  177. raise ValueError(f"文件已存在,请更换前缀或输出目录:\n{output}")
  178. created = []
  179. stream = frames(path)
  180. try:
  181. selected = 0
  182. for index, frame in enumerate(stream):
  183. if cancelled():
  184. raise Cancelled()
  185. if index != indices[selected]:
  186. continue
  187. result = transform(frame, options)
  188. directions = ((0, 1) if config.mirror else (0,)) if config is not None else (None,)
  189. for direction in directions:
  190. output = (directory / f'{options.prefix}_{direction}_{selected}.png' if direction is not None else outputs[selected])
  191. image = ImageOps.mirror(result) if config is not None and config.mirror and direction != config.source_direction else result
  192. with output.open('xb') as handle:
  193. created.append(output)
  194. image.save(handle, format='PNG')
  195. selected += 1
  196. if progress:
  197. progress(selected, options.count)
  198. if selected == options.count:
  199. break
  200. if selected != options.count:
  201. raise ValueError("源文件帧数发生变化,请重新选择文件。")
  202. if cancelled():
  203. raise Cancelled()
  204. if configuration is not None:
  205. with config_path.open('x', encoding='utf-8') as handle:
  206. created.append(config_path)
  207. json.dump(configuration, handle, ensure_ascii=False, indent=4)
  208. handle.write('\n')
  209. return outputs
  210. except Exception:
  211. # Roll back only files created by this run; never remove existing files.
  212. for output in created:
  213. output.unlink(missing_ok=True)
  214. raise
  215. finally:
  216. stream.close()