|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +from moviepy.editor import ColorClip, CompositeVideoClip |
| 5 | +from moviepy.video.tools.subtitles import SubtitlesClip |
| 6 | + |
| 7 | +from funclip.subtitle_renderer import make_text_clip |
| 8 | + |
| 9 | + |
| 10 | +ROOT = Path(__file__).resolve().parents[1] |
| 11 | +FONT_PATH = ROOT / "font" / "STHeitiMedium.ttc" |
| 12 | + |
| 13 | + |
| 14 | +def _foreground_rgb(color): |
| 15 | + clip = make_text_clip("字幕 Test", FONT_PATH, 48, color) |
| 16 | + frame = clip.get_frame(0) |
| 17 | + mask = clip.mask.get_frame(0) |
| 18 | + |
| 19 | + assert mask.min() == 0 |
| 20 | + assert mask.max() > 0.9 |
| 21 | + return frame[mask > 0.5] |
| 22 | + |
| 23 | + |
| 24 | +def test_subtitle_renderer_preserves_selected_colors(): |
| 25 | + red = _foreground_rgb("red").mean(axis=0) |
| 26 | + green = _foreground_rgb("green").mean(axis=0) |
| 27 | + black = _foreground_rgb("black").mean(axis=0) |
| 28 | + white = _foreground_rgb("white").mean(axis=0) |
| 29 | + |
| 30 | + assert red[0] > 200 and red[1] < 40 and red[2] < 40 |
| 31 | + assert green[1] > 100 and green[0] < 40 and green[2] < 40 |
| 32 | + assert black.max() < 10 |
| 33 | + assert white.min() > 240 |
| 34 | + |
| 35 | + |
| 36 | +def test_subtitle_renderer_rejects_invalid_font_size(): |
| 37 | + assert make_text_clip("subtitle", FONT_PATH, 48.0, "white").size[0] > 0 |
| 38 | + |
| 39 | + for value in (0, -1, 48.5, "48", True): |
| 40 | + try: |
| 41 | + make_text_clip("subtitle", FONT_PATH, value, "white") |
| 42 | + except (TypeError, ValueError): |
| 43 | + continue |
| 44 | + raise AssertionError(f"font size {value!r} should be rejected") |
| 45 | + |
| 46 | + |
| 47 | +def test_selected_color_reaches_composited_video_frame(): |
| 48 | + background = ColorClip((320, 120), color=(20, 20, 20), duration=1) |
| 49 | + subtitles = SubtitlesClip( |
| 50 | + [((0, 1), "字幕")], |
| 51 | + lambda text: make_text_clip(text, FONT_PATH, 48, "red"), |
| 52 | + ).set_pos(("center", "bottom")) |
| 53 | + frame = CompositeVideoClip([background, subtitles]).get_frame(0.5) |
| 54 | + |
| 55 | + red_pixels = ( |
| 56 | + (frame[:, :, 0] > 180) |
| 57 | + & (frame[:, :, 1] < 60) |
| 58 | + & (frame[:, :, 2] < 60) |
| 59 | + ) |
| 60 | + assert red_pixels.sum() > 100 |
| 61 | + |
| 62 | + |
| 63 | +def test_pillow_is_an_explicit_runtime_dependency(): |
| 64 | + requirements = { |
| 65 | + line.strip().lower() |
| 66 | + for line in (ROOT / "requirements.txt").read_text(encoding="utf-8").splitlines() |
| 67 | + if line.strip() and not line.lstrip().startswith("#") |
| 68 | + } |
| 69 | + |
| 70 | + assert "pillow" in requirements |
0 commit comments