This repository was archived by the owner on Jul 15, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathai_describe.py
More file actions
156 lines (127 loc) · 4.22 KB
/
Copy pathai_describe.py
File metadata and controls
156 lines (127 loc) · 4.22 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""AI-powered image description using OpenAI GPT-4 Vision or Google Gemini."""
import base64
import requests
from application import get_app
from version import APP_NAME, APP_VERSION
def get_image_description(image_url):
"""Get an AI-generated description of an image.
Args:
image_url: URL of the image to describe
Returns:
tuple: (success: bool, description: str or error message)
"""
prefs = get_app().prefs
service = prefs.ai_service
prompt = prefs.ai_image_prompt
if service == "none" or not service:
return (False, "AI image description is disabled. Enable it in Options > AI.")
if service == "openai":
return _describe_with_openai(image_url, prompt, prefs.openai_api_key, prefs.openai_model)
elif service == "gemini":
return _describe_with_gemini(image_url, prompt, prefs.gemini_api_key, prefs.gemini_model)
else:
return (False, f"Unknown AI service: {service}")
def _describe_with_openai(image_url, prompt, api_key, model):
"""Use OpenAI to describe an image."""
if not api_key:
return (False, "OpenAI API key not configured. Add it in Options > AI.")
try:
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"User-Agent": f"{APP_NAME}/{APP_VERSION}"
}
payload = {
"model": model,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{
"type": "image_url",
"image_url": {"url": image_url}
}
]
}
],
"max_tokens": 1000
}
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers=headers,
json=payload,
timeout=60
)
if response.status_code != 200:
error_data = response.json() if response.text else {}
error_msg = error_data.get("error", {}).get("message", response.text)
return (False, f"OpenAI API error: {error_msg}")
data = response.json()
description = data["choices"][0]["message"]["content"]
return (True, description)
except requests.exceptions.Timeout:
return (False, "Request timed out. Please try again.")
except requests.exceptions.RequestException as e:
return (False, f"Network error: {str(e)}")
except Exception as e:
return (False, f"Error: {str(e)}")
def _describe_with_gemini(image_url, prompt, api_key, model):
"""Use Google Gemini to describe an image."""
if not api_key:
return (False, "Gemini API key not configured. Add it in Options > AI.")
try:
# First, download the image and convert to base64
img_response = requests.get(image_url, headers={"User-Agent": f"{APP_NAME}/{APP_VERSION}"}, timeout=30)
img_response.raise_for_status()
image_data = base64.b64encode(img_response.content).decode('utf-8')
# Detect mime type from content-type header or default to jpeg
content_type = img_response.headers.get('content-type', 'image/jpeg')
if ';' in content_type:
content_type = content_type.split(';')[0].strip()
# Gemini API endpoint
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
payload = {
"contents": [
{
"parts": [
{"text": prompt},
{
"inline_data": {
"mime_type": content_type,
"data": image_data
}
}
]
}
]
}
response = requests.post(
url,
json=payload,
headers={"User-Agent": f"{APP_NAME}/{APP_VERSION}"},
timeout=60
)
if response.status_code != 200:
error_data = response.json() if response.text else {}
error_msg = error_data.get("error", {}).get("message", response.text)
return (False, f"Gemini API error: {error_msg}")
data = response.json()
# Extract text from Gemini response
candidates = data.get("candidates", [])
if not candidates:
return (False, "Gemini returned no response")
content = candidates[0].get("content", {})
parts = content.get("parts", [])
if not parts:
return (False, "Gemini returned empty response")
description = parts[0].get("text", "")
if not description:
return (False, "Gemini returned no description")
return (True, description)
except requests.exceptions.Timeout:
return (False, "Request timed out. Please try again.")
except requests.exceptions.RequestException as e:
return (False, f"Network error: {str(e)}")
except Exception as e:
return (False, f"Error: {str(e)}")