captionm 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- captionm/__init__.py +46 -0
- captionm/discord_ext.py +130 -0
- captionm/emojis.py +96 -0
- captionm/engine.py +397 -0
- captionm/methods.py +377 -0
- captionm/styles.py +99 -0
- captionm-0.1.0.dist-info/METADATA +67 -0
- captionm-0.1.0.dist-info/RECORD +10 -0
- captionm-0.1.0.dist-info/WHEEL +4 -0
- captionm-0.1.0.dist-info/licenses/LICENSE +21 -0
captionm/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from .engine import caption_bytes, recaption_bytes, uncaption_bytes
|
|
2
|
+
from .methods import (
|
|
3
|
+
METHODS,
|
|
4
|
+
AreaRenderer,
|
|
5
|
+
BarRenderer,
|
|
6
|
+
CaptionRenderer,
|
|
7
|
+
OverlayRenderer,
|
|
8
|
+
RecaptionRenderer,
|
|
9
|
+
UncaptionRenderer,
|
|
10
|
+
)
|
|
11
|
+
from .styles import CaptionStyle, EngineLimits
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"caption_bytes",
|
|
15
|
+
"uncaption_bytes",
|
|
16
|
+
"recaption_bytes",
|
|
17
|
+
"CaptionStyle",
|
|
18
|
+
"EngineLimits",
|
|
19
|
+
"CaptionRenderer",
|
|
20
|
+
"BarRenderer",
|
|
21
|
+
"OverlayRenderer",
|
|
22
|
+
"AreaRenderer",
|
|
23
|
+
"UncaptionRenderer",
|
|
24
|
+
"RecaptionRenderer",
|
|
25
|
+
"METHODS",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
from .discord_ext import (
|
|
30
|
+
caption_attachment,
|
|
31
|
+
caption_message,
|
|
32
|
+
recaption_attachment,
|
|
33
|
+
recaption_message,
|
|
34
|
+
uncaption_attachment,
|
|
35
|
+
uncaption_message,
|
|
36
|
+
)
|
|
37
|
+
__all__.extend([
|
|
38
|
+
"caption_attachment",
|
|
39
|
+
"caption_message",
|
|
40
|
+
"uncaption_attachment",
|
|
41
|
+
"uncaption_message",
|
|
42
|
+
"recaption_attachment",
|
|
43
|
+
"recaption_message",
|
|
44
|
+
])
|
|
45
|
+
except ImportError:
|
|
46
|
+
pass
|
captionm/discord_ext.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from dataclasses import replace
|
|
3
|
+
import re
|
|
4
|
+
from urllib.parse import urlparse
|
|
5
|
+
import aiohttp
|
|
6
|
+
import discord
|
|
7
|
+
from .engine import caption_bytes
|
|
8
|
+
from .methods import CaptionRenderer, RecaptionRenderer, UncaptionRenderer
|
|
9
|
+
from .styles import CaptionStyle, EngineLimits
|
|
10
|
+
|
|
11
|
+
_URL_RE = re.compile(r"https?://\S+")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _pick_media(msg: discord.Message) -> tuple[discord.Attachment | str | None, discord.Attachment | None, bool]:
|
|
15
|
+
media = font = None
|
|
16
|
+
force_gif = False
|
|
17
|
+
|
|
18
|
+
for att in msg.attachments:
|
|
19
|
+
if att.filename.lower().endswith((".ttf", ".otf")):
|
|
20
|
+
font = font or att
|
|
21
|
+
elif media is None:
|
|
22
|
+
media = att
|
|
23
|
+
|
|
24
|
+
if media is None:
|
|
25
|
+
for e in msg.embeds:
|
|
26
|
+
is_gifv = e.type == "gifv" or any(
|
|
27
|
+
host in (e.url or "").lower() for host in ("tenor.com", "giphy.com")
|
|
28
|
+
)
|
|
29
|
+
url = (e.video and e.video.url) if is_gifv else None
|
|
30
|
+
url = url or (e.image and e.image.url) or (e.video and e.video.url) or (e.thumbnail and e.thumbnail.url)
|
|
31
|
+
if url:
|
|
32
|
+
media = url
|
|
33
|
+
force_gif = is_gifv
|
|
34
|
+
break
|
|
35
|
+
|
|
36
|
+
if media is None and msg.stickers:
|
|
37
|
+
media = msg.stickers[0].url
|
|
38
|
+
|
|
39
|
+
if media is None and msg.content:
|
|
40
|
+
m = _URL_RE.search(msg.content)
|
|
41
|
+
if m:
|
|
42
|
+
media = m.group(0)
|
|
43
|
+
|
|
44
|
+
return media, font, force_gif
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def _run(
|
|
48
|
+
target: discord.Attachment | discord.Message,
|
|
49
|
+
text: str,
|
|
50
|
+
method: str | CaptionRenderer = "top_bar",
|
|
51
|
+
style: CaptionStyle | None = None,
|
|
52
|
+
limits: EngineLimits | None = None,
|
|
53
|
+
font_attachment: discord.Attachment | None = None,
|
|
54
|
+
) -> discord.File | None:
|
|
55
|
+
limits, style = limits or EngineLimits(), style or CaptionStyle()
|
|
56
|
+
force_gif = False
|
|
57
|
+
|
|
58
|
+
if isinstance(target, discord.Message):
|
|
59
|
+
source, font_att, force_gif = _pick_media(target)
|
|
60
|
+
if source is None and target.reference and target.reference.message_id:
|
|
61
|
+
replied = await target.channel.fetch_message(target.reference.message_id)
|
|
62
|
+
source, r_font, force_gif = _pick_media(replied)
|
|
63
|
+
font_att = font_att or r_font
|
|
64
|
+
if source is None:
|
|
65
|
+
return None
|
|
66
|
+
font_attachment = font_attachment or font_att
|
|
67
|
+
else:
|
|
68
|
+
source = target
|
|
69
|
+
|
|
70
|
+
if font_attachment is not None:
|
|
71
|
+
style = replace(style, font=await font_attachment.read())
|
|
72
|
+
|
|
73
|
+
if isinstance(source, discord.Attachment):
|
|
74
|
+
if limits.max_input_bytes is not None and source.size > limits.max_input_bytes:
|
|
75
|
+
raise ValueError(f"Attachment too large ({source.size} > {limits.max_input_bytes} bytes).")
|
|
76
|
+
raw, filename = await source.read(), source.filename
|
|
77
|
+
else:
|
|
78
|
+
async with aiohttp.ClientSession() as s, s.get(source, headers={"User-Agent": "captionm"}) as r:
|
|
79
|
+
r.raise_for_status()
|
|
80
|
+
raw = await r.read()
|
|
81
|
+
if limits.max_input_bytes is not None and len(raw) > limits.max_input_bytes:
|
|
82
|
+
raise ValueError(f"Media too large ({len(raw)} > {limits.max_input_bytes} bytes).")
|
|
83
|
+
filename = urlparse(source).path.rsplit("/", 1)[-1] or None
|
|
84
|
+
|
|
85
|
+
buf, ext = await asyncio.to_thread(
|
|
86
|
+
caption_bytes,
|
|
87
|
+
raw,
|
|
88
|
+
text,
|
|
89
|
+
method,
|
|
90
|
+
style,
|
|
91
|
+
limits,
|
|
92
|
+
filename,
|
|
93
|
+
"gif" if force_gif else None,
|
|
94
|
+
)
|
|
95
|
+
return discord.File(buf, filename=f"captioned.{ext}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
caption_attachment = _run
|
|
99
|
+
caption_message = _run
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def uncaption_attachment(
|
|
103
|
+
target: discord.Attachment | discord.Message,
|
|
104
|
+
position: str = "top",
|
|
105
|
+
tolerance: int = 40,
|
|
106
|
+
height: int | None = None,
|
|
107
|
+
limits: EngineLimits | None = None,
|
|
108
|
+
) -> discord.File | None:
|
|
109
|
+
return await _run(target, "", UncaptionRenderer(position, tolerance, height), limits=limits)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
uncaption_message = uncaption_attachment
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
async def recaption_attachment(
|
|
116
|
+
target: discord.Attachment | discord.Message,
|
|
117
|
+
text: str,
|
|
118
|
+
position: str = "top",
|
|
119
|
+
method: str | CaptionRenderer = "top_bar",
|
|
120
|
+
style: CaptionStyle | None = None,
|
|
121
|
+
tolerance: int = 40,
|
|
122
|
+
height: int | None = None,
|
|
123
|
+
limits: EngineLimits | None = None,
|
|
124
|
+
font_attachment: discord.Attachment | None = None,
|
|
125
|
+
) -> discord.File | None:
|
|
126
|
+
renderer = RecaptionRenderer(position, method, tolerance, height)
|
|
127
|
+
return await _run(target, text, renderer, style, limits, font_attachment)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
recaption_message = recaption_attachment
|
captionm/emojis.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from functools import lru_cache
|
|
2
|
+
import io
|
|
3
|
+
import re
|
|
4
|
+
import urllib.request
|
|
5
|
+
from PIL import Image, ImageDraw
|
|
6
|
+
|
|
7
|
+
_DISCORD_EMOJI_RE = re.compile(r"<a?:[a-zA-Z0-9_]+:(\d+)>")
|
|
8
|
+
_UNICODE_EMOJI_RE = re.compile(
|
|
9
|
+
"["
|
|
10
|
+
"\U0001F1E0-\U0001F1FF"
|
|
11
|
+
"\U0001F300-\U0001F5FF"
|
|
12
|
+
"\U0001F600-\U0001F64F"
|
|
13
|
+
"\U0001F680-\U0001F6FF"
|
|
14
|
+
"\U0001F700-\U0001F77F"
|
|
15
|
+
"\U0001F900-\U0001F9FF"
|
|
16
|
+
"\U0001FA00-\U0001FAFF"
|
|
17
|
+
"\u2600-\u27BF"
|
|
18
|
+
"](?:\uFE0F|\U0001F3FB-\U0001F3FF|\u200D[\U0001F1E0-\U0001FAFF\u2600-\u27BF\uFE0F])*"
|
|
19
|
+
)
|
|
20
|
+
_TOKEN_RE = re.compile(f"({_DISCORD_EMOJI_RE.pattern}|{_UNICODE_EMOJI_RE.pattern})")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@lru_cache(maxsize=256)
|
|
24
|
+
def _fetch_emoji(url: str) -> Image.Image | None:
|
|
25
|
+
try:
|
|
26
|
+
req = urllib.request.Request(url, headers={"User-Agent": "captionm"})
|
|
27
|
+
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
28
|
+
return Image.open(io.BytesIO(resp.read())).convert("RGBA")
|
|
29
|
+
except Exception:
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _get_emoji_image(token: str) -> Image.Image | None:
|
|
34
|
+
m = _DISCORD_EMOJI_RE.fullmatch(token)
|
|
35
|
+
if m:
|
|
36
|
+
return _fetch_emoji(f"https://cdn.discordapp.com/emojis/{m.group(1)}.png?size=128")
|
|
37
|
+
|
|
38
|
+
codepoints = "-".join(f"{ord(c):x}" for c in token if ord(c) != 0xFE0F)
|
|
39
|
+
return _fetch_emoji(
|
|
40
|
+
f"https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/{codepoints}.png"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def tokenize(text: str) -> list[tuple[bool, str]]:
|
|
45
|
+
tokens: list[tuple[bool, str]] = []
|
|
46
|
+
pos = 0
|
|
47
|
+
for m in _TOKEN_RE.finditer(text):
|
|
48
|
+
if m.start() > pos:
|
|
49
|
+
tokens.append((False, text[pos:m.start()]))
|
|
50
|
+
tokens.append((True, m.group(0)))
|
|
51
|
+
pos = m.end()
|
|
52
|
+
if pos < len(text):
|
|
53
|
+
tokens.append((False, text[pos:]))
|
|
54
|
+
return tokens
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def measure_line(draw: ImageDraw.ImageDraw, line: str, font, render_emojis: bool = True) -> float:
|
|
58
|
+
if not render_emojis:
|
|
59
|
+
return draw.textlength(line, font=font)
|
|
60
|
+
width = 0.0
|
|
61
|
+
emoji_size = int(font.size * 1.05)
|
|
62
|
+
for is_emoji, part in tokenize(line):
|
|
63
|
+
if is_emoji:
|
|
64
|
+
width += emoji_size
|
|
65
|
+
else:
|
|
66
|
+
width += draw.textlength(part, font=font)
|
|
67
|
+
return width
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def draw_line(
|
|
71
|
+
canvas: Image.Image,
|
|
72
|
+
draw: ImageDraw.ImageDraw,
|
|
73
|
+
pos: tuple[float, float],
|
|
74
|
+
line: str,
|
|
75
|
+
font,
|
|
76
|
+
fill,
|
|
77
|
+
stroke_width: int = 0,
|
|
78
|
+
stroke_fill=None,
|
|
79
|
+
render_emojis: bool = True,
|
|
80
|
+
) -> None:
|
|
81
|
+
x, y = pos
|
|
82
|
+
if not render_emojis:
|
|
83
|
+
draw.text((x, y), line, fill=fill, font=font, stroke_width=stroke_width, stroke_fill=stroke_fill)
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
emoji_size = int(font.size * 1.05)
|
|
87
|
+
for is_emoji, part in tokenize(line):
|
|
88
|
+
if is_emoji:
|
|
89
|
+
em = _get_emoji_image(part)
|
|
90
|
+
if em is not None:
|
|
91
|
+
resized = em.resize((emoji_size, emoji_size), Image.Resampling.LANCZOS)
|
|
92
|
+
canvas.paste(resized, (int(x), int(y)), resized)
|
|
93
|
+
x += emoji_size
|
|
94
|
+
continue
|
|
95
|
+
draw.text((x, y), part, fill=fill, font=font, stroke_width=stroke_width, stroke_fill=stroke_fill)
|
|
96
|
+
x += draw.textlength(part, font=font)
|
captionm/engine.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import time
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from PIL import Image, UnidentifiedImageError
|
|
5
|
+
from .methods import METHODS, CaptionRenderer, RecaptionRenderer, UncaptionRenderer
|
|
6
|
+
from .styles import CaptionStyle, EngineLimits
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
import pillow_heif
|
|
10
|
+
pillow_heif.register_heif_opener()
|
|
11
|
+
except ImportError:
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
_IMAGE_FORMAT_MAP: dict[str, tuple[str, str]] = {
|
|
15
|
+
"GIF": ("GIF", "gif"),
|
|
16
|
+
"PNG": ("PNG", "png"),
|
|
17
|
+
"JPEG": ("JPEG", "jpg"),
|
|
18
|
+
"JPG": ("JPEG", "jpg"),
|
|
19
|
+
"WEBP": ("WEBP", "webp"),
|
|
20
|
+
"BMP": ("BMP", "bmp"),
|
|
21
|
+
"TIFF": ("TIFF", "tiff"),
|
|
22
|
+
"ICO": ("ICO", "ico"),
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
_VIDEO_FORMAT_MAP: dict[str, tuple[str, str, str]] = {
|
|
26
|
+
"mp4": ("mp4", "libx264", "mp4"),
|
|
27
|
+
"mov": ("mov", "libx264", "mov"),
|
|
28
|
+
"mkv": ("matroska", "libx264", "mkv"),
|
|
29
|
+
"matroska": ("matroska", "libx264", "mkv"),
|
|
30
|
+
"webm": ("webm", "libvpx", "webm"),
|
|
31
|
+
"avi": ("avi", "mpeg4", "avi"),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _check_deadline(deadline: float | None) -> None:
|
|
36
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
37
|
+
raise TimeoutError("Captioning exceeded the configured time limit.")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _downscale(img: Image.Image, max_dim: int | None) -> Image.Image:
|
|
41
|
+
if max_dim is None or max(img.width, img.height) <= max_dim:
|
|
42
|
+
return img
|
|
43
|
+
scale = max_dim / max(img.width, img.height)
|
|
44
|
+
new_size = (max(2, int(img.width * scale)), max(2, int(img.height * scale)))
|
|
45
|
+
return img.resize(new_size, Image.Resampling.LANCZOS)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _apply_output_size(img: Image.Image, output_size: tuple[int, int] | None) -> Image.Image:
|
|
49
|
+
if output_size is None:
|
|
50
|
+
return img
|
|
51
|
+
return img.resize(output_size, Image.Resampling.LANCZOS)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _ensure_even(img: Image.Image) -> Image.Image:
|
|
55
|
+
w = img.width + (img.width % 2)
|
|
56
|
+
h = img.height + (img.height % 2)
|
|
57
|
+
if (w, h) == img.size:
|
|
58
|
+
return img
|
|
59
|
+
canvas = Image.new("RGB", (w, h), (0, 0, 0))
|
|
60
|
+
canvas.paste(img, (0, 0))
|
|
61
|
+
return canvas
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _to_gif_frame(img: Image.Image) -> Image.Image:
|
|
65
|
+
rgb = img.convert("RGB")
|
|
66
|
+
try:
|
|
67
|
+
return rgb.quantize(
|
|
68
|
+
colors=256,
|
|
69
|
+
method=Image.Quantize.LIBIMAGEQUANT,
|
|
70
|
+
dither=Image.Dither.FLOYDSTEINBERG,
|
|
71
|
+
)
|
|
72
|
+
except Exception:
|
|
73
|
+
return rgb.quantize(
|
|
74
|
+
colors=256,
|
|
75
|
+
method=Image.Quantize.FASTOCTREE,
|
|
76
|
+
dither=Image.Dither.FLOYDSTEINBERG,
|
|
77
|
+
)
|
|
78
|
+
finally:
|
|
79
|
+
rgb.close()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _pick_video_output(filename: str | None, container_name: str) -> tuple[str, str, str]:
|
|
83
|
+
if filename:
|
|
84
|
+
ext = Path(filename).suffix.lower().lstrip(".")
|
|
85
|
+
if ext in _VIDEO_FORMAT_MAP:
|
|
86
|
+
return _VIDEO_FORMAT_MAP[ext]
|
|
87
|
+
for token in container_name.lower().split(","):
|
|
88
|
+
token = token.strip()
|
|
89
|
+
if token in _VIDEO_FORMAT_MAP:
|
|
90
|
+
return _VIDEO_FORMAT_MAP[token]
|
|
91
|
+
return ("mp4", "libx264", "mp4")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _caption_video(
|
|
95
|
+
media_bytes: bytes,
|
|
96
|
+
text: str,
|
|
97
|
+
renderer: CaptionRenderer,
|
|
98
|
+
style: CaptionStyle,
|
|
99
|
+
limits: EngineLimits,
|
|
100
|
+
deadline: float | None,
|
|
101
|
+
filename: str | None = None,
|
|
102
|
+
output_format: str | None = None,
|
|
103
|
+
) -> tuple[io.BytesIO, str]:
|
|
104
|
+
try:
|
|
105
|
+
import av
|
|
106
|
+
except ImportError as exc:
|
|
107
|
+
raise RuntimeError(
|
|
108
|
+
"Video support requires PyAV. Install with: pip install av"
|
|
109
|
+
) from exc
|
|
110
|
+
|
|
111
|
+
in_buf = io.BytesIO(media_bytes)
|
|
112
|
+
out_buf = io.BytesIO()
|
|
113
|
+
|
|
114
|
+
with av.open(in_buf) as in_container:
|
|
115
|
+
if not in_container.streams.video:
|
|
116
|
+
raise ValueError("Input file contains no video stream.")
|
|
117
|
+
|
|
118
|
+
in_video = in_container.streams.video[0]
|
|
119
|
+
fps = float(in_video.average_rate or 24)
|
|
120
|
+
|
|
121
|
+
if output_format == "gif":
|
|
122
|
+
gif_frames: list[Image.Image] = []
|
|
123
|
+
apply_fn = None
|
|
124
|
+
frame_count = 0
|
|
125
|
+
duration_ms = max(20, int(1000 / min(fps, 30)))
|
|
126
|
+
|
|
127
|
+
for frame in in_container.decode(video=0):
|
|
128
|
+
_check_deadline(deadline)
|
|
129
|
+
if limits.max_frames is not None and frame_count >= limits.max_frames:
|
|
130
|
+
break
|
|
131
|
+
frame_count += 1
|
|
132
|
+
|
|
133
|
+
pil_frame = _downscale(frame.to_image().convert("RGBA"), limits.max_dimension)
|
|
134
|
+
if apply_fn is None:
|
|
135
|
+
apply_fn = renderer.prepare(pil_frame.size, text, style)
|
|
136
|
+
|
|
137
|
+
captioned = _apply_output_size(apply_fn(pil_frame), style.output_size)
|
|
138
|
+
gif_frames.append(_to_gif_frame(captioned))
|
|
139
|
+
pil_frame.close()
|
|
140
|
+
captioned.close()
|
|
141
|
+
|
|
142
|
+
if not gif_frames:
|
|
143
|
+
raise ValueError("No video frames decoded.")
|
|
144
|
+
|
|
145
|
+
gif_frames[0].save(
|
|
146
|
+
out_buf,
|
|
147
|
+
format="GIF",
|
|
148
|
+
save_all=True,
|
|
149
|
+
append_images=gif_frames[1:],
|
|
150
|
+
duration=duration_ms,
|
|
151
|
+
loop=0,
|
|
152
|
+
disposal=2,
|
|
153
|
+
)
|
|
154
|
+
for f in gif_frames:
|
|
155
|
+
f.close()
|
|
156
|
+
out_buf.seek(0)
|
|
157
|
+
return out_buf, "gif"
|
|
158
|
+
|
|
159
|
+
in_audio = in_container.streams.audio[0] if in_container.streams.audio else None
|
|
160
|
+
out_fmt, out_codec, out_ext = _pick_video_output(filename, in_container.format.name)
|
|
161
|
+
|
|
162
|
+
with av.open(out_buf, mode="w", format=out_fmt) as out_container:
|
|
163
|
+
out_video = None
|
|
164
|
+
out_audio = None
|
|
165
|
+
if in_audio is not None:
|
|
166
|
+
try:
|
|
167
|
+
out_audio = out_container.add_stream(template=in_audio)
|
|
168
|
+
except Exception:
|
|
169
|
+
out_audio = None
|
|
170
|
+
|
|
171
|
+
apply_fn = None
|
|
172
|
+
frame_count = 0
|
|
173
|
+
|
|
174
|
+
for packet in in_container.demux():
|
|
175
|
+
_check_deadline(deadline)
|
|
176
|
+
if packet.dts is None:
|
|
177
|
+
continue
|
|
178
|
+
|
|
179
|
+
if out_audio is not None and packet.stream == in_audio:
|
|
180
|
+
try:
|
|
181
|
+
packet.stream = out_audio
|
|
182
|
+
out_container.mux(packet)
|
|
183
|
+
except Exception:
|
|
184
|
+
pass
|
|
185
|
+
elif packet.stream == in_video:
|
|
186
|
+
for frame in packet.decode():
|
|
187
|
+
_check_deadline(deadline)
|
|
188
|
+
if limits.max_frames is not None and frame_count >= limits.max_frames:
|
|
189
|
+
break
|
|
190
|
+
frame_count += 1
|
|
191
|
+
|
|
192
|
+
pil_frame = _downscale(frame.to_image().convert("RGBA"), limits.max_dimension)
|
|
193
|
+
if apply_fn is None:
|
|
194
|
+
apply_fn = renderer.prepare(pil_frame.size, text, style)
|
|
195
|
+
|
|
196
|
+
captioned = _apply_output_size(apply_fn(pil_frame), style.output_size)
|
|
197
|
+
rgb = _ensure_even(captioned.convert("RGB"))
|
|
198
|
+
|
|
199
|
+
if out_video is None:
|
|
200
|
+
out_video = out_container.add_stream(out_codec, rate=in_video.average_rate or 30)
|
|
201
|
+
out_video.width = rgb.width
|
|
202
|
+
out_video.height = rgb.height
|
|
203
|
+
out_video.pix_fmt = "yuv420p"
|
|
204
|
+
|
|
205
|
+
new_frame = av.VideoFrame.from_image(rgb)
|
|
206
|
+
for out_pkt in out_video.encode(new_frame):
|
|
207
|
+
out_container.mux(out_pkt)
|
|
208
|
+
|
|
209
|
+
pil_frame.close()
|
|
210
|
+
captioned.close()
|
|
211
|
+
rgb.close()
|
|
212
|
+
|
|
213
|
+
if limits.max_frames is not None and frame_count >= limits.max_frames:
|
|
214
|
+
break
|
|
215
|
+
|
|
216
|
+
if out_video is not None:
|
|
217
|
+
for out_pkt in out_video.encode(None):
|
|
218
|
+
out_container.mux(out_pkt)
|
|
219
|
+
|
|
220
|
+
out_buf.seek(0)
|
|
221
|
+
return out_buf, out_ext
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def caption_bytes(
|
|
225
|
+
media_bytes: bytes,
|
|
226
|
+
text: str,
|
|
227
|
+
method: str | CaptionRenderer = "top_bar",
|
|
228
|
+
style: CaptionStyle | None = None,
|
|
229
|
+
limits: EngineLimits | None = None,
|
|
230
|
+
filename: str | None = None,
|
|
231
|
+
output_format: str | None = None,
|
|
232
|
+
) -> tuple[io.BytesIO, str]:
|
|
233
|
+
style = style or CaptionStyle()
|
|
234
|
+
limits = limits or EngineLimits()
|
|
235
|
+
deadline = (
|
|
236
|
+
time.monotonic() + limits.timeout_seconds
|
|
237
|
+
if limits.timeout_seconds is not None
|
|
238
|
+
else None
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
if limits.max_input_bytes is not None and len(media_bytes) > limits.max_input_bytes:
|
|
242
|
+
raise ValueError(
|
|
243
|
+
f"Input exceeds max_input_bytes ({limits.max_input_bytes} bytes)."
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
renderer = METHODS[method] if isinstance(method, str) else method
|
|
247
|
+
|
|
248
|
+
prev_max_pixels = Image.MAX_IMAGE_PIXELS
|
|
249
|
+
if limits.max_pixels is not None:
|
|
250
|
+
Image.MAX_IMAGE_PIXELS = limits.max_pixels
|
|
251
|
+
try:
|
|
252
|
+
img = Image.open(io.BytesIO(media_bytes))
|
|
253
|
+
except UnidentifiedImageError:
|
|
254
|
+
Image.MAX_IMAGE_PIXELS = prev_max_pixels
|
|
255
|
+
return _caption_video(
|
|
256
|
+
media_bytes, text, renderer, style, limits, deadline, filename, output_format
|
|
257
|
+
)
|
|
258
|
+
finally:
|
|
259
|
+
Image.MAX_IMAGE_PIXELS = prev_max_pixels
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
src_fmt = (img.format or "PNG").upper()
|
|
263
|
+
n_frames = getattr(img, "n_frames", 1)
|
|
264
|
+
out = io.BytesIO()
|
|
265
|
+
|
|
266
|
+
if src_fmt == "GIF" or n_frames > 1:
|
|
267
|
+
frames: list[Image.Image] = []
|
|
268
|
+
durations: list[int] = []
|
|
269
|
+
apply_fn = None
|
|
270
|
+
target_frames = (
|
|
271
|
+
min(n_frames, limits.max_frames)
|
|
272
|
+
if limits.max_frames is not None
|
|
273
|
+
else n_frames
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
for idx in range(target_frames):
|
|
277
|
+
_check_deadline(deadline)
|
|
278
|
+
try:
|
|
279
|
+
img.seek(idx)
|
|
280
|
+
except EOFError:
|
|
281
|
+
break
|
|
282
|
+
|
|
283
|
+
rgba = _downscale(img.convert("RGBA"), limits.max_dimension)
|
|
284
|
+
if apply_fn is None:
|
|
285
|
+
apply_fn = renderer.prepare(rgba.size, text, style)
|
|
286
|
+
|
|
287
|
+
rendered = _apply_output_size(apply_fn(rgba), style.output_size)
|
|
288
|
+
rgba.close()
|
|
289
|
+
|
|
290
|
+
if src_fmt == "GIF" or output_format == "gif":
|
|
291
|
+
frames.append(_to_gif_frame(rendered))
|
|
292
|
+
rendered.close()
|
|
293
|
+
else:
|
|
294
|
+
frames.append(rendered)
|
|
295
|
+
durations.append(int(img.info.get("duration", 100) or 100))
|
|
296
|
+
|
|
297
|
+
if output_format == "gif" or src_fmt == "GIF":
|
|
298
|
+
frames[0].save(
|
|
299
|
+
out,
|
|
300
|
+
format="GIF",
|
|
301
|
+
save_all=True,
|
|
302
|
+
append_images=frames[1:],
|
|
303
|
+
duration=durations,
|
|
304
|
+
loop=img.info.get("loop", 0),
|
|
305
|
+
disposal=2,
|
|
306
|
+
)
|
|
307
|
+
ext = "gif"
|
|
308
|
+
elif src_fmt == "WEBP":
|
|
309
|
+
frames[0].save(
|
|
310
|
+
out,
|
|
311
|
+
format="WEBP",
|
|
312
|
+
save_all=True,
|
|
313
|
+
append_images=frames[1:],
|
|
314
|
+
duration=durations,
|
|
315
|
+
loop=img.info.get("loop", 0),
|
|
316
|
+
)
|
|
317
|
+
ext = "webp"
|
|
318
|
+
else:
|
|
319
|
+
frames[0].save(
|
|
320
|
+
out,
|
|
321
|
+
format="PNG",
|
|
322
|
+
save_all=True,
|
|
323
|
+
append_images=frames[1:],
|
|
324
|
+
duration=durations,
|
|
325
|
+
loop=img.info.get("loop", 0),
|
|
326
|
+
)
|
|
327
|
+
ext = "png"
|
|
328
|
+
|
|
329
|
+
for f in frames:
|
|
330
|
+
f.close()
|
|
331
|
+
out.seek(0)
|
|
332
|
+
return out, ext
|
|
333
|
+
|
|
334
|
+
rgba = _downscale(img.convert("RGBA"), limits.max_dimension)
|
|
335
|
+
rendered = _apply_output_size(renderer.render(rgba, text, style), style.output_size)
|
|
336
|
+
rgba.close()
|
|
337
|
+
|
|
338
|
+
save_fmt, ext = _IMAGE_FORMAT_MAP.get(src_fmt, ("PNG", "png"))
|
|
339
|
+
if save_fmt in ("JPEG", "BMP"):
|
|
340
|
+
to_save = rendered.convert("RGB")
|
|
341
|
+
to_save.save(out, format=save_fmt)
|
|
342
|
+
to_save.close()
|
|
343
|
+
else:
|
|
344
|
+
rendered.save(out, format=save_fmt)
|
|
345
|
+
rendered.close()
|
|
346
|
+
|
|
347
|
+
out.seek(0)
|
|
348
|
+
return out, ext
|
|
349
|
+
finally:
|
|
350
|
+
img.close()
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def uncaption_bytes(
|
|
354
|
+
media_bytes: bytes,
|
|
355
|
+
position: str = "top",
|
|
356
|
+
tolerance: int = 40,
|
|
357
|
+
height: int | None = None,
|
|
358
|
+
limits: EngineLimits | None = None,
|
|
359
|
+
filename: str | None = None,
|
|
360
|
+
output_format: str | None = None,
|
|
361
|
+
) -> tuple[io.BytesIO, str]:
|
|
362
|
+
return caption_bytes(
|
|
363
|
+
media_bytes,
|
|
364
|
+
"",
|
|
365
|
+
method=UncaptionRenderer(position=position, tolerance=tolerance, height=height),
|
|
366
|
+
limits=limits,
|
|
367
|
+
filename=filename,
|
|
368
|
+
output_format=output_format,
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def recaption_bytes(
|
|
373
|
+
media_bytes: bytes,
|
|
374
|
+
text: str,
|
|
375
|
+
position: str = "top",
|
|
376
|
+
method: str | CaptionRenderer = "top_bar",
|
|
377
|
+
style: CaptionStyle | None = None,
|
|
378
|
+
tolerance: int = 40,
|
|
379
|
+
height: int | None = None,
|
|
380
|
+
limits: EngineLimits | None = None,
|
|
381
|
+
filename: str | None = None,
|
|
382
|
+
output_format: str | None = None,
|
|
383
|
+
) -> tuple[io.BytesIO, str]:
|
|
384
|
+
return caption_bytes(
|
|
385
|
+
media_bytes,
|
|
386
|
+
text,
|
|
387
|
+
method=RecaptionRenderer(
|
|
388
|
+
uncaption_position=position,
|
|
389
|
+
caption_method=method,
|
|
390
|
+
tolerance=tolerance,
|
|
391
|
+
height=height,
|
|
392
|
+
),
|
|
393
|
+
style=style,
|
|
394
|
+
limits=limits,
|
|
395
|
+
filename=filename,
|
|
396
|
+
output_format=output_format,
|
|
397
|
+
)
|
captionm/methods.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Callable
|
|
3
|
+
import textwrap
|
|
4
|
+
from PIL import Image, ImageColor, ImageDraw
|
|
5
|
+
from .emojis import draw_line, measure_line
|
|
6
|
+
from .styles import CaptionStyle
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CaptionRenderer(ABC):
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def render(self, frame: Image.Image, text: str, style: CaptionStyle) -> Image.Image:
|
|
12
|
+
...
|
|
13
|
+
|
|
14
|
+
def prepare(
|
|
15
|
+
self, frame_size: tuple[int, int], text: str, style: CaptionStyle
|
|
16
|
+
) -> Callable[[Image.Image], Image.Image]:
|
|
17
|
+
return lambda frame: self.render(frame, text, style)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _to_rgba(color, opacity: float = 1.0) -> tuple[int, int, int, int]:
|
|
21
|
+
if isinstance(color, str):
|
|
22
|
+
rgba = ImageColor.getcolor(color, "RGBA")
|
|
23
|
+
elif len(color) == 3:
|
|
24
|
+
rgba = (color[0], color[1], color[2], 255)
|
|
25
|
+
else:
|
|
26
|
+
rgba = tuple(color)
|
|
27
|
+
alpha = max(0, min(255, int(rgba[3] * opacity)))
|
|
28
|
+
return (rgba[0], rgba[1], rgba[2], alpha)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _wrap_text(text: str, font, max_width: int) -> list[str]:
|
|
32
|
+
avg_w = max(1, font.getlength("A"))
|
|
33
|
+
max_chars = max(4, int(max_width / avg_w))
|
|
34
|
+
lines: list[str] = []
|
|
35
|
+
for paragraph in text.splitlines() or [""]:
|
|
36
|
+
wrapped = textwrap.wrap(paragraph.strip(), width=max_chars)
|
|
37
|
+
lines.extend(wrapped or [""])
|
|
38
|
+
return lines or [""]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _make_background(size: tuple[int, int], style: CaptionStyle) -> Image.Image:
|
|
42
|
+
w, h = size
|
|
43
|
+
bg_img = style.load_bg_image((w, h))
|
|
44
|
+
if bg_img is not None:
|
|
45
|
+
if style.bg_opacity < 1.0:
|
|
46
|
+
alpha = bg_img.getchannel("A").point(lambda a: int(a * style.bg_opacity))
|
|
47
|
+
bg_img.putalpha(alpha)
|
|
48
|
+
base = bg_img
|
|
49
|
+
else:
|
|
50
|
+
base = Image.new("RGBA", (w, h), _to_rgba(style.bg_color, style.bg_opacity))
|
|
51
|
+
|
|
52
|
+
if style.bg_radius > 0:
|
|
53
|
+
mask = Image.new("L", (w, h), 0)
|
|
54
|
+
ImageDraw.Draw(mask).rounded_rectangle(
|
|
55
|
+
(0, 0, w - 1, h - 1), radius=style.bg_radius, fill=255
|
|
56
|
+
)
|
|
57
|
+
out = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
|
58
|
+
out.paste(base, (0, 0), mask)
|
|
59
|
+
return out
|
|
60
|
+
return base
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _draw_lines(
|
|
64
|
+
canvas: Image.Image,
|
|
65
|
+
lines: list[str],
|
|
66
|
+
font,
|
|
67
|
+
box: tuple[int, int, int, int],
|
|
68
|
+
style: CaptionStyle,
|
|
69
|
+
) -> None:
|
|
70
|
+
x0, y0, bw, bh = box
|
|
71
|
+
draw = ImageDraw.Draw(canvas)
|
|
72
|
+
line_h = int(font.size * style.line_spacing)
|
|
73
|
+
total_h = len(lines) * line_h
|
|
74
|
+
pad_x = int(bw * style.margin_x)
|
|
75
|
+
|
|
76
|
+
if style.valign == "top":
|
|
77
|
+
y = y0 + int(font.size * style.padding_ratio)
|
|
78
|
+
elif style.valign == "bottom":
|
|
79
|
+
y = y0 + bh - total_h - int(font.size * style.padding_ratio)
|
|
80
|
+
else:
|
|
81
|
+
y = y0 + (bh - total_h) // 2
|
|
82
|
+
|
|
83
|
+
for line in lines:
|
|
84
|
+
w = measure_line(draw, line, font, style.render_emojis)
|
|
85
|
+
if style.align == "left":
|
|
86
|
+
x = x0 + pad_x
|
|
87
|
+
elif style.align == "right":
|
|
88
|
+
x = x0 + bw - w - pad_x
|
|
89
|
+
else:
|
|
90
|
+
x = x0 + (bw - w) / 2
|
|
91
|
+
draw_line(
|
|
92
|
+
canvas,
|
|
93
|
+
draw,
|
|
94
|
+
(x, y),
|
|
95
|
+
line,
|
|
96
|
+
font=font,
|
|
97
|
+
fill=style.text_color,
|
|
98
|
+
stroke_width=style.stroke_width,
|
|
99
|
+
stroke_fill=style.stroke_color,
|
|
100
|
+
render_emojis=style.render_emojis,
|
|
101
|
+
)
|
|
102
|
+
y += line_h
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _resolve_box(
|
|
106
|
+
frame_size: tuple[int, int], area: tuple[float, float, float, float]
|
|
107
|
+
) -> tuple[int, int, int, int]:
|
|
108
|
+
fw, fh = frame_size
|
|
109
|
+
ax, ay, aw, ah = area
|
|
110
|
+
if all(0.0 <= v <= 1.0 for v in area):
|
|
111
|
+
return (int(ax * fw), int(ay * fh), max(1, int(aw * fw)), max(1, int(ah * fh)))
|
|
112
|
+
return (int(ax), int(ay), max(1, int(aw)), max(1, int(ah)))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _detect_bar_height(
|
|
116
|
+
frame: Image.Image,
|
|
117
|
+
position: str = "top",
|
|
118
|
+
tolerance: int = 40,
|
|
119
|
+
max_ratio: float = 0.5,
|
|
120
|
+
) -> int:
|
|
121
|
+
rgb = frame.convert("RGB")
|
|
122
|
+
w, h = rgb.size
|
|
123
|
+
sample_w = min(w, 120)
|
|
124
|
+
small = rgb.resize((sample_w, h), Image.Resampling.BILINEAR)
|
|
125
|
+
px = small.load()
|
|
126
|
+
|
|
127
|
+
max_scan = int(h * max_ratio)
|
|
128
|
+
if max_scan < 12:
|
|
129
|
+
return 0
|
|
130
|
+
|
|
131
|
+
start_y = 0 if position == "top" else h - 1
|
|
132
|
+
step = 1 if position == "top" else -1
|
|
133
|
+
bg = px[0, start_y]
|
|
134
|
+
|
|
135
|
+
edge_ok = sum(
|
|
136
|
+
1
|
|
137
|
+
for x in range(sample_w)
|
|
138
|
+
if all(abs(px[x, start_y][c] - bg[c]) <= tolerance for c in range(3))
|
|
139
|
+
)
|
|
140
|
+
if edge_ok / sample_w < 0.85:
|
|
141
|
+
return 0
|
|
142
|
+
|
|
143
|
+
bar_h = 0
|
|
144
|
+
margin = max(2, int(sample_w * 0.04))
|
|
145
|
+
for i in range(max_scan):
|
|
146
|
+
y = start_y + (i * step)
|
|
147
|
+
left_ok = (
|
|
148
|
+
sum(
|
|
149
|
+
1
|
|
150
|
+
for x in range(margin)
|
|
151
|
+
if all(abs(px[x, y][c] - bg[c]) <= tolerance for c in range(3))
|
|
152
|
+
)
|
|
153
|
+
>= margin * 0.7
|
|
154
|
+
)
|
|
155
|
+
right_ok = (
|
|
156
|
+
sum(
|
|
157
|
+
1
|
|
158
|
+
for x in range(sample_w - margin, sample_w)
|
|
159
|
+
if all(abs(px[x, y][c] - bg[c]) <= tolerance for c in range(3))
|
|
160
|
+
)
|
|
161
|
+
>= margin * 0.7
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
if not (left_ok and right_ok):
|
|
165
|
+
break
|
|
166
|
+
|
|
167
|
+
bar_h = i + 1
|
|
168
|
+
|
|
169
|
+
return bar_h if bar_h >= 12 else 0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class BarRenderer(CaptionRenderer):
|
|
173
|
+
def __init__(self, position: str = "top"):
|
|
174
|
+
self.position = position
|
|
175
|
+
|
|
176
|
+
def _build_bar(self, width: int, text: str, style: CaptionStyle) -> Image.Image:
|
|
177
|
+
text = text.upper() if style.uppercase else text
|
|
178
|
+
font = style.load_font(width)
|
|
179
|
+
max_text_w = max(20, int(width * (1.0 - 2 * style.margin_x)))
|
|
180
|
+
lines = _wrap_text(text, font, max_text_w)
|
|
181
|
+
|
|
182
|
+
line_h = int(font.size * style.line_spacing)
|
|
183
|
+
pad = int(font.size * style.padding_ratio)
|
|
184
|
+
bar_h = style.bar_height or ((len(lines) * line_h) + (pad * 2))
|
|
185
|
+
if style.min_bar_height is not None:
|
|
186
|
+
bar_h = max(bar_h, style.min_bar_height)
|
|
187
|
+
if style.max_bar_height is not None:
|
|
188
|
+
bar_h = min(bar_h, style.max_bar_height)
|
|
189
|
+
|
|
190
|
+
bar = _make_background((width, max(1, bar_h)), style)
|
|
191
|
+
_draw_lines(bar, lines, font, (0, 0, width, bar.height), style)
|
|
192
|
+
return bar
|
|
193
|
+
|
|
194
|
+
def prepare(
|
|
195
|
+
self, frame_size: tuple[int, int], text: str, style: CaptionStyle
|
|
196
|
+
) -> Callable[[Image.Image], Image.Image]:
|
|
197
|
+
fw, fh = frame_size
|
|
198
|
+
bar = self._build_bar(fw, text, style)
|
|
199
|
+
bar_h = bar.height
|
|
200
|
+
out_size = (fw, fh + bar_h)
|
|
201
|
+
bg_fill = _to_rgba(style.bg_color, style.bg_opacity)
|
|
202
|
+
position = self.position
|
|
203
|
+
|
|
204
|
+
def apply(frame: Image.Image) -> Image.Image:
|
|
205
|
+
canvas = Image.new("RGBA", out_size, bg_fill)
|
|
206
|
+
if position == "top":
|
|
207
|
+
canvas.paste(bar, (0, 0), bar)
|
|
208
|
+
canvas.paste(frame, (0, bar_h), frame)
|
|
209
|
+
else:
|
|
210
|
+
canvas.paste(frame, (0, 0), frame)
|
|
211
|
+
canvas.paste(bar, (0, fh), bar)
|
|
212
|
+
return canvas
|
|
213
|
+
|
|
214
|
+
return apply
|
|
215
|
+
|
|
216
|
+
def render(self, frame: Image.Image, text: str, style: CaptionStyle) -> Image.Image:
|
|
217
|
+
return self.prepare(frame.size, text, style)(frame)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class OverlayRenderer(CaptionRenderer):
|
|
221
|
+
def __init__(self, position: str = "bottom"):
|
|
222
|
+
self.position = position
|
|
223
|
+
|
|
224
|
+
def prepare(
|
|
225
|
+
self, frame_size: tuple[int, int], text: str, style: CaptionStyle
|
|
226
|
+
) -> Callable[[Image.Image], Image.Image]:
|
|
227
|
+
fw, fh = frame_size
|
|
228
|
+
layer = Image.new("RGBA", (fw, fh), (0, 0, 0, 0))
|
|
229
|
+
text = text.upper() if style.uppercase else text
|
|
230
|
+
font = style.load_font(fw)
|
|
231
|
+
max_text_w = max(20, int(fw * (1.0 - 2 * style.margin_x)))
|
|
232
|
+
lines = _wrap_text(text, font, max_text_w)
|
|
233
|
+
|
|
234
|
+
line_h = int(font.size * style.line_spacing)
|
|
235
|
+
total_h = len(lines) * line_h
|
|
236
|
+
pad_y = int(fh * style.margin_y)
|
|
237
|
+
|
|
238
|
+
if style.caption_area is not None:
|
|
239
|
+
box = _resolve_box(frame_size, style.caption_area)
|
|
240
|
+
else:
|
|
241
|
+
box_h = total_h + int(font.size * style.padding_ratio)
|
|
242
|
+
if self.position == "top":
|
|
243
|
+
y0 = pad_y
|
|
244
|
+
elif self.position == "center":
|
|
245
|
+
y0 = (fh - box_h) // 2
|
|
246
|
+
else:
|
|
247
|
+
y0 = fh - box_h - pad_y
|
|
248
|
+
box = (int(fw * style.margin_x), y0, max_text_w, box_h)
|
|
249
|
+
|
|
250
|
+
if (
|
|
251
|
+
style.bg_image is not None
|
|
252
|
+
or (style.bg_opacity > 0 and _to_rgba(style.bg_color, style.bg_opacity)[3] > 0)
|
|
253
|
+
):
|
|
254
|
+
if style.caption_area is not None or style.bg_image is not None or style.bg_radius > 0:
|
|
255
|
+
bg = _make_background((box[2], box[3]), style)
|
|
256
|
+
layer.paste(bg, (box[0], box[1]), bg)
|
|
257
|
+
|
|
258
|
+
_draw_lines(layer, lines, font, box, style)
|
|
259
|
+
|
|
260
|
+
def apply(frame: Image.Image) -> Image.Image:
|
|
261
|
+
out = frame.copy()
|
|
262
|
+
out.alpha_composite(layer)
|
|
263
|
+
return out
|
|
264
|
+
|
|
265
|
+
return apply
|
|
266
|
+
|
|
267
|
+
def render(self, frame: Image.Image, text: str, style: CaptionStyle) -> Image.Image:
|
|
268
|
+
return self.prepare(frame.size, text, style)(frame)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class AreaRenderer(CaptionRenderer):
|
|
272
|
+
def prepare(
|
|
273
|
+
self, frame_size: tuple[int, int], text: str, style: CaptionStyle
|
|
274
|
+
) -> Callable[[Image.Image], Image.Image]:
|
|
275
|
+
fw, fh = frame_size
|
|
276
|
+
area = style.caption_area or (0.05, 0.05, 0.90, 0.20)
|
|
277
|
+
bx, by, bw, bh = _resolve_box(frame_size, area)
|
|
278
|
+
|
|
279
|
+
layer = Image.new("RGBA", (fw, fh), (0, 0, 0, 0))
|
|
280
|
+
bg = _make_background((bw, bh), style)
|
|
281
|
+
layer.paste(bg, (bx, by), bg)
|
|
282
|
+
|
|
283
|
+
text = text.upper() if style.uppercase else text
|
|
284
|
+
font = style.load_font(bw)
|
|
285
|
+
max_text_w = max(20, int(bw * (1.0 - 2 * style.margin_x)))
|
|
286
|
+
lines = _wrap_text(text, font, max_text_w)
|
|
287
|
+
_draw_lines(layer, lines, font, (bx, by, bw, bh), style)
|
|
288
|
+
|
|
289
|
+
def apply(frame: Image.Image) -> Image.Image:
|
|
290
|
+
out = frame.copy()
|
|
291
|
+
out.alpha_composite(layer)
|
|
292
|
+
return out
|
|
293
|
+
|
|
294
|
+
return apply
|
|
295
|
+
|
|
296
|
+
def render(self, frame: Image.Image, text: str, style: CaptionStyle) -> Image.Image:
|
|
297
|
+
return self.prepare(frame.size, text, style)(frame)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class UncaptionRenderer(CaptionRenderer):
|
|
301
|
+
def __init__(self, position: str = "top", tolerance: int = 40, height: int | None = None):
|
|
302
|
+
self.position = position
|
|
303
|
+
self.tolerance = tolerance
|
|
304
|
+
self.height = height
|
|
305
|
+
|
|
306
|
+
def prepare(
|
|
307
|
+
self, frame_size: tuple[int, int], text: str, style: CaptionStyle
|
|
308
|
+
) -> Callable[[Image.Image], Image.Image]:
|
|
309
|
+
crop_h: int | None = self.height
|
|
310
|
+
position = self.position
|
|
311
|
+
tolerance = self.tolerance
|
|
312
|
+
|
|
313
|
+
def apply(frame: Image.Image) -> Image.Image:
|
|
314
|
+
nonlocal crop_h
|
|
315
|
+
if crop_h is None:
|
|
316
|
+
crop_h = _detect_bar_height(frame, position=position, tolerance=tolerance)
|
|
317
|
+
if crop_h <= 0 or crop_h >= frame.height:
|
|
318
|
+
return frame.copy()
|
|
319
|
+
if position == "top":
|
|
320
|
+
return frame.crop((0, crop_h, frame.width, frame.height))
|
|
321
|
+
return frame.crop((0, 0, frame.width, frame.height - crop_h))
|
|
322
|
+
|
|
323
|
+
return apply
|
|
324
|
+
|
|
325
|
+
def render(self, frame: Image.Image, text: str, style: CaptionStyle) -> Image.Image:
|
|
326
|
+
return self.prepare(frame.size, text, style)(frame)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
class RecaptionRenderer(CaptionRenderer):
|
|
330
|
+
def __init__(
|
|
331
|
+
self,
|
|
332
|
+
uncaption_position: str = "top",
|
|
333
|
+
caption_method: str | CaptionRenderer = "top_bar",
|
|
334
|
+
tolerance: int = 40,
|
|
335
|
+
height: int | None = None,
|
|
336
|
+
):
|
|
337
|
+
self.uncaption = UncaptionRenderer(uncaption_position, tolerance, height)
|
|
338
|
+
self.caption_method = caption_method
|
|
339
|
+
|
|
340
|
+
def prepare(
|
|
341
|
+
self, frame_size: tuple[int, int], text: str, style: CaptionStyle
|
|
342
|
+
) -> Callable[[Image.Image], Image.Image]:
|
|
343
|
+
uncap_apply = self.uncaption.prepare(frame_size, "", style)
|
|
344
|
+
cap_renderer = (
|
|
345
|
+
METHODS[self.caption_method]
|
|
346
|
+
if isinstance(self.caption_method, str)
|
|
347
|
+
else self.caption_method
|
|
348
|
+
)
|
|
349
|
+
cap_apply: Callable[[Image.Image], Image.Image] | None = None
|
|
350
|
+
|
|
351
|
+
def apply(frame: Image.Image) -> Image.Image:
|
|
352
|
+
nonlocal cap_apply
|
|
353
|
+
cropped = uncap_apply(frame)
|
|
354
|
+
if cap_apply is None:
|
|
355
|
+
cap_apply = cap_renderer.prepare(cropped.size, text, style)
|
|
356
|
+
out = cap_apply(cropped)
|
|
357
|
+
cropped.close()
|
|
358
|
+
return out
|
|
359
|
+
|
|
360
|
+
return apply
|
|
361
|
+
|
|
362
|
+
def render(self, frame: Image.Image, text: str, style: CaptionStyle) -> Image.Image:
|
|
363
|
+
return self.prepare(frame.size, text, style)(frame)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
METHODS: dict[str, CaptionRenderer] = {
|
|
367
|
+
"top_bar": BarRenderer("top"),
|
|
368
|
+
"bottom_bar": BarRenderer("bottom"),
|
|
369
|
+
"overlay_top": OverlayRenderer("top"),
|
|
370
|
+
"overlay_bottom": OverlayRenderer("bottom"),
|
|
371
|
+
"overlay_center": OverlayRenderer("center"),
|
|
372
|
+
"area": AreaRenderer(),
|
|
373
|
+
"uncaption_top": UncaptionRenderer("top"),
|
|
374
|
+
"uncaption_bottom": UncaptionRenderer("bottom"),
|
|
375
|
+
"recaption_top": RecaptionRenderer("top", "top_bar"),
|
|
376
|
+
"recaption_bottom": RecaptionRenderer("bottom", "bottom_bar"),
|
|
377
|
+
}
|
captionm/styles.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import io
|
|
4
|
+
import sys
|
|
5
|
+
from PIL import Image, ImageFont
|
|
6
|
+
|
|
7
|
+
FontSource = str | Path | bytes | None
|
|
8
|
+
ImageSource = str | Path | bytes | Image.Image | None
|
|
9
|
+
Color = tuple[int, int, int] | tuple[int, int, int, int] | str
|
|
10
|
+
|
|
11
|
+
_WARNED_DEFAULT_FONT = False
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class EngineLimits:
|
|
16
|
+
max_input_bytes: int | None = None
|
|
17
|
+
max_pixels: int | None = None
|
|
18
|
+
max_dimension: int | None = None
|
|
19
|
+
max_frames: int | None = None
|
|
20
|
+
timeout_seconds: float | None = None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class CaptionStyle:
|
|
25
|
+
font: FontSource = None
|
|
26
|
+
font_size: int | None = None
|
|
27
|
+
font_scale: float = 0.10
|
|
28
|
+
text_color: Color = (0, 0, 0, 255)
|
|
29
|
+
bg_color: Color = (255, 255, 255, 255)
|
|
30
|
+
bg_image: ImageSource = None
|
|
31
|
+
bg_opacity: float = 1.0
|
|
32
|
+
bg_radius: int = 0
|
|
33
|
+
stroke_width: int = 0
|
|
34
|
+
stroke_color: Color = (0, 0, 0, 255)
|
|
35
|
+
align: str = "center"
|
|
36
|
+
valign: str = "center"
|
|
37
|
+
padding_ratio: float = 0.6
|
|
38
|
+
margin_x: float = 0.05
|
|
39
|
+
margin_y: float = 0.05
|
|
40
|
+
line_spacing: float = 1.22
|
|
41
|
+
uppercase: bool = False
|
|
42
|
+
render_emojis: bool = True
|
|
43
|
+
bar_height: int | None = None
|
|
44
|
+
min_bar_height: int | None = None
|
|
45
|
+
max_bar_height: int | None = None
|
|
46
|
+
caption_area: tuple[float, float, float, float] | None = None
|
|
47
|
+
output_size: tuple[int, int] | None = None
|
|
48
|
+
|
|
49
|
+
def load_font(self, image_width: int) -> ImageFont.FreeTypeFont:
|
|
50
|
+
global _WARNED_DEFAULT_FONT
|
|
51
|
+
size = self.font_size or max(16, int(image_width * self.font_scale))
|
|
52
|
+
|
|
53
|
+
if isinstance(self.font, (str, Path)):
|
|
54
|
+
p = Path(self.font).expanduser().resolve()
|
|
55
|
+
if not p.is_file():
|
|
56
|
+
raise FileNotFoundError(f"Font file not found at: {p}")
|
|
57
|
+
return ImageFont.truetype(str(p), size)
|
|
58
|
+
|
|
59
|
+
if isinstance(self.font, bytes):
|
|
60
|
+
return ImageFont.truetype(io.BytesIO(self.font), size)
|
|
61
|
+
|
|
62
|
+
cwd = Path.cwd()
|
|
63
|
+
for search_dir in (cwd / "fonts", cwd):
|
|
64
|
+
if search_dir.is_dir():
|
|
65
|
+
for pattern in ("*.ttf", "*.otf"):
|
|
66
|
+
matches = sorted(search_dir.glob(pattern))
|
|
67
|
+
if matches:
|
|
68
|
+
return ImageFont.truetype(str(matches[0]), size)
|
|
69
|
+
|
|
70
|
+
if not _WARNED_DEFAULT_FONT:
|
|
71
|
+
print(
|
|
72
|
+
"[captionm] No custom font provided or found in your bot folder; "
|
|
73
|
+
"using the built-in package font.",
|
|
74
|
+
file=sys.stderr,
|
|
75
|
+
)
|
|
76
|
+
_WARNED_DEFAULT_FONT = True
|
|
77
|
+
|
|
78
|
+
pkg_fonts = Path(__file__).resolve().parent / "fonts"
|
|
79
|
+
if pkg_fonts.is_dir():
|
|
80
|
+
for pattern in ("*.ttf", "*.otf"):
|
|
81
|
+
matches = sorted(pkg_fonts.glob(pattern))
|
|
82
|
+
if matches:
|
|
83
|
+
return ImageFont.truetype(str(matches[0]), size)
|
|
84
|
+
|
|
85
|
+
return ImageFont.load_default(size=size)
|
|
86
|
+
|
|
87
|
+
def load_bg_image(self, size: tuple[int, int]) -> Image.Image | None:
|
|
88
|
+
if self.bg_image is None:
|
|
89
|
+
return None
|
|
90
|
+
if isinstance(self.bg_image, Image.Image):
|
|
91
|
+
img = self.bg_image.convert("RGBA")
|
|
92
|
+
elif isinstance(self.bg_image, bytes):
|
|
93
|
+
img = Image.open(io.BytesIO(self.bg_image)).convert("RGBA")
|
|
94
|
+
else:
|
|
95
|
+
p = Path(self.bg_image).expanduser().resolve()
|
|
96
|
+
if not p.is_file():
|
|
97
|
+
raise FileNotFoundError(f"Background image not found at: {p}")
|
|
98
|
+
img = Image.open(p).convert("RGBA")
|
|
99
|
+
return img.resize(size, Image.Resampling.LANCZOS)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: captionm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Customizable media captioning engine for images, GIFs, and videos with discord.py support.
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Requires-Dist: av>=12.0.0
|
|
8
|
+
Requires-Dist: pillow>=10.0.0
|
|
9
|
+
Provides-Extra: heif
|
|
10
|
+
Requires-Dist: pillow-heif>=0.16.0; extra == 'heif'
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# captionm
|
|
14
|
+
|
|
15
|
+
simple python library for adding, removing, and replacing captions on images, gifs, and videos. works anywhere (web backends, scripts, discord bots, whatever).
|
|
16
|
+
|
|
17
|
+
## install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install captionm
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
needs python 3.10+. uses pillow and pyav under the hood.
|
|
24
|
+
|
|
25
|
+
## basic usage
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from captionm import caption_bytes, uncaption_bytes, recaption_bytes, CaptionStyle
|
|
29
|
+
|
|
30
|
+
with open("meme.gif", "rb") as f:
|
|
31
|
+
raw = f.read()
|
|
32
|
+
|
|
33
|
+
# add caption
|
|
34
|
+
buf, ext = caption_bytes(raw, "ohfr?")
|
|
35
|
+
|
|
36
|
+
# remove caption bar
|
|
37
|
+
buf, ext = uncaption_bytes(raw)
|
|
38
|
+
|
|
39
|
+
# replace caption
|
|
40
|
+
buf, ext = recaption_bytes(raw, "new text")
|
|
41
|
+
|
|
42
|
+
with open(f"out.{ext}", "wb") as f:
|
|
43
|
+
f.write(buf.read())
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## styling
|
|
47
|
+
|
|
48
|
+
pass `CaptionStyle` if you don't want the default white top bar:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
style = CaptionStyle(
|
|
52
|
+
font="path/to/font.otf",
|
|
53
|
+
text_color="white",
|
|
54
|
+
bg_color="black",
|
|
55
|
+
uppercase=True,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
buf, ext = caption_bytes(raw, "hello", method="bottom_bar", style=style)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
available methods: `top_bar`, `bottom_bar`, `overlay_top`, `overlay_bottom`, `overlay_center`, `area`.
|
|
62
|
+
|
|
63
|
+
## notes
|
|
64
|
+
|
|
65
|
+
- renders unicode emojis and custom discord emojis in color by default (`render_emojis=False` to turn off).
|
|
66
|
+
- if you have `discord.py` installed, `caption_message`, `uncaption_message`, and `recaption_message` are also exported.
|
|
67
|
+
- use `EngineLimits` if you need to cap resolution, frames, file size, or timeout.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
captionm/__init__.py,sha256=TILVMNXknp-TiIZinsS53TnaKAVgfB6rrjvnwdgILQg,994
|
|
2
|
+
captionm/discord_ext.py,sha256=4Rl6eRALVCQZgaBXyr61dnw_FaJ3a2huus27rRdCqMA,4364
|
|
3
|
+
captionm/emojis.py,sha256=MY4Ik9pVU1APFWBuQ4clB__UnC5zbpHgTG5TrkCsTB8,3056
|
|
4
|
+
captionm/engine.py,sha256=pVUlVxOdKNQzWtMRBrhn543dtWj0z-rireVNLcl8vK8,13117
|
|
5
|
+
captionm/methods.py,sha256=L8xCPy7FRfRZD68Oth5U5JGbvpRU_We-AkJcdt8awSg,12776
|
|
6
|
+
captionm/styles.py,sha256=ZlybBCvGFp-FwP7AQqMAtZQuhHDY6XxwZO8yGlH5Ko0,3471
|
|
7
|
+
captionm-0.1.0.dist-info/METADATA,sha256=tRESmPwdwSL28RPoJe-4Nl5mQtuSFSjdCWA7U5k-Md4,1756
|
|
8
|
+
captionm-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
captionm-0.1.0.dist-info/licenses/LICENSE,sha256=anFQAE8NUS8IgkYJC2MBE5ofP6ezfsc6usPZOcq9ULE,1068
|
|
10
|
+
captionm-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 thugyahu-ui
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|