diff --git a/foodie_utils.py b/foodie_utils.py index 4cc50f1..5c0b15a 100644 --- a/foodie_utils.py +++ b/foodie_utils.py @@ -1074,4 +1074,77 @@ def search_ddg_for_flickr(query): return photo_ids except Exception as e: logger.warning(f"DDG search failed for query '{ddg_query}': {e}") - return set() \ No newline at end of file + return set() + +def get_flickr_image(search_query: str, relevance_keywords: List[str] = None) -> Tuple[Optional[str], Optional[str], Optional[str], Optional[str]]: + """ + Get an image from Flickr using the search query and relevance keywords. + + Args: + search_query: The search query to find images + relevance_keywords: Optional list of keywords to help filter relevant images + + Returns: + Tuple of (image_url, image_source, uploader, page_url) or (None, None, None, None) if no image found + """ + try: + # Initialize Flickr API + flickr_api.set_keys(api_key=FLICKR_API_KEY, api_secret=FLICKR_API_SECRET) + + # Try to find photo IDs via DuckDuckGo first + photo_ids = search_ddg_for_flickr(search_query) + if not photo_ids: + # Fallback to direct Flickr search + photos = flickr_api.Photo.search( + text=search_query, + sort='relevance', + per_page=10, + safe_search=1 + ) + photo_ids = [photo.id for photo in photos] + + if not photo_ids: + logger.warning(f"No Flickr photos found for query '{search_query}'") + return None, None, None, None + + # Try each photo ID until we find a suitable image + for photo_id in photo_ids: + try: + photo = flickr_api.Photo(id=photo_id) + sizes = photo.getSizes() + + # Get the largest available size + size = sizes.get('Large', sizes.get('Medium', sizes.get('Small'))) + if not size: + continue + + img_url = size['source'] + if not img_url: + continue + + # Check if image is already used + if img_url in used_images: + continue + + # Get photo info for attribution + info = photo.getInfo() + uploader = info.owner.username + page_url = f"https://www.flickr.com/photos/{info.owner.id}/{photo_id}" + + # Save to used images + used_images.add(img_url) + save_used_images() + + logger.info(f"Selected Flickr image: {img_url} by {uploader} for query '{search_query}'") + return img_url, "Flickr", uploader, page_url + + except Exception as e: + logger.warning(f"Failed to process Flickr photo {photo_id}: {e}") + continue + + logger.warning(f"No suitable Flickr images found for query '{search_query}'") + return None, None, None, None + + except Exception as e: + logger.error(f"Flickr image fetch failed for query '{search_query}': {e}") + return None, None, None, None \ No newline at end of file