Created
June 4, 2017 10:52
-
-
Save zopieux/06fa58f54df778e2c2795a0039873f54 to your computer and use it in GitHub Desktop.
Yet another reddis-to-wallpaper script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| from PIL import Image, ImageDraw, ImageFont | |
| import io | |
| import re | |
| import requests | |
| import subprocess | |
| import time | |
| FNAME = '/tmp/wallpaper' | |
| IMGUR_RAW = re.compile(r'^https?://i.imgur.com/([^/]+)$') | |
| IMGUR_PAGE = re.compile(r'^https?://imgur.com/([^/]+)$') | |
| HTTP = requests.session() | |
| HTTP.headers = {'User-agent': 'wallpaper'} | |
| HTTP.timeout = 3 | |
| URL = 'https://www.reddit.com/r/EarthPorn/search.json?sort=top&restrict_sr=on&t=day' | |
| FONT = ImageFont.truetype('DejaVuSerifCondensed.ttf', 50) | |
| def text(text): | |
| size = FONT.getsize(text) | |
| base = Image.new('RGB', size, (0, 0, 0)) | |
| d = ImageDraw.Draw(base) | |
| d.text((0, 0), text, font=FONT, align='center', fill=(255, 255, 255)) | |
| buf = io.BytesIO() | |
| base.save(buf, 'jpeg') | |
| return buf.getvalue() | |
| def feh(content, method='fill'): | |
| with open(FNAME, 'wb') as f: | |
| f.write(content) | |
| subprocess.run(['feh', f'--bg-{method}', FNAME], check=True) | |
| def get_url(): | |
| data = HTTP.get(URL, timeout=5).json() | |
| for item in data['data']['children']: | |
| url = item['data']['url'] | |
| m = IMGUR_RAW.match(url) | |
| if m is not None: | |
| yield url | |
| m = IMGUR_PAGE.match(url) | |
| if m is not None: | |
| yield f'https://i.imgur.com/{m.group(1)}.jpg' | |
| def main(): | |
| feh(text("Finding…"), 'center') | |
| for url in get_url(): | |
| delay = 1 | |
| while True: | |
| feh(text("Downloading…"), 'center') | |
| try: | |
| feh(HTTP.get(url, timeout=5).content) | |
| return | |
| except subprocess.CalledProcessError: | |
| break | |
| except requests.exceptions.RequestException: | |
| feh(text(f"Network error, retrying in {delay}s…"), 'center') | |
| time.sleep(delay) | |
| delay *= 2 | |
| continue | |
| raise RuntimeError("unknown error") | |
| feh(text("Invalid image, trying next…"), 'center') | |
| time.sleep(1) | |
| raise RuntimeError("no suitable URL found") | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment