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 count = 0
34 while count < max_tries:
35 params['page'] = random.randint(1, max_pages)
36 r = requests.get(base_url + page_suffix, params)
37 page = r.json()
38 #print("Page: " + str(params['page']))
39
40 if 'success' in page:
41 if not page['success']:
42 print("Error: " + page['error'])
43 print("Message: " + page['message'])
44 else:
45 print(page)
46 else:
47 n = random.randint(0, limit - 1)
48 #print("File: " + str(n))
49 try:
50 file_url = page[n]['file_url']
51 r = requests.get(file_url)
52 try:
53 img = Image.open(BytesIO(r.content))
54 return img, base_url + post_suffix + str(page[n]['id'])
55 except UnidentifiedImageError:
56 print("Unidentified image: " + file_url)
57 except KeyError:
58 print("Image has no file_url. post: " + base_url + post_suffix + str(page[n]['id']))
59 print(str(page[n]))
60 except IndexError:
61 print("Page does not exist. " + str(page))
62
63 count += 1
64 print(f"Try #{count} failed. Retrying in {sleep_seconds} seconds...\n")
65 #time.sleep(sleep_seconds)
66 print(f"Reached {count} tries. Giving up.")
67 return None, None