-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.py
147 lines (118 loc) · 5.26 KB
/
example.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
#
# pip install requests
#
# Create an example.sh file with the following content and execute it from the command line using ./example-js.sh:
# USEAPI_SERVER="…" USEAPI_CHANNEL="…" USEAPI_TOKEN="…" USEAPI_DISCORD="…" python3 ./example.py
#
import datetime
import os
import time
import requests
import json
import sys
def dateAsString():
return datetime.datetime.now().isoformat()
def loadFromFile(filePath):
try:
with open(filePath, 'r') as file:
data = json.load(file)
return data
except Exception as error:
print(f'Unable to load file: {filePath}. Error: {error}')
sys.exit(1)
def saveToFile(filePath, data):
try:
with open(filePath, 'w') as file:
json.dump(data, file, indent=2)
except Exception as error:
print(f'Error writing to file: {error}')
# Extract filename.png from https://cdn.discordapp.com/attachments/server_id/channed_id/filename.png?ex=
def getFilenameFromUrl(url):
return url.split("/")[-1].split("?")[0]
def download_file(url, ind):
localPath = f"./{ind}-{getFilenameFromUrl(url)}"
response = requests.get(url)
with open(localPath, 'wb') as file:
file.write(response.content)
def main():
# Load all required parameters from the environment variables
token = os.getenv('USEAPI_TOKEN')
discord = os.getenv('USEAPI_DISCORD')
server = os.getenv('USEAPI_SERVER')
channel = os.getenv('USEAPI_CHANNEL')
# You can use https://webhook.site if you want to receive results via callback.
replyUrl = None
prompts = loadFromFile('./prompts.json')
print(f"{dateAsString()} ⁝ prompts to process: {len(prompts)}")
results = []
ind = 0
start_time = time.time()
for prompt in prompts:
ind += 1
data = {
'method': 'POST',
'headers': {
'Authorization': f"Bearer {token}",
'Content-Type': 'application/json'
},
'body': json.dumps({
'prompt': prompt,
'discord': discord,
'server': server,
'channel': channel,
# We will utilize all three available job slots for the Basic or Standard plan.
'maxJobs': 3,
'replyUrl': f"{replyUrl}?ind={ind}" if replyUrl is not None else None
})
}
print(f"{dateAsString()} ⁝ #{ind} prompt: {prompt}")
attempt = 0
retry = True
while retry:
attempt += 1
response = requests.post("https://api.useapi.net/v2/jobs/imagine", headers=data['headers'], data=data['body'])
result = response.json()
print(f"{dateAsString()} ⁝ attempt #{attempt}, response: {{ status: {response.status_code}, jobid: {result.get('jobid')}, job_status: {result.get('status')} }}")
if response.status_code == 429:
print(f"{dateAsString()} ⁝ #{ind} attempt #{attempt} sleeping for 10 secs...")
time.sleep(10)
elif response.status_code in [200, 422]:
results.append({ 'status': response.status_code, 'jobid': result.get('jobid'), 'job_status': result.get('status'), 'ind': ind, 'prompt': prompt })
retry = False
else:
print(f"Unexpected response.status: {response.status_code}, result: {result}")
retry = False
saveToFile('./result.json', results)
print(f"{dateAsString()} ⁝ downloading generated images")
ind = 0
for item in results:
ind += 1
jobid = item.get('jobid')
status = item.get('status')
print(f"{dateAsString()} ⁝ #{ind} jobid: {{ jobid: {jobid}, status: {status} }}")
if status == 422:
print(f"Moderated prompt: {item.get('prompt')}")
elif status == 200:
attempt = 0
retry = True
while retry:
attempt += 1
response = requests.get(f"https://api.useapi.net/v2/jobs/?jobid={jobid}", headers={"Authorization": f"Bearer {token}"})
result = response.json()
print(f"{dateAsString()} ⁝ attempt #{attempt}, response: {{ status: {response.status_code}, jobid: {result.get('jobid')}, job_status: {result.get('status')} }}")
if response.status_code == 200:
if result.get('status') == 'completed':
if len(result.get('attachments', [])):
download_file(result['attachments'][0]['url'], ind)
else:
print(f"#{ind} completed jobid has no attachments")
retry = False
elif result.get('status') in ['started', 'progress']:
print(f"{dateAsString()} ⁝ #{ind} attempt #{attempt} sleeping for 10 secs... status: {result.get('status')}")
time.sleep(10)
else:
print(f"Unexpected response.status: {response.status_code}, result: {result}")
retry = False
execution_time = time.time() - start_time
print(f"{dateAsString()} ⁝ total elapsed time {datetime.datetime.utcfromtimestamp(execution_time).strftime('%H:%M:%S')}")
main()