File size: 6,364 Bytes
630930b |
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
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.
"""
# Update URL to fetch entries based on max_count.
self._url += '&limit={}'.format(
max_count * 1000) # There are a lot of unwanted images, so setting it to high value.
# Fetch the JSON file for subreddit here.
subreddit_data = Utils.fetch_subreddit_data(subreddit_url=self._url)
# If we can't get subreddit data even after 20 trials, we close the program. Try later.
if subreddit_data is None:
#print('Unable to connect to reddit. Check internet connection. Or try later.')
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']:
# Get the information about the image.
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']
# Set image save name
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 we have already downloaded the image, we can skip.
if osp.exists(img_save_name):
continue
open(img_save_name, 'a').close()
os.utime(img_save_name, None)
# Actually downloading the image.
try:
#self.executor.submit(WallpaperDownloader.download_image, image_url, img_save_name)
'''
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)
# Update the preferences.
self._preferences['urls'][image_id] = {'title': image_title,
'url': image_url}
Utils.save_to_preferences(self._preferences, self._preferences_file)
count += 1
# Done downloading, so remove unwanted images and return the total number of saved images.
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.
"""
# Load the preferences file.
preferences = Utils.load_preferences(self._preferences_file) if osp.exists(self._preferences_file) else {}
# If it's empty (running for the first time), we set it up manually.
if preferences == {}:
os_type, wallpaper_dir = Utils.get_os()
# If wallpapers directory is not there, we create it.
if not osp.exists(wallpaper_dir):
os.makedirs(wallpaper_dir)
preferences['os_type'] = os_type
preferences['wallpaper_dir'] = wallpaper_dir
preferences['urls'] = dict()
# Update the default dir here.
if save_dir != 'default':
preferences['wallpaper_dir'] = save_dir
# Just save preferences back to file in case of update.
Utils.save_to_preferences(preferences, self._preferences_file)
return preferences
|