CosmickVisions commited on
Commit
b73e529
·
verified ·
1 Parent(s): 7feb231

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +269 -0
app.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from google.cloud import vision
3
+ import os
4
+ from PIL import Image, ImageDraw
5
+ import io
6
+ import numpy as np
7
+ from streamlit_option_menu import option_menu
8
+
9
+ # Set page config
10
+ st.set_page_config(
11
+ page_title="Vision AI Analyzer",
12
+ page_icon="👁️",
13
+ layout="wide"
14
+ )
15
+
16
+ # Set your Google Cloud credentials
17
+ os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path/to/your/credentials.json'
18
+
19
+ # Initialize the Vision AI client
20
+ client = vision.ImageAnnotatorClient()
21
+
22
+ # Custom CSS
23
+ st.markdown("""
24
+ <style>
25
+ .main-header {
26
+ font-size: 2.5rem;
27
+ color: #4285F4;
28
+ text-align: center;
29
+ margin-bottom: 1rem;
30
+ }
31
+ .subheader {
32
+ font-size: 1.5rem;
33
+ color: #34A853;
34
+ margin-top: 1.5rem;
35
+ }
36
+ .result-container {
37
+ background-color: #f8f9fa;
38
+ border-radius: 10px;
39
+ padding: 15px;
40
+ margin-top: 10px;
41
+ }
42
+ .label-item {
43
+ padding: 5px;
44
+ margin: 2px 0;
45
+ border-radius: 4px;
46
+ background-color: #e9f5e9;
47
+ }
48
+ .object-item {
49
+ padding: 5px;
50
+ margin: 2px 0;
51
+ border-radius: 4px;
52
+ background-color: #e9ecf5;
53
+ }
54
+ .text-item {
55
+ padding: 5px;
56
+ margin: 2px 0;
57
+ border-radius: 4px;
58
+ background-color: #f5eee9;
59
+ }
60
+ </style>
61
+ """, unsafe_allow_html=True)
62
+
63
+ def analyze_image(image, analysis_types):
64
+ """Analyze image with selected analysis types"""
65
+ # Convert uploaded image to bytes
66
+ if image is None:
67
+ return None, {}, {}, ""
68
+
69
+ img_byte_arr = io.BytesIO()
70
+ image.save(img_byte_arr, format='PNG')
71
+ content = img_byte_arr.getvalue()
72
+
73
+ # Create vision image object
74
+ vision_image = vision.Image(content=content)
75
+
76
+ # Perform detection based on selected types
77
+ labels_data = {}
78
+ objects_data = {}
79
+ text_content = ""
80
+
81
+ img_with_boxes = image.copy()
82
+ draw = ImageDraw.Draw(img_with_boxes)
83
+
84
+ if "Labels" in analysis_types:
85
+ labels = client.label_detection(image=vision_image)
86
+ labels_data = {label.description: round(label.score * 100)
87
+ for label in labels.label_annotations}
88
+
89
+ if "Objects" in analysis_types:
90
+ objects = client.object_localization(image=vision_image)
91
+ objects_data = {obj.name: round(obj.score * 100)
92
+ for obj in objects.localized_object_annotations}
93
+
94
+ # Draw object boundaries
95
+ for obj in objects.localized_object_annotations:
96
+ box = [(vertex.x * image.width, vertex.y * image.height)
97
+ for vertex in obj.bounding_poly.normalized_vertices]
98
+ draw.polygon(box, outline='red', width=2)
99
+ draw.text((box[0][0], box[0][1] - 10),
100
+ f"{obj.name}: {int(obj.score * 100)}%",
101
+ fill='red')
102
+
103
+ if "Text" in analysis_types:
104
+ text = client.text_detection(image=vision_image)
105
+ if text.text_annotations:
106
+ text_content = text.text_annotations[0].description
107
+
108
+ # Draw text boundaries
109
+ for text_annot in text.text_annotations[1:]: # Skip the first one (full text)
110
+ box = [(vertex.x, vertex.y) for vertex in text_annot.bounding_poly.vertices]
111
+ draw.polygon(box, outline='blue', width=1)
112
+
113
+ if "Face Detection" in analysis_types:
114
+ faces = client.face_detection(image=vision_image)
115
+ for face in faces.face_annotations:
116
+ vertices = face.bounding_poly.vertices
117
+ box = [(vertex.x, vertex.y) for vertex in vertices]
118
+ draw.polygon(box, outline='green', width=2)
119
+
120
+ # Draw facial landmarks
121
+ for landmark in face.landmarks:
122
+ px = landmark.position.x
123
+ py = landmark.position.y
124
+ draw.ellipse((px-2, py-2, px+2, py+2), fill='yellow')
125
+
126
+ return img_with_boxes, labels_data, objects_data, text_content
127
+
128
+ def display_results(annotated_img, labels, objects, text):
129
+ """Display analysis results in a clean format"""
130
+ col1, col2 = st.columns([3, 2])
131
+
132
+ with col1:
133
+ st.markdown('<div class="subheader">Analyzed Image</div>', unsafe_allow_html=True)
134
+ st.image(annotated_img, use_column_width=True)
135
+
136
+ with col2:
137
+ st.markdown('<div class="subheader">Analysis Results</div>', unsafe_allow_html=True)
138
+
139
+ # Labels tab
140
+ if labels:
141
+ st.markdown("##### 🏷️ Labels Detected")
142
+ st.markdown('<div class="result-container">', unsafe_allow_html=True)
143
+ for label, confidence in labels.items():
144
+ st.markdown(f'<div class="label-item">{label}: {confidence}%</div>', unsafe_allow_html=True)
145
+ st.markdown('</div>', unsafe_allow_html=True)
146
+
147
+ # Objects tab
148
+ if objects:
149
+ st.markdown("##### 📦 Objects Detected")
150
+ st.markdown('<div class="result-container">', unsafe_allow_html=True)
151
+ for obj, confidence in objects.items():
152
+ st.markdown(f'<div class="object-item">{obj}: {confidence}%</div>', unsafe_allow_html=True)
153
+ st.markdown('</div>', unsafe_allow_html=True)
154
+
155
+ # Text tab
156
+ if text:
157
+ st.markdown("##### 📝 Text Detected")
158
+ st.markdown('<div class="result-container">', unsafe_allow_html=True)
159
+ st.markdown(f'<div class="text-item">{text}</div>', unsafe_allow_html=True)
160
+ st.markdown('</div>', unsafe_allow_html=True)
161
+
162
+ def main():
163
+ # Header
164
+ st.markdown('<div class="main-header">Google Cloud Vision AI Analyzer</div>', unsafe_allow_html=True)
165
+
166
+ # Navigation
167
+ selected = option_menu(
168
+ menu_title=None,
169
+ options=["Image Analysis", "About"],
170
+ icons=["image", "info-circle"],
171
+ menu_icon="cast",
172
+ default_index=0,
173
+ orientation="horizontal",
174
+ )
175
+
176
+ if selected == "Image Analysis":
177
+ # Sidebar controls
178
+ with st.sidebar:
179
+ st.markdown("### Analysis Settings")
180
+
181
+ # Analysis types selection
182
+ st.write("Choose analysis types:")
183
+ analysis_types = []
184
+
185
+ if st.checkbox("Label Detection", value=True):
186
+ analysis_types.append("Labels")
187
+
188
+ if st.checkbox("Object Detection", value=True):
189
+ analysis_types.append("Objects")
190
+
191
+ if st.checkbox("Text Recognition", value=True):
192
+ analysis_types.append("Text")
193
+
194
+ if st.checkbox("Face Detection"):
195
+ analysis_types.append("Face Detection")
196
+
197
+ st.markdown("---")
198
+
199
+ # Image quality settings
200
+ st.write("Image settings:")
201
+ quality = st.slider("Image Quality", min_value=0, max_value=100, value=100)
202
+
203
+ st.markdown("---")
204
+ st.info("This application analyzes images using Google Cloud Vision AI. Upload an image to get started.")
205
+
206
+ # Main content
207
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
208
+
209
+ if uploaded_file is not None:
210
+ # Convert uploaded file to image
211
+ image = Image.open(uploaded_file)
212
+
213
+ # Apply quality adjustment if needed
214
+ if quality < 100:
215
+ img_byte_arr = io.BytesIO()
216
+ image.save(img_byte_arr, format='JPEG', quality=quality)
217
+ image = Image.open(img_byte_arr)
218
+
219
+ # Show original image
220
+ st.markdown('<div class="subheader">Original Image</div>', unsafe_allow_html=True)
221
+ st.image(image, use_column_width=True)
222
+
223
+ # Add analyze button
224
+ if st.button("Analyze Image"):
225
+ if not analysis_types:
226
+ st.warning("Please select at least one analysis type.")
227
+ else:
228
+ with st.spinner("Analyzing image..."):
229
+ # Call analyze function
230
+ annotated_img, labels, objects, text = analyze_image(image, analysis_types)
231
+
232
+ # Display results
233
+ display_results(annotated_img, labels, objects, text)
234
+
235
+ # Add download button for the annotated image
236
+ buf = io.BytesIO()
237
+ annotated_img.save(buf, format="PNG")
238
+ byte_im = buf.getvalue()
239
+
240
+ st.download_button(
241
+ label="Download Annotated Image",
242
+ data=byte_im,
243
+ file_name="annotated_image.png",
244
+ mime="image/png"
245
+ )
246
+
247
+ elif selected == "About":
248
+ st.markdown("## About This App")
249
+ st.write("""
250
+ This application uses Google Cloud Vision AI to analyze images. It can:
251
+
252
+ - **Detect labels** in images
253
+ - **Identify objects** and their locations
254
+ - **Extract text** from images
255
+ - **Detect faces** and facial landmarks
256
+
257
+ To use this app, you need to:
258
+ 1. Set up Google Cloud Vision API credentials
259
+ 2. Upload an image
260
+ 3. Select the types of analysis you want to perform
261
+ 4. Click "Analyze Image"
262
+
263
+ The app is built with Streamlit and Google Cloud Vision API.
264
+ """)
265
+
266
+ st.info("Note: Make sure your Google Cloud credentials are properly set up to use this application.")
267
+
268
+ if __name__ == "__main__":
269
+ main()