File size: 4,846 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
#%%
from pathlib import Path
from pyparsing import Any
from types import SimpleNamespace

import time
import random
import filetype
import numpy as np

from rich.live import Live
from rich.table import Table

from reddit import rdownloader, SUBREDDITS

class UCB:
    def __init__(self, K) -> None:
        self.K = K
        self.xs = np.zeros(self.K)
        self.Ts = np.zeros(self.K)
        self.delta = 1./self.K
        self.ucb = np.empty(self.K)
        self.ucb.fill(10000.)

    def update(self, idx, reward):
        self.xs[idx] += reward
        self.Ts[idx] += 1
        self.ucb[idx] = (self.xs[idx]/self.Ts[idx]) + 2*np.sqrt(1./self.delta*(self.Ts[idx]))

    def get_index(self):
        return np.argmax(self.ucb)


class RedditDownloader:
    def initialize_subreddit_counter(self):
        for subreddit in SUBREDDITS:
            subreddit_folder = self.reddit_root_dir / subreddit

            imfiles = [imfile for imfile in subreddit_folder.glob('*') if filetype.is_image(imfile)]

            self.subreddit_counter[subreddit] = len(imfiles)
            #self.delay_counter[subreddit] = 0
            self.changed_status[subreddit] = False

    def __init__(self) -> None:
        self.reddit_root_dir = Path("~/me/data/reddit").expanduser()
        self.subreddit_counter = { }
        self.changed_status = {}

        self.initialize_subreddit_counter()
        
    def generate_table(self, overall_run_status = True, subreddit = None, running = False) -> Table:
        """Make a new table."""
        table = Table()

        overall_run_status_col = "green" if overall_run_status else "yellow"

        table.add_column(f"[{overall_run_status_col}]Subreddit")
        table.add_column("Total Images")

        total = 0

        for subr, kount in self.subreddit_counter.items():
            changed_num_col= "orchid" if self.changed_status[subr] else "blue"

            if subr != subreddit:
                table.add_row(f"{subr}", f"[{changed_num_col}]{kount}")
            else:
                if running == False:
                    table.add_row(f"[magenta3]{subr}", f"[{changed_num_col}]{kount}")
                else:
                    table.add_row(f"[green]{subr}", f"[{changed_num_col}]{kount}")
            total += kount

        table.add_section()
        table.add_row(f"[silver]Total", f"[blue]{total}")

        return table


    def __call__(self, *args: Any, **kwds: Any) -> Any:

        run_list = set(SUBREDDITS)

        delays = 0

        with Live(self.generate_table(overall_run_status=True), auto_refresh=False, refresh_per_second=0.01) as live:

            while True:
                
                chosen_sort_by = random.choice(['new', 'hot', 'top', 'rising'])
                chosen_sort_time = random.choice(['day', 'week', 'month', 'year', 'all'])

                for subreddit in SUBREDDITS:
                    self.changed_status[subreddit] = False

                for subreddit in SUBREDDITS:

                    if subreddit not in run_list: continue

                    overall_run_status = len(run_list) > 0

                    live.update(self.generate_table(overall_run_status, subreddit, running=True), refresh=True)
                    d = { }
                    d["subreddit"] = subreddit
                    d["sort_by"] = chosen_sort_by
                    d["sort_time"] = chosen_sort_time
                    d["max_download_count"] = 200
                    d["save_dir"] = self.reddit_root_dir
                    d["download_only"] = True
                    d["update_every"] = 20
                    d["run_for"] = 24
                    d = SimpleNamespace(**d)
                    rsubreddit, total_downloaded = rdownloader(d)
                    
                    if subreddit in self.subreddit_counter:
                        self.subreddit_counter[subreddit] += total_downloaded
                    else:
                        self.subreddit_counter[subreddit] = total_downloaded
                    
                    if total_downloaded == 0:
                        run_list.remove(subreddit)

                    self.changed_status[subreddit] = (total_downloaded > 0)

                    overall_run_status = len(run_list) > 0

                    live.update(self.generate_table(overall_run_status, subreddit, running=False), refresh=True)

                if len(run_list) == 0:
                    time.sleep(120)
                    delays = 0
                    run_list = set(SUBREDDITS)
                else:
                    delays += 30
                    time.sleep(30)
                    if (delays > 120):
                        run_list = set(SUBREDDITS)
                    if run_list == set(SUBREDDITS):
                        delays = 0


if __name__ == "__main__":
    RedditDownloader()()

# %%