From a9475c27ffe72e61355e31fd985269c089acc65f Mon Sep 17 00:00:00 2001 From: Juli Date: Tue, 3 Sep 2024 18:42:37 +0100 Subject: [PATCH] Add img_source.py --- img_source.py | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 img_source.py diff --git a/img_source.py b/img_source.py new file mode 100644 index 0000000..73b8fb2 --- /dev/null +++ b/img_source.py @@ -0,0 +1,84 @@ +import os +import random +import requests +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + +# Danbooru API base URL +base_url = 'https://danbooru.donmai.us/posts.json' + +# Parameters from .env file +search_query = os.getenv('searchquery') +banned_tags = os.getenv('bannedtags').split(',') +danbooru_user = os.getenv('danbooru_user') +danbooru_apikey = os.getenv('danbooru_apikey') + +# Function to fetch a random post +def fetch_random_post(): + try: + tags = search_query.split() + + + tags = tags[:2] + + params = { + 'tags': ' '.join(tags), + 'random': 'true', + 'login': danbooru_user, + 'api_key': danbooru_apikey + } + + response = requests.get(base_url, params=params) + response.raise_for_status() + + posts = response.json() + + filtered_posts = [post for post in posts if not any(tag in post['tag_string'] for tag in banned_tags)] + + if filtered_posts: + random_post = random.choice(filtered_posts) + return random_post + else: + print("No posts found matching the criteria.") + return None + + except requests.exceptions.RequestException as e: + print(f"Error fetching data: {e}") + return None + +def get_image_url(post): + if 'large_file_url' in post: + return post['large_file_url'] + else: + print("Image URL not found in the post data.") + return None +def get_artist_names(post): + return post['tag_string_artist'].split(',') if 'tag_string_artist' in post else [] + +# Main function +def main(): + random_post = fetch_random_post() + if random_post: + print(f"URL: https://danbooru.donmai.us/posts/{random_post['id']}") + image_url = get_image_url(random_post) + # if image_url: + # r = requests.get(image_url) + # with open("out.jpg","wb") as f: + # f.write(r.content) + # print(f"Image URL: {image_url}") + # else: + # print("Failed to fetch a random post.") + + + artist_names = get_artist_names(random_post) + if artist_names: + artists = f"{', '.join(artist_names)}" + else: + artists = "Unknown" + + return f"https://danbooru.donmai.us/posts/{random_post['id']}", image_url, artists + +if __name__ == "__main__": + main() \ No newline at end of file