-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
183 lines (152 loc) · 5.8 KB
/
main.py
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
from random import randrange
import subprocess
import webbrowser
import requests
from twitter import TwitterImgCrawler
from data_types import *
from util import *
abspath = os.path.abspath
RECOMMENDATION_COUNT = 5
TWEETS_PER_ACCOUNT = 1000
CONFIG_PATH = abspath("./config/config.json")
DATA_DIR = abspath("./data")
METADATA_PATH = abspath("./data/metadata.json")
HISTORY_PATH = abspath("./data/history.json")
IMAGE_DIR = abspath("./img")
WEBSITE = "https://www.instagram.com/create/select/"
def init_dir_structure():
debug_log_info(f"Initializing dir structure...")
if not os.path.exists(IMAGE_DIR):
os.mkdir(IMAGE_DIR)
debug_log_info(f"Created {IMAGE_DIR}")
else:
debug_log_info(f"{IMAGE_DIR} already present")
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
debug_log_info(f"Created {DATA_DIR}")
else:
debug_log_info(f"{DATA_DIR} already present")
if not os.path.exists(HISTORY_PATH):
history = History(file_path=HISTORY_PATH, tweets=[], last_update=datetime.now())
history.write()
debug_log_info(f"Created {HISTORY_PATH}")
else:
debug_log_info(f"{HISTORY_PATH} already present")
if not os.path.exists(METADATA_PATH):
sample_metadata = Metadata(
file_path=METADATA_PATH,
accounts={
"username1": AccountMetadata("123456", "username1", None),
"username2": AccountMetadata("654321", "username2", None)
},
last_update=datetime.now()
)
sample_metadata.save()
print(f"Sample metadata file created at {METADATA_PATH}, fill it and come back!")
exit("Exiting...")
else:
debug_log_info(f"{METADATA_PATH} already present")
def download_image(url: str, target_path: str):
debug_log_info(f"Downloading img from {url} into {target_path}...")
with open(target_path, 'wb') as f:
res = requests.get(url, stream=True)
if res.status_code == 200:
for data in res.iter_content(1024):
if not data:
break
f.write(data)
debug_log_info(f"{target_path} downloaded successfully")
else:
debug_log_response(res, False)
def main():
# --- INIT ---
init_dir_structure()
# load config
config = json_load(CONFIG_PATH)
if not config['twitter']['app_key'] or not config['twitter']['app_secret']:
exit("Twitter app_key or app_secret not present, exiting...")
# load metadata
metadata = Metadata.load(METADATA_PATH)
if len(metadata.accounts) == 0:
print("Your metadata file has no accounts, there is nothing to crawl!")
exit("Exiting...")
# --- CRAWLER ---
crawler = TwitterImgCrawler(
config['twitter']['app_key'],
config['twitter']['app_secret'],
metadata,
DATA_DIR
)
outdated_accounts = crawler.get_outdated_accounts()
for username in outdated_accounts:
crawler.crawl_account(username=username, max_tweets=TWEETS_PER_ACCOUNT)
# --- RECOMMENDER ---
# load history
history = History.study(HISTORY_PATH)
# This is really dumb :)
# Throwing together all the "recommender" & user interaction code here, needs a refactor
debug_log_info(f"Stupidly selecting {RECOMMENDATION_COUNT} random images...")
# Get some random tweets from tweet files
recommendations: [Tweet] = []
crawled_accounts = crawler.get_account_tweet_files()
account_count = len(crawled_accounts)
rec_i = 0
while rec_i < RECOMMENDATION_COUNT:
rand_acc = randrange(0, account_count)
account = crawled_accounts[rand_acc]
with open(account['file_path'], 'r') as f:
tweets_json = json.load(f)
rand_tweet = randrange(0, len(tweets_json))
tweet = Tweet.from_json(tweets_json[rand_tweet])
already_in_history = history.contains(tweet)
if already_in_history:
debug_log_info(f"Tweet {tweet.id} already in history, rerolling...")
else:
recommendations.append(tweet)
debug_log_data(tweet)
rec_i += 1
# Download images for the randomly selected tweets
downloads = {} # {file_name: file_path}
rec_dict = {} # {file_name: Tweet} (to write chosen to history)
img_dir = os.path.abspath(IMAGE_DIR)
for i, rec in enumerate(recommendations):
suffix = ''
for j, img in enumerate(rec.media):
if j > 0:
suffix = f'-{j}'
img_name = f"{i}{suffix}"
img_path = os.path.join(img_dir, f'{img_name}.jpg')
download_image(img.url, img_path)
downloads[img_name] = img_path
rec_dict[img_name] = rec
# Open file explorer to choose image and handle user input
subprocess.Popen(f'explorer "{img_dir}"') # TODO support other OSs (this is windows only)
while True:
print("Insert image to post (no ext):")
user_input = input()
if user_input == '-1':
break
elif user_input in downloads:
selected = downloads[user_input]
downloads.pop(user_input)
print(f"{selected} it is!")
history.tweets.append(rec_dict[user_input])
history.write()
break
else:
print("That's the wrong number, try again (-1 to exit)...")
# Delete all images that weren't chosen
print("Cleaning up...")
for to_delete in downloads.values():
os.remove(to_delete)
# Open website where to post the image
if WEBSITE:
print(f"Open {WEBSITE}? (y/n):")
user_input = input()
if user_input == "y":
print("Opening web browser...")
webbrowser.open(WEBSITE)
if __name__ == '__main__':
print("Ready?")
input()
main()