anki-generator/anki_generator/clients/unsplash.py

58 lines
1.9 KiB
Python

from typing import Optional
import requests
from PIL import Image
from io import BytesIO
import os
from ..models import Settings, UnsplashImage
from anki_generator.settings import get_settings, Settings
class UnsplashClient:
def __init__(self, settings: Optional[Settings] = None):
self.settings = settings or get_settings()
self.api_key = self.settings.unsplash_api_key.get_secret_value()
def get_image(self, search_term: str, filename: str) -> Optional[UnsplashImage]:
"""Fetch and save an image from Unsplash"""
url = "https://api.unsplash.com/search/photos"
headers = {"Authorization": f"Client-ID {self.api_key}"}
params = {
"query": search_term,
"per_page": 1,
"orientation": "landscape"
}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
data = response.json()
if not data["results"]:
return None
image_data = data["results"][0]
image_url = image_data["urls"]["regular"]
photographer = f"{image_data['user']['name']} on Unsplash"
# Download and process image
img_response = requests.get(image_url)
img_response.raise_for_status()
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(filename) or '.', exist_ok=True)
# Process and save image
img = Image.open(BytesIO(img_response.content))
img.thumbnail((800, 600))
img.save(filename, "JPEG", quality=85)
return UnsplashImage(
url=image_url,
photographer=photographer,
local_path=filename
)
except Exception as e:
print(f"Error fetching image: {e}")
return None