generate_meme.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. #!/usr/bin/env python3
  2. """Generate a meme image by overlaying text on a template.
  3. Usage:
  4. python generate_meme.py <template_id_or_name> <output_path> <text1> [text2] [text3] [text4]
  5. Example:
  6. python generate_meme.py drake ~/.hermes/cache/scratch/meme.png "Writing tests" "Shipping to prod and hoping"
  7. python generate_meme.py "Disaster Girl" ~/.hermes/cache/scratch/meme.png "Top text" "Bottom text"
  8. python generate_meme.py --list # show curated templates
  9. python generate_meme.py --search "distracted" # search all imgflip templates
  10. Templates with custom text positioning are in templates.json (10 curated).
  11. Any of the ~100 popular imgflip templates can also be used by name or ID —
  12. unknown templates get smart default text positioning based on their box_count.
  13. """
  14. import json
  15. import os
  16. import sys
  17. from io import BytesIO
  18. from pathlib import Path
  19. try:
  20. import requests as _requests
  21. except ImportError:
  22. _requests = None
  23. from PIL import Image, ImageDraw, ImageFont
  24. SCRIPT_DIR = Path(__file__).parent
  25. TEMPLATES_FILE = SCRIPT_DIR / "templates.json"
  26. CACHE_DIR = SCRIPT_DIR / ".cache"
  27. IMGFLIP_API = "https://api.imgflip.com/get_memes"
  28. IMGFLIP_CACHE_FILE = CACHE_DIR / "imgflip_memes.json"
  29. IMGFLIP_CACHE_MAX_AGE = 86400 # 24 hours
  30. def _fetch_url(url: str, timeout: int = 15) -> bytes:
  31. """Fetch URL content, using requests if available, else urllib."""
  32. if _requests is not None:
  33. resp = _requests.get(url, timeout=timeout)
  34. resp.raise_for_status()
  35. return resp.content
  36. import urllib.request
  37. return urllib.request.urlopen(url, timeout=timeout).read()
  38. def load_curated_templates() -> dict:
  39. """Load templates with hand-tuned text field positions."""
  40. with open(TEMPLATES_FILE) as f:
  41. return json.load(f)
  42. def _default_fields(box_count: int) -> list:
  43. """Generate sensible default text field positions for unknown templates."""
  44. if box_count <= 0:
  45. box_count = 2
  46. if box_count == 1:
  47. return [{"name": "text", "x_pct": 0.5, "y_pct": 0.5, "w_pct": 0.90, "align": "center"}]
  48. if box_count == 2:
  49. return [
  50. {"name": "top", "x_pct": 0.5, "y_pct": 0.08, "w_pct": 0.95, "align": "center"},
  51. {"name": "bottom", "x_pct": 0.5, "y_pct": 0.92, "w_pct": 0.95, "align": "center"},
  52. ]
  53. # 3+: evenly space vertically
  54. fields = []
  55. for i in range(box_count):
  56. y = 0.08 + (0.84 * i / (box_count - 1)) if box_count > 1 else 0.5
  57. fields.append({
  58. "name": f"text{i+1}",
  59. "x_pct": 0.5,
  60. "y_pct": round(y, 2),
  61. "w_pct": 0.90,
  62. "align": "center",
  63. })
  64. return fields
  65. def fetch_imgflip_templates() -> list:
  66. """Fetch popular meme templates from imgflip API. Cached for 24h."""
  67. import time
  68. CACHE_DIR.mkdir(exist_ok=True)
  69. # Check cache
  70. if IMGFLIP_CACHE_FILE.exists():
  71. age = time.time() - IMGFLIP_CACHE_FILE.stat().st_mtime
  72. if age < IMGFLIP_CACHE_MAX_AGE:
  73. with open(IMGFLIP_CACHE_FILE) as f:
  74. return json.load(f)
  75. try:
  76. data = json.loads(_fetch_url(IMGFLIP_API))
  77. memes = data.get("data", {}).get("memes", [])
  78. with open(IMGFLIP_CACHE_FILE, "w") as f:
  79. json.dump(memes, f)
  80. return memes
  81. except Exception as e:
  82. # If fetch fails and we have stale cache, use it
  83. if IMGFLIP_CACHE_FILE.exists():
  84. with open(IMGFLIP_CACHE_FILE) as f:
  85. return json.load(f)
  86. print(f"Warning: could not fetch imgflip templates: {e}", file=sys.stderr)
  87. return []
  88. def _slugify(name: str) -> str:
  89. """Convert a template name to a slug for matching."""
  90. return name.lower().replace(" ", "-").replace("'", "").replace("\"", "")
  91. def resolve_template(identifier: str) -> dict:
  92. """Resolve a template by curated ID, imgflip name, or imgflip ID.
  93. Returns dict with: name, url, fields, source.
  94. """
  95. curated = load_curated_templates()
  96. # 1. Exact curated ID match
  97. if identifier in curated:
  98. tmpl = curated[identifier]
  99. return {**tmpl, "source": "curated"}
  100. # 2. Slugified curated match
  101. slug = _slugify(identifier)
  102. for tid, tmpl in curated.items():
  103. if _slugify(tmpl["name"]) == slug or tid == slug:
  104. return {**tmpl, "source": "curated"}
  105. # 3. Search imgflip templates
  106. imgflip_memes = fetch_imgflip_templates()
  107. slug_lower = slug.lower()
  108. id_lower = identifier.strip()
  109. for meme in imgflip_memes:
  110. meme_slug = _slugify(meme["name"])
  111. # Check curated first for this imgflip template (custom positioning)
  112. for tid, ctmpl in curated.items():
  113. if _slugify(ctmpl["name"]) == meme_slug:
  114. if meme_slug == slug_lower or meme["id"] == id_lower:
  115. return {**ctmpl, "source": "curated"}
  116. if meme_slug == slug_lower or meme["id"] == id_lower or slug_lower in meme_slug:
  117. return {
  118. "name": meme["name"],
  119. "url": meme["url"],
  120. "fields": _default_fields(meme.get("box_count", 2)),
  121. "source": "imgflip",
  122. }
  123. return None
  124. def get_template_image(url: str) -> Image.Image:
  125. """Download a template image, caching it locally."""
  126. CACHE_DIR.mkdir(exist_ok=True)
  127. # Use URL hash as cache key
  128. cache_name = url.split("/")[-1]
  129. cache_path = CACHE_DIR / cache_name
  130. # Always cache as PNG to avoid JPEG/RGBA conflicts
  131. cache_path = cache_path.with_suffix(".png")
  132. if cache_path.exists():
  133. return Image.open(cache_path).convert("RGBA")
  134. data = _fetch_url(url)
  135. img = Image.open(BytesIO(data)).convert("RGBA")
  136. img.save(cache_path, "PNG")
  137. return img
  138. def find_font(size: int) -> ImageFont.FreeTypeFont:
  139. """Find a bold font for meme text. Tries Impact, then falls back."""
  140. candidates = [
  141. "/usr/share/fonts/truetype/msttcorefonts/Impact.ttf",
  142. "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
  143. "/usr/share/fonts/liberation-sans/LiberationSans-Bold.ttf",
  144. "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
  145. "/usr/share/fonts/dejavu-sans/DejaVuSans-Bold.ttf",
  146. "/System/Library/Fonts/Helvetica.ttc",
  147. "/System/Library/Fonts/SFCompact.ttf",
  148. ]
  149. for path in candidates:
  150. if os.path.exists(path):
  151. try:
  152. return ImageFont.truetype(path, size)
  153. except OSError:
  154. continue
  155. # Last resort: Pillow default
  156. try:
  157. return ImageFont.truetype("DejaVuSans-Bold", size)
  158. except OSError:
  159. return ImageFont.load_default()
  160. def _wrap_text(text: str, font: ImageFont.FreeTypeFont, max_width: int) -> str:
  161. """Word-wrap text to fit within max_width pixels. Never breaks mid-word."""
  162. words = text.split()
  163. if not words:
  164. return text
  165. lines = []
  166. current_line = words[0]
  167. for word in words[1:]:
  168. test_line = current_line + " " + word
  169. if font.getlength(test_line) <= max_width:
  170. current_line = test_line
  171. else:
  172. lines.append(current_line)
  173. current_line = word
  174. lines.append(current_line)
  175. return "\n".join(lines)
  176. def draw_outlined_text(
  177. draw: ImageDraw.ImageDraw,
  178. text: str,
  179. x: int,
  180. y: int,
  181. font_size: int,
  182. max_width: int,
  183. align: str = "center",
  184. ):
  185. """Draw white text with black outline, auto-scaled to fit max_width."""
  186. # Auto-scale: reduce font size until text fits reasonably
  187. size = font_size
  188. while size > 12:
  189. font = find_font(size)
  190. wrapped = _wrap_text(text, font, max_width)
  191. bbox = draw.multiline_textbbox((0, 0), wrapped, font=font, align=align)
  192. text_w = bbox[2] - bbox[0]
  193. line_count = wrapped.count("\n") + 1
  194. # Accept if width fits and not too many lines
  195. if text_w <= max_width * 1.05 and line_count <= 4:
  196. break
  197. size -= 2
  198. else:
  199. font = find_font(size)
  200. wrapped = _wrap_text(text, font, max_width)
  201. # Measure total text block
  202. bbox = draw.multiline_textbbox((0, 0), wrapped, font=font, align=align)
  203. text_w = bbox[2] - bbox[0]
  204. text_h = bbox[3] - bbox[1]
  205. # Center horizontally at x, vertically at y
  206. tx = x - text_w // 2
  207. ty = y - text_h // 2
  208. # Draw outline (black border)
  209. outline_range = max(2, font.size // 18)
  210. for dx in range(-outline_range, outline_range + 1):
  211. for dy in range(-outline_range, outline_range + 1):
  212. if dx == 0 and dy == 0:
  213. continue
  214. draw.multiline_text(
  215. (tx + dx, ty + dy), wrapped, font=font, fill="black", align=align
  216. )
  217. # Draw main text (white)
  218. draw.multiline_text((tx, ty), wrapped, font=font, fill="white", align=align)
  219. def _overlay_on_image(img: Image.Image, texts: list, fields: list) -> Image.Image:
  220. """Overlay meme text directly on an image using field positions."""
  221. draw = ImageDraw.Draw(img)
  222. w, h = img.size
  223. base_font_size = max(16, min(w, h) // 12)
  224. for i, field in enumerate(fields):
  225. if i >= len(texts):
  226. break
  227. text = texts[i].strip()
  228. if not text:
  229. continue
  230. fx = int(field["x_pct"] * w)
  231. fy = int(field["y_pct"] * h)
  232. fw = int(field["w_pct"] * w)
  233. draw_outlined_text(draw, text, fx, fy, base_font_size, fw, field.get("align", "center"))
  234. return img
  235. def _add_bars(img: Image.Image, texts: list) -> Image.Image:
  236. """Add black bars with white text above/below the image.
  237. Distributes texts across bars: first text on top bar, last text on
  238. bottom bar, any middle texts overlaid on the image center.
  239. """
  240. w, h = img.size
  241. bar_font_size = max(20, w // 16)
  242. font = find_font(bar_font_size)
  243. padding = bar_font_size // 2
  244. top_text = texts[0].strip() if texts else ""
  245. bottom_text = texts[-1].strip() if len(texts) > 1 else ""
  246. middle_texts = [t.strip() for t in texts[1:-1]] if len(texts) > 2 else []
  247. def _measure_bar(text: str) -> int:
  248. if not text:
  249. return 0
  250. wrapped = _wrap_text(text, font, int(w * 0.92))
  251. bbox = ImageDraw.Draw(Image.new("RGB", (1, 1))).multiline_textbbox(
  252. (0, 0), wrapped, font=font, align="center"
  253. )
  254. return (bbox[3] - bbox[1]) + padding * 2
  255. top_h = _measure_bar(top_text)
  256. bottom_h = _measure_bar(bottom_text)
  257. new_h = h + top_h + bottom_h
  258. canvas = Image.new("RGB", (w, new_h), (0, 0, 0))
  259. canvas.paste(img.convert("RGB"), (0, top_h))
  260. draw = ImageDraw.Draw(canvas)
  261. if top_text:
  262. wrapped = _wrap_text(top_text, font, int(w * 0.92))
  263. bbox = draw.multiline_textbbox((0, 0), wrapped, font=font, align="center")
  264. tw = bbox[2] - bbox[0]
  265. th = bbox[3] - bbox[1]
  266. tx = (w - tw) // 2
  267. ty = (top_h - th) // 2
  268. draw.multiline_text((tx, ty), wrapped, font=font, fill="white", align="center")
  269. if bottom_text:
  270. wrapped = _wrap_text(bottom_text, font, int(w * 0.92))
  271. bbox = draw.multiline_textbbox((0, 0), wrapped, font=font, align="center")
  272. tw = bbox[2] - bbox[0]
  273. th = bbox[3] - bbox[1]
  274. tx = (w - tw) // 2
  275. ty = top_h + h + (bottom_h - th) // 2
  276. draw.multiline_text((tx, ty), wrapped, font=font, fill="white", align="center")
  277. # Overlay any middle texts centered on the image
  278. if middle_texts:
  279. mid_fields = _default_fields(len(middle_texts))
  280. # Shift y positions to account for top bar offset
  281. for field in mid_fields:
  282. field["y_pct"] = (top_h + field["y_pct"] * h) / new_h
  283. field["w_pct"] = 0.90
  284. _overlay_on_image(canvas, middle_texts, mid_fields)
  285. return canvas
  286. def generate_meme(template_id: str, texts: list[str], output_path: str) -> str:
  287. """Generate a meme from a template and save it. Returns the path."""
  288. tmpl = resolve_template(template_id)
  289. if tmpl is None:
  290. print(f"Unknown template: {template_id}", file=sys.stderr)
  291. print("Use --list to see curated templates or --search to find imgflip templates.", file=sys.stderr)
  292. sys.exit(1)
  293. fields = tmpl["fields"]
  294. print(f"Using template: {tmpl['name']} ({tmpl['source']}, {len(fields)} fields)", file=sys.stderr)
  295. img = get_template_image(tmpl["url"])
  296. img = _overlay_on_image(img, texts, fields)
  297. output = Path(output_path)
  298. if output.suffix.lower() in {".jpg", ".jpeg"}:
  299. img = img.convert("RGB")
  300. img.save(str(output), quality=95)
  301. return str(output)
  302. def generate_from_image(
  303. image_path: str, texts: list[str], output_path: str, use_bars: bool = False
  304. ) -> str:
  305. """Generate a meme from a custom image (e.g. AI-generated). Returns the path."""
  306. img = Image.open(image_path).convert("RGBA")
  307. print(f"Custom image: {img.size[0]}x{img.size[1]}, {len(texts)} text(s), mode={'bars' if use_bars else 'overlay'}", file=sys.stderr)
  308. if use_bars:
  309. result = _add_bars(img, texts)
  310. else:
  311. fields = _default_fields(len(texts))
  312. result = _overlay_on_image(img, texts, fields)
  313. output = Path(output_path)
  314. if output.suffix.lower() in {".jpg", ".jpeg"}:
  315. result = result.convert("RGB")
  316. result.save(str(output), quality=95)
  317. return str(output)
  318. def list_templates():
  319. """Print curated templates with custom positioning."""
  320. templates = load_curated_templates()
  321. print(f"{'ID':<25} {'Name':<30} {'Fields':<8} Best for")
  322. print("-" * 90)
  323. for tid, tmpl in sorted(templates.items()):
  324. fields = len(tmpl["fields"])
  325. print(f"{tid:<25} {tmpl['name']:<30} {fields:<8} {tmpl['best_for']}")
  326. print(f"\n{len(templates)} curated templates with custom text positioning.")
  327. print("Use --search to find any of the ~100 popular imgflip templates.")
  328. def search_templates(query: str):
  329. """Search imgflip templates by name."""
  330. imgflip_memes = fetch_imgflip_templates()
  331. curated = load_curated_templates()
  332. curated_slugs = {_slugify(t["name"]) for t in curated.values()}
  333. query_lower = query.lower()
  334. matches = []
  335. for meme in imgflip_memes:
  336. if query_lower in meme["name"].lower():
  337. slug = _slugify(meme["name"])
  338. has_custom = "curated" if slug in curated_slugs else "default"
  339. matches.append((meme["name"], meme["id"], meme.get("box_count", 2), has_custom))
  340. if not matches:
  341. print(f"No templates found matching '{query}'")
  342. return
  343. print(f"{'Name':<40} {'ID':<12} {'Fields':<8} Positioning")
  344. print("-" * 75)
  345. for name, mid, boxes, positioning in matches:
  346. print(f"{name:<40} {mid:<12} {boxes:<8} {positioning}")
  347. print(f"\n{len(matches)} template(s) found. Use the name or ID as the first argument.")
  348. if __name__ == "__main__":
  349. if len(sys.argv) < 2:
  350. print("Usage: generate_meme.py <template_id_or_name> <output_path> <text1> [text2] ...")
  351. print(" generate_meme.py --image <path> [--bars] <output_path> <text1> [text2] ...")
  352. print(" generate_meme.py --list # curated templates")
  353. print(" generate_meme.py --search <query> # search all imgflip templates")
  354. sys.exit(1)
  355. if sys.argv[1] == "--list":
  356. list_templates()
  357. sys.exit(0)
  358. if sys.argv[1] == "--search":
  359. if len(sys.argv) < 3:
  360. print("Usage: generate_meme.py --search <query>")
  361. sys.exit(1)
  362. search_templates(sys.argv[2])
  363. sys.exit(0)
  364. if sys.argv[1] == "--image":
  365. # Custom image mode: --image <path> [--bars] <output> <text1> ...
  366. args = sys.argv[2:]
  367. if len(args) < 3:
  368. print("Usage: generate_meme.py --image <image_path> [--bars] <output_path> <text1> ...")
  369. sys.exit(1)
  370. image_path = args.pop(0)
  371. use_bars = False
  372. if args and args[0] == "--bars":
  373. use_bars = True
  374. args.pop(0)
  375. if len(args) < 2:
  376. print("Need at least: output_path and one text argument")
  377. sys.exit(1)
  378. output_path = args.pop(0)
  379. result = generate_from_image(image_path, args, output_path, use_bars=use_bars)
  380. print(f"Meme saved to: {result}")
  381. sys.exit(0)
  382. if len(sys.argv) < 4:
  383. print("Need at least: template_id_or_name, output_path, and one text argument")
  384. sys.exit(1)
  385. template_id = sys.argv[1]
  386. output_path = sys.argv[2]
  387. texts = sys.argv[3:]
  388. result = generate_meme(template_id, texts, output_path)
  389. print(f"Meme saved to: {result}")