-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreceiver.py
166 lines (133 loc) · 6.08 KB
/
receiver.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
import requests
import json
import numpy as np
from tqdm import tqdm
import pandas as pd
import os
import re
from datetime import datetime
import glob
import argparse
import sys
import hashlib
class Receiver:
def __init__(self,
params,
local_path,
task_name):
self.params = params
self.local_path = local_path
self.task_name = task_name
self.json_path = f'{task_name}/{task_name}.json'
os.makedirs(self.local_path, exist_ok=True)
with open('hps_training_prompts.json', 'r') as f:
self.all_prompts = json.load(f)
self.sender_initializer()
if os.path.exists(self.json_path):
with open(self.json_path, 'r') as f:
self.df = json.load(f)
else:
self.df = []
# pd.DataFrame(columns = ['prompt', 'url', 'filename', 'is_downloaded'])
def sender_initializer(self):
with open(self.params, "r") as json_file:
params = json.load(json_file)
self.channelid=params['channelid']
self.authorization=params['authorization']
self.headers = {'authorization' : self.authorization}
def retrieve_messages(self):
r = requests.get(
f'https://discord.com/api/v10/channels/{self.channelid}/messages?limit={100}', headers=self.headers)
jsonn = json.loads(r.text)
return jsonn
def collecting_results(self):
message_list = self.retrieve_messages()
self.awaiting_list = pd.DataFrame(columns = ['prompt', 'status'])
for i,message in enumerate(message_list):
if (message['author']['username'] == 'Midjourney Bot') and ('**' in message['content']):
if len(message['attachments']) > 0:
if (message['attachments'][0]['filename'][-4:] == '.png') or ('(Open on website for full quality)' in message['content']):
id = message['id']
prompt = message['content'].split('**')[1].split(' --')[0]
url = message['attachments'][0]['url']
exists_prompts = [d['prompt'] for d in self.df]
if prompt not in exists_prompts:
filename = hashlib.sha256(prompt.encode()).hexdigest() + ".png"
info = {
"prompt":prompt,
"url":url,
"filename":filename,
"is_downloaded":0
}
self.df.append(info)
else:
filename = self.df[exists_prompts.index(prompt)]['filename']
else:
id = message['id']
prompt = message['content'].split('**')[1].split(' --')[0]
if ('(fast)' in message['content']) or ('(relaxed)' in message['content']):
try:
status = re.findall("(\w*%)", message['content'])[0]
except:
status = 'unknown status'
self.awaiting_list.loc[id] = [prompt, status]
else:
id = message['id']
prompt = message['content'].split('**')[1].split(' --')[0]
if '(Waiting to start)' in message['content']:
status = 'Waiting to start'
self.awaiting_list.loc[id] = [prompt, status]
def outputer(self):
if len(self.awaiting_list) > 0:
print(datetime.now().strftime("%H:%M:%S"))
print('prompts in progress:')
print(self.awaiting_list)
print('=========================================')
waiting_for_download = [d["prompt"] for d in self.df if d["is_downloaded"] == 0]
if len(waiting_for_download) > 0:
print(datetime.now().strftime("%H:%M:%S"))
print('waiting for download prompts: ', waiting_for_download)
print(f"total {len(waiting_for_download)} prompts")
print('=========================================')
print(f"total {len(os.listdir(self.local_path))} images has been downloaded")
print('=========================================')
def downloading_results(self):
processed_prompts = []
for i in tqdm(range(len(self.df))):
if self.df[i]["is_downloaded"] == 0:
response = requests.get(self.df[i]["url"])
with open(os.path.join(self.local_path, self.df[i]["filename"]), "wb") as req:
req.write(response.content)
self.df[i]["is_downloaded"] = 1
processed_prompts.append(self.df[i]["prompt"])
if len(processed_prompts) > 0:
print(datetime.now().strftime("%H:%M:%S"))
print('processed prompts: ', processed_prompts)
print('=========================================')
def save_result(self):
with open(self.json_path, 'w') as f:
json.dump(self.df, f)
def main(self):
while True:
try:
self.collecting_results()
self.outputer()
self.downloading_results()
self.save_result()
except:
self.save_result()
# time.sleep(0.5)
def parse_args(args):
parser = argparse.ArgumentParser()
parser.add_argument('--params',help='Path to discord authorization and channel parameters', default="sender_params.json")
parser.add_argument('--task-name',help='task name',default='mdj')
return parser.parse_args(args)
if __name__ == "__main__":
args = sys.argv[1:]
args = parse_args(args)
params = args.params
task_name = args.task_name
local_path = task_name + '/images'
print('=========== listening started ===========')
receiver = Receiver(params, local_path, task_name)
receiver.main()