-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_analyzer.py
204 lines (167 loc) · 6.59 KB
/
image_analyzer.py
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
"""
Image Analysis Module Using OpenAI's Vision Model.
This module provides functionality to analyze doorbell camera snapshots using
OpenAI's GPT-4 Vision model. It handles:
- Image encoding and validation
- API communication with OpenAI
- Custom analysis prompts
- Error handling and logging
The analyzer generates detailed descriptions of:
- People and their appearance
- Notable objects or activities
- Relevant contextual details
- Potential security concerns
Usage:
analyzer = ImageAnalyzer(api_key)
description = analyzer.analyze_snapshot('path/to/image.jpg')
"""
import base64
import logging
import os
from typing import Optional, Dict, Any, Union
from openai import OpenAI
from openai.types.chat import ChatCompletion
from .config import VISION_MODEL
#------------------------------------------------------------------------------
# Constants
#------------------------------------------------------------------------------
# Analysis Configuration
DEFAULT_MAX_TOKENS = 300
DEFAULT_PROMPT = (
"Please describe who or what you see in this doorbell camera snapshot. "
"Focus on any people, their appearance, and notable objects or activities. "
"Be concise but detailed."
)
# Image Configuration
SUPPORTED_FORMATS = ['.jpg', '.jpeg', '.png']
MAX_IMAGE_SIZE = 20 * 1024 * 1024 # 20MB limit for OpenAI
#------------------------------------------------------------------------------
# Logger Configuration
#------------------------------------------------------------------------------
# Configure logger
logger = logging.getLogger('doorbell')
#------------------------------------------------------------------------------
# Image Analyzer Class
#------------------------------------------------------------------------------
class ImageAnalyzer:
"""
Handles image analysis using OpenAI's vision model.
This class manages:
- Image validation and encoding
- OpenAI API communication
- Analysis prompt handling
- Error management
Attributes:
client (OpenAI): OpenAI API client instance
"""
def __init__(self, api_key: str):
"""
Initialize the image analyzer.
Args:
api_key: OpenAI API key for authentication
Raises:
ValueError: If API key is invalid or empty
"""
if not api_key or not isinstance(api_key, str):
raise ValueError("Invalid OpenAI API key")
self.client = OpenAI(api_key=api_key)
def _validate_image(self, image_path: str) -> None:
"""
Validate image file before processing.
Args:
image_path: Path to the image file
Raises:
FileNotFoundError: If image file doesn't exist
ValueError: If image format is unsupported or file is too large
"""
if not os.path.exists(image_path):
raise FileNotFoundError(f"Image file not found: {image_path}")
file_ext = os.path.splitext(image_path)[1].lower()
if file_ext not in SUPPORTED_FORMATS:
raise ValueError(
f"Unsupported image format: {file_ext}. "
f"Supported formats: {', '.join(SUPPORTED_FORMATS)}"
)
file_size = os.path.getsize(image_path)
if file_size > MAX_IMAGE_SIZE:
raise ValueError(
f"Image file too large: {file_size/1024/1024:.1f}MB. "
f"Maximum size: {MAX_IMAGE_SIZE/1024/1024:.1f}MB"
)
def _encode_image(self, image_path: str) -> str:
"""
Encode image to base64 string.
Args:
image_path: Path to the image file
Returns:
Base64 encoded image string
Raises:
IOError: If image file cannot be read
Exception: For other encoding errors
"""
try:
self._validate_image(image_path)
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
except IOError as e:
logger.error(f"Error reading image file: {e}")
raise
except Exception as e:
logger.error(f"Error encoding image: {e}")
raise
def analyze_snapshot(self, image_path: str, prompt: Optional[str] = None) -> str:
"""
Analyze snapshot using OpenAI's vision model.
This method:
1. Validates and encodes the image
2. Sends analysis request to OpenAI
3. Processes and returns the description
Args:
image_path: Path to the snapshot image
prompt: Optional custom prompt for analysis
If not provided, uses default prompt
Returns:
Detailed description of the snapshot
Raises:
ValueError: For invalid inputs
Exception: For API or processing errors
"""
try:
logger.info(f"Analyzing snapshot: {image_path}")
# Encode image
base64_image = self._encode_image(image_path)
# Prepare analysis request
messages = [{
"role": "user",
"content": [
{
"type": "text",
"text": prompt or DEFAULT_PROMPT,
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}",
"detail": "auto"
},
},
],
}]
# Send analysis request
response: ChatCompletion = self.client.chat.completions.create(
model=VISION_MODEL,
messages=messages,
max_tokens=DEFAULT_MAX_TOKENS
)
# Extract and validate description
if not response.choices:
raise ValueError("No response received from OpenAI")
description = response.choices[0].message.content
if not description:
raise ValueError("Empty description received from OpenAI")
logger.info(f"Generated snapshot description: {description}")
return description
except Exception as e:
error_msg = f"Error analyzing snapshot: {str(e)}"
logger.error(error_msg)
return error_msg