forked from vycdev/thermal-printer-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmeme_print.py
More file actions
71 lines (57 loc) · 2.78 KB
/
Copy pathmeme_print.py
File metadata and controls
71 lines (57 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python3
"""Print a random meme (meme-api.com, sourced from Reddit) on the S01 printer.
Pulls a random meme from a default mix of safe-for-work meme subreddits, or a
subreddit you name. NSFW posts are skipped by default; static images only (GIFs
and videos are retried past).
Examples:
python meme_print.py # random SFW meme
python meme_print.py --subreddit ProgrammerHumor
python meme_print.py --nsfw # allow NSFW results
python meme_print.py --no-print
"""
from __future__ import annotations
import argparse
from datetime import datetime
from pathlib import Path
from print_common import ROOT, Card, fit_dither, get_bytes, get_json
STATIC_EXT = (".jpg", ".jpeg", ".png", ".webp")
def fetch_meme(subreddit: str | None, allow_nsfw: bool, tries: int = 8) -> dict:
base = "https://meme-api.com/gimme"
url = f"{base}/{subreddit}" if subreddit else base
last = None
for _ in range(tries):
meme = get_json(url)
last = meme
if meme.get("nsfw") and not allow_nsfw:
continue
img = meme.get("url", "")
if not img.lower().split("?")[0].endswith(STATIC_EXT):
continue # skip gifs/videos that won't print
return meme
raise SystemExit(f"Could not find a printable meme after {tries} tries (last: {last and last.get('url')})")
def main() -> int:
parser = argparse.ArgumentParser(description="Print a random meme on the S01 thermal printer.")
parser.add_argument("--subreddit", default=None, help="Pull from a specific subreddit (e.g. ProgrammerHumor).")
parser.add_argument("--nsfw", action="store_true", help="Allow NSFW results (skipped by default).")
parser.add_argument("--out", type=Path, default=ROOT / "meme.png")
parser.add_argument("--darkness", type=int, choices=range(1, 6), default=3)
parser.add_argument("--bottom-feed", type=int, default=24)
parser.add_argument("--no-print", action="store_true")
args = parser.parse_args()
print("Fetching a random meme ...")
meme = fetch_meme(args.subreddit, args.nsfw)
title = meme.get("title", "meme")
sub = meme.get("subreddit", "")
ups = meme.get("ups")
print(f"r/{sub}: {title}" + (f" ({ups} ups)" if ups else ""))
# memes carry text -> a touch of contrast keeps captions legible after dither
img = fit_dither(get_bytes(meme["url"]), Card().inner_w, 420, contrast=1.15, gamma=1.1)
card = Card()
card.title("RANDOM MEME")
card.heading(title, size=15)
card.image(img)
right = f"{ups} ^" if ups else datetime.now().strftime("%Y-%m-%d")
card.footer(f"r/{sub}" if sub else "meme-api.com", right)
return card.finish(args.out, args.bottom_feed, args.darkness, do_print=not args.no_print)
if __name__ == "__main__":
raise SystemExit(main())