Api.py (view raw)
1
2from PIL import Image, UnidentifiedImageError
3from io import BytesIO
4import requests, random, time
5
6base_url = "https://danbooru.donmai.us/"
7base_url_test = "https://testbooru.donmai.us/"
8
9page_suffix = "post/index.json"
10post_suffix = "posts/"
11
12ratings = [
13 'g', # general
14 's', # sensitive
15 'q', # questionable
16 'e', # explicit
17]
18
19rating_normal = "g,s"
20rating_lewd = "q"
21
22limit = 100
23max_pages = 700
24sleep_seconds = 3
25max_tries = 5
26
27def get_random_image(rating=rating_normal):
28 params = {
29 "limit": limit,
30 #"tags": "order:change_desc rating:" + rating,
31 "tags": "rating:" + rating,
32 }
33 #url = "https://danbooru.donmai.us/post/index.json"
34 count = 0
35 while count < max_tries:
36 params['page'] = random.randint(1,max_pages)
37 r = requests.get(base_url + page_suffix, params)
38 page = r.json()
39 #print("Page: " + str(params['page']))
40
41 if 'success' in page:
42 if page['success'] == False:
43 print("Error: " + page['error'])
44 print("Message: " + page['message'])
45 else:
46 print(page)
47 else:
48 n = random.randint(0, limit - 1)
49 #print("File: " + str(n))
50 try:
51 file_url = page[n]['file_url']
52 r = requests.get(file_url)
53 try:
54 img = Image.open(BytesIO(r.content))
55 return img, base_url + post_suffix + str(page[n]['id'])
56 except UnidentifiedImageError:
57 print("Unidentified image: " + file_url)
58 except KeyError:
59 print("Image has no file_url. post: " + base_url + post_suffix + str(page[n]['id']))
60 print(str(page[n]))
61 except IndexError:
62 print("Page does not exist. " + str(page))
63
64 count += 1
65 print(f"Try #{count} failed. Retrying in {sleep_seconds} seconds...\n")
66 #time.sleep(sleep_seconds)
67 print(f"Reached {count} tries. Giving up.")
68 return None, None