reddew / run_reddit.old.py
chitravyanjan's picture
reddit code
630930b
#%%
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()()
# %%