-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_analyzer_app.py
More file actions
494 lines (415 loc) · 14.1 KB
/
image_analyzer_app.py
File metadata and controls
494 lines (415 loc) · 14.1 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#!/usr/bin/env python3
"""
ImageSense Analyzer - Drag & Drop Image Analysis Tool
Analyzes images using OpenAI GPT Vision and saves to CSV
"""
import os
import sys
import base64
import json
import pandas as pd
from pathlib import Path
from datetime import datetime
from tkinter import Tk, Label, Text, Scrollbar, Frame, Button, messagebox
from tkinter import END, DISABLED, NORMAL
from tkinterdnd2 import DND_FILES, TkinterDnD
try:
from openai import OpenAI
except ImportError:
print("ERROR: openai package not installed")
print("Run: pip install openai")
sys.exit(1)
# ==============================
# CONFIG
# ==============================
OUTPUT_CSV = "image_analysis_results.csv"
VERSION = "1.0.0"
# Predefined CSV structure
CSV_COLUMNS = [
"filename",
"timestamp",
"summary",
"objects",
"people_count",
"people_description",
"colors",
"mood",
"emotion",
"movement",
"setting",
"lighting",
"composition",
"elements_list",
"full_description",
"cost_estimate"
]
# Pricing (as of Feb 2026 - verify current prices)
GPT4O_MINI_INPUT_PRICE = 0.00015 / 1000 # per token
GPT4O_MINI_OUTPUT_PRICE = 0.0006 / 1000 # per token
# ==============================
# GLOBAL STATE
# ==============================
client = None
total_cost = 0.0
images_processed = 0
# ==============================
# API KEY VALIDATION
# ==============================
def validate_api_key():
"""Check if OpenAI API key is set and valid"""
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
messagebox.showerror(
"API Key Missing",
"OpenAI API key not found!\n\n"
"Please set your API key:\n\n"
"Mac/Linux:\nexport OPENAI_API_KEY='your-key-here'\n\n"
"Windows:\nsetx OPENAI_API_KEY 'your-key-here'\n\n"
"Then restart this application."
)
return False
try:
global client
client = OpenAI(api_key=api_key)
# Test API key with a simple call
log_message("✓ API key validated successfully")
return True
except Exception as e:
messagebox.showerror(
"API Key Invalid",
f"Failed to initialize OpenAI client:\n{str(e)}\n\n"
"Please check your API key."
)
return False
# ==============================
# IMAGE TO BASE64
# ==============================
def encode_image(image_path):
"""Encode image to base64 string"""
with open(image_path, "rb") as img:
return base64.b64encode(img.read()).decode("utf-8")
# ==============================
# GPT IMAGE ANALYSIS
# ==============================
def analyse_image(image_path):
"""
Analyze image using OpenAI GPT Vision
Returns dict with analysis results
"""
global total_cost, images_processed
log_message(f"\n{'='*60}")
log_message(f"📸 Analyzing: {Path(image_path).name}")
log_message(f"{'='*60}")
try:
# Encode image
base64_image = encode_image(image_path)
log_message("✓ Image encoded")
# Create prompt
prompt = """
Please analyze this image in detail and return your response ONLY as valid JSON with exactly these fields:
{
"summary": "Brief one-sentence description",
"objects": "List main objects visible (comma-separated)",
"people_count": "Number of people (0 if none, or specific count)",
"people_description": "What people are doing (or 'None' if no people)",
"colors": "Dominant colors and color characteristics",
"mood": "Overall mood/atmosphere",
"emotion": "Emotional quality conveyed",
"movement": "Sense of movement or stillness",
"setting": "Location/environment type",
"lighting": "Lighting characteristics and quality",
"composition": "Compositional elements and structure",
"elements_list": "Detailed comma-separated list of all visible elements",
"full_description": "Comprehensive 2-3 paragraph description covering all aspects"
}
Important: Return ONLY the JSON object, no other text before or after.
"""
log_message("→ Sending to OpenAI GPT Vision...")
# Call API
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
},
],
}
],
max_tokens=1500,
)
log_message("✓ Response received")
# Calculate cost
usage = response.usage
input_cost = usage.prompt_tokens * GPT4O_MINI_INPUT_PRICE
output_cost = usage.completion_tokens * GPT4O_MINI_OUTPUT_PRICE
image_cost = input_cost + output_cost
total_cost += image_cost
log_message(f"💰 Cost: ${image_cost:.4f} (Total: ${total_cost:.4f})")
log_message(f"📊 Tokens: {usage.prompt_tokens} input, {usage.completion_tokens} output")
# Parse response
content = response.choices[0].message.content.strip()
# Remove markdown code blocks if present
if content.startswith("```json"):
content = content[7:]
if content.startswith("```"):
content = content[3:]
if content.endswith("```"):
content = content[:-3]
content = content.strip()
try:
data = json.loads(content)
log_message("✓ JSON parsed successfully")
except json.JSONDecodeError as e:
log_message(f"⚠ JSON parse error: {str(e)}")
log_message("Raw response:")
log_message(content[:500])
# Fallback structure
data = {col: "" for col in CSV_COLUMNS if col not in ["filename", "timestamp", "cost_estimate"]}
data["full_description"] = content
data["summary"] = "Error parsing response - see full_description"
# Add metadata
data["filename"] = os.path.basename(image_path)
data["timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data["cost_estimate"] = f"${image_cost:.4f}"
images_processed += 1
log_message(f"✓ Analysis complete ({images_processed} total)")
return data
except Exception as e:
log_message(f"❌ ERROR: {str(e)}")
messagebox.showerror("Analysis Error", f"Failed to analyze {Path(image_path).name}:\n{str(e)}")
# Return error record
return {
"filename": os.path.basename(image_path),
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"summary": f"ERROR: {str(e)}",
"objects": "",
"people_count": "",
"people_description": "",
"colors": "",
"mood": "",
"emotion": "",
"movement": "",
"setting": "",
"lighting": "",
"composition": "",
"elements_list": "",
"full_description": "",
"cost_estimate": "$0.0000"
}
# ==============================
# SAVE TO CSV
# ==============================
def save_to_csv(data):
"""Append analysis data to CSV file"""
try:
# Ensure all columns exist
for col in CSV_COLUMNS:
if col not in data:
data[col] = ""
# Load existing or create new
if os.path.exists(OUTPUT_CSV):
df = pd.read_csv(OUTPUT_CSV)
else:
df = pd.DataFrame(columns=CSV_COLUMNS)
# Append new row
df = pd.concat([df, pd.DataFrame([data])], ignore_index=True)
# Save
df.to_csv(OUTPUT_CSV, index=False)
log_message(f"✓ Saved to {OUTPUT_CSV}")
return True
except Exception as e:
log_message(f"❌ Error saving to CSV: {str(e)}")
messagebox.showerror("Save Error", f"Failed to save to CSV:\n{str(e)}")
return False
# ==============================
# GUI LOGGING
# ==============================
def log_message(message):
"""Add message to log window"""
if log_text:
log_text.config(state=NORMAL)
log_text.insert(END, message + "\n")
log_text.see(END)
log_text.config(state=DISABLED)
log_text.update()
# ==============================
# DROP HANDLER
# ==============================
def handle_drop(event):
"""Handle drag and drop of image files"""
files = root.tk.splitlist(event.data)
# Filter for image files
image_files = [f for f in files if f.lower().endswith((".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"))]
if not image_files:
messagebox.showwarning("No Images", "Please drop image files (.png, .jpg, .jpeg, .webp)")
return
log_message(f"\n{'#'*60}")
log_message(f"🎯 Processing {len(image_files)} image(s)")
log_message(f"{'#'*60}\n")
# Process each image
success_count = 0
for file in image_files:
result = analyse_image(file)
if save_to_csv(result):
success_count += 1
# Summary
log_message(f"\n{'#'*60}")
log_message(f"✅ BATCH COMPLETE")
log_message(f"{'#'*60}")
log_message(f"Processed: {len(image_files)} images")
log_message(f"Successful: {success_count}")
log_message(f"Total cost: ${total_cost:.4f}")
log_message(f"Output: {OUTPUT_CSV}")
log_message(f"{'#'*60}\n")
messagebox.showinfo(
"Analysis Complete",
f"Analyzed {success_count} images\n"
f"Total cost: ${total_cost:.4f}\n\n"
f"Results saved to:\n{OUTPUT_CSV}"
)
# ==============================
# OPEN CSV HANDLER
# ==============================
def open_csv():
"""Open the CSV file in default application"""
if os.path.exists(OUTPUT_CSV):
import subprocess
import platform
try:
if platform.system() == 'Darwin': # macOS
subprocess.call(['open', OUTPUT_CSV])
elif platform.system() == 'Windows':
os.startfile(OUTPUT_CSV)
else: # Linux
subprocess.call(['xdg-open', OUTPUT_CSV])
log_message(f"✓ Opened {OUTPUT_CSV}")
except Exception as e:
log_message(f"❌ Could not open CSV: {str(e)}")
messagebox.showinfo("CSV Location", f"CSV file location:\n{os.path.abspath(OUTPUT_CSV)}")
else:
messagebox.showwarning("No Data", "No CSV file exists yet. Analyze some images first!")
# ==============================
# CLEAR LOG
# ==============================
def clear_log():
"""Clear the log window"""
log_text.config(state=NORMAL)
log_text.delete(1.0, END)
log_text.config(state=DISABLED)
log_message(f"ImageSense Analyzer v{VERSION}")
log_message("="*60)
log_message("Ready! Drag and drop images here to analyze.")
log_message("="*60 + "\n")
# ==============================
# GUI SETUP
# ==============================
def create_gui():
"""Create the main GUI window"""
global root, log_text
root = TkinterDnD.Tk()
root.title(f"ImageSense Analyzer v{VERSION}")
root.geometry("800x600")
# Header Frame
header_frame = Frame(root, bg="#2c3e50", height=80)
header_frame.pack(fill="x")
header_frame.pack_propagate(False)
title_label = Label(
header_frame,
text="🖼️ ImageSense Analyzer",
font=("Arial", 24, "bold"),
bg="#2c3e50",
fg="white"
)
title_label.pack(pady=10)
subtitle_label = Label(
header_frame,
text="Drag & Drop Images Here for AI Analysis",
font=("Arial", 12),
bg="#2c3e50",
fg="#ecf0f1"
)
subtitle_label.pack()
# Button Frame
button_frame = Frame(root, bg="#ecf0f1")
button_frame.pack(fill="x", padx=10, pady=10)
open_btn = Button(
button_frame,
text="📊 Open CSV",
command=open_csv,
font=("Arial", 10),
bg="#3498db",
fg="white",
padx=20,
pady=5
)
open_btn.pack(side="left", padx=5)
clear_btn = Button(
button_frame,
text="🗑️ Clear Log",
command=clear_log,
font=("Arial", 10),
bg="#95a5a6",
fg="white",
padx=20,
pady=5
)
clear_btn.pack(side="left", padx=5)
# Info Label
info_label = Label(
button_frame,
text=f"Total Cost: ${total_cost:.4f} | Images: {images_processed}",
font=("Arial", 10),
bg="#ecf0f1"
)
info_label.pack(side="right", padx=10)
# Log Frame
log_frame = Frame(root)
log_frame.pack(fill="both", expand=True, padx=10, pady=10)
scrollbar = Scrollbar(log_frame)
scrollbar.pack(side="right", fill="y")
log_text = Text(
log_frame,
wrap="word",
yscrollcommand=scrollbar.set,
font=("Courier", 10),
bg="#1e1e1e",
fg="#00ff00",
insertbackground="white"
)
log_text.pack(side="left", fill="both", expand=True)
scrollbar.config(command=log_text.yview)
# Initial message
clear_log()
# Enable drag and drop
root.drop_target_register(DND_FILES)
root.dnd_bind("<<Drop>>", handle_drop)
return root
# ==============================
# MAIN
# ==============================
def main():
"""Main entry point"""
global root
# Create GUI
root = create_gui()
# Validate API key on startup
if not validate_api_key():
root.destroy()
return
log_message("✓ Ready to analyze images!")
log_message(f"Output will be saved to: {OUTPUT_CSV}\n")
# Start GUI loop
try:
root.mainloop()
except KeyboardInterrupt:
log_message("\n👋 Shutting down...")
root.destroy()
if __name__ == "__main__":
main()