from typing import Optional import requests from PIL import Image from io import BytesIO 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, save_path: 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() # Process and save image img = Image.open(BytesIO(img_response.content)) img.thumbnail((800, 600)) img.save(save_path, "JPEG", quality=85) return UnsplashImage( url=image_url, photographer=photographer, local_path=save_path ) except Exception as e: print(f"Error fetching image: {e}") return None