imagi / imagi.py
electric-otter's picture
Update imagi.py
470baaa verified
import requests
from PIL import Image, ImageDraw
from io import BytesIO
import random
import time
from urllib.parse import quote
# Configuration
REQUEST_DELAY = 1.5 # Conservative delay between requests
CACHE_TIME = 86400 # Cache header simulation (1 day)
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:
# Construct URL without disallowed parameters
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()
# Extract only direct CDN links (avoiding download URLs)
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 # Respect robots.txt disallow
))[:10] # Limit results
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:
# Select random images
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))
# Create composite
composite = Image.new('RGB', (1200, 800), (240, 240, 240))
draw = ImageDraw.Draw(composite)
# Position images
positions = [(50, 50), (600, 100), (300, 400)]
for (img, url), pos in zip(images, positions):
img.thumbnail((400, 400))
composite.paste(img, pos)
# Add URL attribution
draw.text((pos[0], pos[1] - 20),
f"Source: {url.split('/')[-1][:20]}...",
fill=(0, 0, 0))
# Add footer attribution
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")