| import requests |
| from PIL import Image, ImageDraw |
| from io import BytesIO |
| import random |
| import time |
| from urllib.parse import quote |
|
|
| |
| REQUEST_DELAY = 1.5 |
| CACHE_TIME = 86400 |
| USER_AGENT = "ImageformGenerator/1.0 (+https://github.com/your-repo)" |
|
|
| def compliant_pixabay_search(query): |
| """Search that respects all robots.txt rules""" |
| time.sleep(REQUEST_DELAY) |
| |
| try: |
| |
| base_url = f"https://pixabay.com/images/search/{quote(query)}/" |
| |
| headers = { |
| 'User-Agent': USER_AGENT, |
| 'Accept': 'text/html', |
| 'Cache-Control': f'max-age={CACHE_TIME}' |
| } |
| |
| response = requests.get(base_url, headers=headers, timeout=10) |
| response.raise_for_status() |
| |
| |
| cdn_links = list(set( |
| link for link in re.findall( |
| r'(https://cdn\.pixabay\.com/photo[\w/-]+\.(?:jpg|png))', |
| response.text |
| ) |
| if 'download' not in link |
| ))[:10] |
| |
| return cdn_links |
| |
| except Exception as e: |
| print(f"Search error: {str(e)}") |
| return [] |
|
|
| def create_attributed_image(links, output_path="output.jpg"): |
| """Create composite with visible attribution""" |
| try: |
| |
| selected = random.sample(links, min(3, len(links))) |
| images = [] |
| |
| for url in selected: |
| time.sleep(REQUEST_DELAY) |
| resp = requests.get(url, headers={'User-Agent': USER_AGENT}, timeout=10) |
| img = Image.open(BytesIO(resp.content)) |
| images.append((img, url)) |
| |
| |
| composite = Image.new('RGB', (1200, 800), (240, 240, 240)) |
| draw = ImageDraw.Draw(composite) |
| |
| |
| positions = [(50, 50), (600, 100), (300, 400)] |
| for (img, url), pos in zip(images, positions): |
| img.thumbnail((400, 400)) |
| composite.paste(img, pos) |
| |
| |
| draw.text((pos[0], pos[1] - 20), |
| f"Source: {url.split('/')[-1][:20]}...", |
| fill=(0, 0, 0)) |
| |
| |
| draw.text((50, 750), |
| "Images from Pixabay CDN - Not affiliated with Pixabay", |
| fill=(100, 100, 100)) |
| |
| composite.save(output_path) |
| return output_path |
| |
| except Exception as e: |
| print(f"Creation error: {str(e)}") |
| return None |
|
|
| if __name__ == "__main__": |
| query = input("What images would you like to search for? ").strip() or "nature" |
| print(f"Searching Pixabay for '{query}'...") |
| |
| links = compliant_pixabay_search(query) |
| if links: |
| output = create_attributed_image(links) |
| if output: |
| print(f"Created composite image: {output}") |
| Image.open(output).show() |
| else: |
| print("No valid images found or access restricted") |