File size: 5,381 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
import argparse
import os
import random
import glob
from os import path as osp
from typing import Optional
from .core import WallpaperDownloader

import pandas as pd

from pathlib import Path
from types import SimpleNamespace



def save_as_dataframe(preferences_file, subreddit_name, parent_dir) -> None:
    """
    Saves the preferences as dataframe
    """

    parent_dir = Path(parent_dir)
    reddit_df_path = parent_dir/"reddit.csv"

    original_len = 0

    try:
        df = pd.read_json(preferences_file, 
                parse_dates=False)
        rdf = df.urls.apply(pd.Series)
        ndf = df.join(rdf)
        ndf = ndf.drop(columns=["urls"]).reset_index()
        ndf["subreddit"] = subreddit_name
        ndf["downloaded"] = False
    except:
        return

    try:
        if reddit_df_path.exists():
            tdf = pd.read_csv(reddit_df_path)
            original_len = len(tdf)
            tdf = pd.concat([tdf, ndf], axis=0).drop_duplicates(subset=['index'])
        else:
            tdf = ndf
    except (FileNotFoundError, pd.errors.EmptyDataError) as err:
        tdf = ndf

    new_len = len(tdf)
    if new_len != original_len:
        tdf.to_csv(reddit_df_path, index=False)


def rdownloader(d : Optional[SimpleNamespace] = None):
    """
    Runs the main code. Downloads images, set and switches wallpapers.
    """

    if d is None:
        # Process user inputs.
        args = parse_args()
    else:
        args = d

    parent_dir = Path(args.save_dir).expanduser()
    save_dir = parent_dir.expanduser() / args.subreddit
    save_dir.mkdir(parents=True, exist_ok=True)    
    save_dir = str(save_dir)

    # Setup the downloader.
    downloader = WallpaperDownloader(subreddit=args.subreddit,
                                     sort_time=args.sort_time,
                                     sort_by=args.sort_by,
                                     save_dir=save_dir)

    # Download and return the total number of downloads.
    total_downloaded = downloader.download(max_count=args.max_download_count)
    save_as_dataframe(downloader._preferences_file, args.subreddit, parent_dir)

    #print('Downloaded {} images from /r/{} sorted by {} for sort time {}'.format(total_downloaded,
    #                                                                             args.subreddit,
    #                                                                             args.sort_by,
    #                                                                             args.sort_time))

    if args.download_only:
        return args.subreddit, total_downloaded

    # Now setup wallpaper randomly from the wallpaper folder.
    preferences = downloader.preferences
    wallpapers = glob.glob(osp.join(preferences['wallpaper_dir'], '*.jpg'))
    random.shuffle(wallpapers)

    total_iters = int((args.run_for * 60) / args.update_every)

    assert total_iters >= 1, "See help for run_for and update_every"

    if total_iters >= len(wallpapers):
        to_extend = int(total_iters/len(wallpapers)) + 1
        wallpapers_copy = []
        for _ in range(to_extend):
            wallpapers_copy.extend(wallpapers.copy())
        wallpapers = wallpapers_copy

    for i in range(total_iters):
        if preferences['os_type'] == 'Linux':
            filepath = "gsettings set org.gnome.desktop.background picture-uri file:" + wallpapers[i]
        elif preferences['os_type'] == 'Darwin':
            filepath = "osascript -e 'tell application \"Finder\" to set desktop picture to POSIX file \"" + \
                       wallpapers[i] + "\"'"
        else:
            raise NotImplementedError('Implemented only for Linux and Mac. ')

        os.system(filepath)


def parse_args():
    """
    Fetch user inputs from command line.
    """
    parser = argparse.ArgumentParser(
        description='Download images and set wallpaper from your choice of subreddit!')
    parser.add_argument('--subreddit', type=str, default='wallpaper',
                        help='Your choice of subreddit to download Images. Default is "wallpaper".')
    parser.add_argument('--sort_by', type=str, default='hot',
                        help='Select sort-by option. Default is "hot". Options: hot|new|rising|top')
    parser.add_argument('--sort_time', type=str, default='day',
                        help='Sort time for subreddit. Default is "day". Options: all|year|month|week|day')
    parser.add_argument('--max_download_count', type=int, default=20,
                        help='Maximum number of images to download. Default is 20.')
    parser.add_argument('--save_dir', type=str, default='~/me/data/reddit',
                        help='Where to save downloaded images? '
                             'By default it saves at machine default wallpapers folder')
    parser.add_argument('--download_only', action='store_true', default=False,
                        help='Only download the photos. Skip setting up wallpaper.')
    parser.add_argument('--update_every', type=int, default=30,
                        help='Update the wallpaper after how many mins? Default is 30 mins.')
    parser.add_argument('--run_for', type=int, default=24,
                        help='How long you want to keep updating the wallpaper? Default ius 24 hours.')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    rdownloader()