File size: 2,307 Bytes
9df4cc0
 
 
 
 
 
 
 
9c57dcd
9df4cc0
 
 
 
 
 
 
9c57dcd
9df4cc0
 
 
 
 
 
 
 
 
 
bb235fc
 
 
 
 
9df4cc0
bb235fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9df4cc0
bb235fc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import requests
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
UNSPLASH_ACCESS_KEY = os.getenv("UNSPLASH_ACCESS_KEY")

def extract_unsplash_keywords(title, openai_api_key, num_keywords=2):
    prompt = f"""
Extract {num_keywords} distinct, concise, visually-relevant keywords for Unsplash image search from this article title.

Format: space-separated, lowercase. No punctuation.
Title: {title}
"""
    try:
        client = OpenAI(api_key=openai_api_key)
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.3,
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        print(f"⚠️ Keyword extraction failed: {e}")
        return title  # fallback

def search_unsplash_image(title):
    # Always return the same placeholder image and a simple credit
    default_image_url = "https://via.placeholder.com/1280x720.png?text=AI+News+Analyzer"
    image_credit = "Default placeholder image"
    return default_image_url, image_credit

# def search_unsplash_image(title, openai_api_key):
#     keywords = extract_unsplash_keywords(title, openai_api_key)
#     try:
#         response = requests.get(
#             "https://api.unsplash.com/search/photos",
#             headers={"Authorization": f"Client-ID {UNSPLASH_ACCESS_KEY}"},
#             params={"query": keywords, "orientation": "landscape", "per_page": 1}
#         )
#         data = response.json()
#         if data.get("results"):
#             photo = data["results"][0]
#             image_url = photo["urls"]["regular"]
#             author_name = photo["user"]["name"]
#             author_username = photo["user"]["username"]
#             author_link = f"https://unsplash.com/@{author_username}"

#             image_credit_html = (
#                 f'Photo by <a href="{author_link}" target="_blank">{author_name}</a> '
#                 f'on <a href="https://unsplash.com" target="_blank">Unsplash</a>'
#             )
#             return image_url, image_credit_html

#     except Exception as e:
#         print(f"❌ Unsplash fetch failed: {e}")

#     return "https://via.placeholder.com/1281x721?text=No+Image+Found", "Image unavailable"