|
import os |
|
from typing import Dict |
|
|
|
import requests |
|
|
|
from .utils import Utils |
|
from os import path as osp |
|
from pathlib import Path |
|
import pandas as pd |
|
import concurrent |
|
|
|
class WallpaperDownloader: |
|
""" |
|
Core class to download images from Reddit. |
|
""" |
|
|
|
def __init__(self, |
|
subreddit: str = 'wallpaper', |
|
sort_by: str = 'top', |
|
sort_time: str = 'all', |
|
save_dir: str = 'default'): |
|
""" |
|
Initialize the preference and link to subreddit. |
|
:param subreddit: Name of the subreddit. |
|
:param sort_by: Sort by? Hot/Top/New/Controversial. |
|
:param sort_time: Sort time. day/week/month/year/all |
|
""" |
|
self._url = 'https://www.reddit.com/r/{}/{}/.json?raw_json=1&t={}&limit=100'.format(subreddit, |
|
sort_by, |
|
sort_time) |
|
self._preferences_file = Path(save_dir) / 'wp_preferences.json' |
|
self._preferences = self._setup_preferences(save_dir=save_dir) |
|
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=16) |
|
|
|
@property |
|
def preferences(self) -> Dict: |
|
""" |
|
Get the preferences. |
|
:return: Preferences Dict. |
|
""" |
|
return Utils.load_preferences(self._preferences_file) |
|
|
|
@staticmethod |
|
def download_image(image_url, img_save_name): |
|
|
|
if osp.exists(img_save_name): |
|
return |
|
|
|
dummy_img_save_name = img_save_name + ".dummy" |
|
|
|
with requests.get(image_url, stream=True) as r: |
|
r.raise_for_status() |
|
with open('{}'.format(img_save_name), 'wb') as f: |
|
for chunk in r.iter_content(chunk_size=26214400): |
|
if chunk: |
|
f.write(chunk) |
|
|
|
if osp.exists(dummy_img_save_name): |
|
osp.remove(dummy_img_save_name) |
|
|
|
def download(self, max_count: int = 200): |
|
""" |
|
This is where all the downloading takes place. |
|
:param max_count: Maximum number of images to download. |
|
:return: num_downloaded: Number of downloaded images. |
|
""" |
|
|
|
|
|
self._url += '&limit={}'.format( |
|
max_count * 1000) |
|
|
|
|
|
subreddit_data = Utils.fetch_subreddit_data(subreddit_url=self._url) |
|
|
|
|
|
if subreddit_data is None: |
|
|
|
return 0 |
|
|
|
count = 0 |
|
saved_images = [] |
|
|
|
for content in subreddit_data['data']['children']: |
|
|
|
if content['data'].get('post_hint', 'none') == 'image' and 'preview' in content['data']: |
|
|
|
image_url = content['data']['preview']['images'][0]['source']['url'] |
|
image_title = content['data']['title'][:15] |
|
image_title = ''.join(filter(str.isalnum, image_title)) |
|
image_id = content['data']['id'] |
|
|
|
|
|
img_save_name = '{}_{}.jpg'.format(image_title, image_id) |
|
img_save_name = osp.join(self._preferences['wallpaper_dir'], img_save_name) |
|
|
|
|
|
dummy_img_save_name = img_save_name + ".dummy" |
|
|
|
if osp.exists(img_save_name): |
|
continue |
|
|
|
open(img_save_name, 'a').close() |
|
os.utime(img_save_name, None) |
|
|
|
|
|
try: |
|
|
|
''' |
|
with requests.get(image_url, stream=True) as r: |
|
r.raise_for_status() |
|
with open('{}'.format(img_save_name), 'wb') as f: |
|
for chunk in r.iter_content(chunk_size=26214400): |
|
if chunk: |
|
f.write(chunk) |
|
''' |
|
except: |
|
continue |
|
|
|
saved_images.append(img_save_name) |
|
|
|
|
|
self._preferences['urls'][image_id] = {'title': image_title, |
|
'url': image_url} |
|
Utils.save_to_preferences(self._preferences, self._preferences_file) |
|
|
|
count += 1 |
|
|
|
|
|
if count >= max_count: |
|
count_removed = Utils.remove_unwanted_images(saved_images) |
|
return len(saved_images) - count_removed |
|
|
|
return count |
|
|
|
def _setup_preferences(self, save_dir='default') -> Dict: |
|
""" |
|
Setup the preferences for downloading. Find the machine type etc if its running for the first time. |
|
:return: preferences - Loaded preferences. |
|
""" |
|
|
|
preferences = Utils.load_preferences(self._preferences_file) if osp.exists(self._preferences_file) else {} |
|
|
|
|
|
if preferences == {}: |
|
os_type, wallpaper_dir = Utils.get_os() |
|
|
|
|
|
if not osp.exists(wallpaper_dir): |
|
os.makedirs(wallpaper_dir) |
|
|
|
preferences['os_type'] = os_type |
|
preferences['wallpaper_dir'] = wallpaper_dir |
|
preferences['urls'] = dict() |
|
|
|
|
|
if save_dir != 'default': |
|
preferences['wallpaper_dir'] = save_dir |
|
|
|
|
|
Utils.save_to_preferences(preferences, self._preferences_file) |
|
|
|
return preferences |
|
|