DexterSptizu commited on
Commit
aa44125
Β·
verified Β·
1 Parent(s): dcae82a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +175 -0
app.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from openai import OpenAI
4
+ from PIL import Image
5
+ import io
6
+ import base64
7
+
8
+ # Custom CSS for better styling
9
+ def apply_custom_css():
10
+ st.markdown("""
11
+ <style>
12
+ .stApp {
13
+ max-width: 1200px;
14
+ margin: 0 auto;
15
+ }
16
+ .upload-box {
17
+ border: 2px dashed #4CAF50;
18
+ border-radius: 10px;
19
+ padding: 20px;
20
+ text-align: center;
21
+ background-color: #f8f9fa;
22
+ }
23
+ .sidebar-content {
24
+ padding: 20px;
25
+ background-color: #f1f3f4;
26
+ border-radius: 10px;
27
+ }
28
+ .response-box {
29
+ background-color: #ffffff;
30
+ padding: 20px;
31
+ border-radius: 10px;
32
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
33
+ }
34
+ .title-text {
35
+ color: #1E88E5;
36
+ text-align: center;
37
+ font-size: 2.5rem;
38
+ margin-bottom: 2rem;
39
+ }
40
+ </style>
41
+ """, unsafe_allow_html=True)
42
+
43
+ def initialize_session_state():
44
+ if 'history' not in st.session_state:
45
+ st.session_state.history = []
46
+
47
+ def encode_image_to_base64(image):
48
+ buffered = io.BytesIO()
49
+ image.save(buffered, format="PNG")
50
+ return base64.b64encode(buffered.getvalue()).decode('utf-8')
51
+
52
+ def analyze_image(image, question, api_key):
53
+ try:
54
+ client = OpenAI(api_key=api_key)
55
+ base64_image = encode_image_to_base64(image)
56
+
57
+ completion = client.chat.completions.create(
58
+ model="gpt-4-vision-preview",
59
+ messages=[
60
+ {
61
+ "role": "user",
62
+ "content": [
63
+ {"type": "text", "text": question},
64
+ {
65
+ "type": "image_url",
66
+ "image_url": {
67
+ "url": f"data:image/png;base64,{base64_image}"
68
+ }
69
+ },
70
+ ],
71
+ }
72
+ ],
73
+ max_tokens=500
74
+ )
75
+ return completion.choices[0].message.content
76
+ except Exception as e:
77
+ return f"Error: {str(e)}"
78
+
79
+ def main():
80
+ apply_custom_css()
81
+ initialize_session_state()
82
+
83
+ st.set_page_config(
84
+ page_title="Smart Image Analyzer",
85
+ page_icon="πŸ”",
86
+ layout="wide"
87
+ )
88
+
89
+ # Sidebar Configuration
90
+ with st.sidebar:
91
+ st.markdown('<div class="sidebar-content">', unsafe_allow_html=True)
92
+ st.image("https://your-logo-url.com/logo.png", width=100) # Add your logo
93
+ st.header("βš™οΈ Configuration")
94
+ api_key = st.text_input("OpenAI API Key:", type="password")
95
+
96
+ st.markdown("### 🎯 Quick Prompts")
97
+ quick_prompts = [
98
+ "Describe this image in detail",
99
+ "What objects are present?",
100
+ "Analyze the composition",
101
+ "Identify any text in the image",
102
+ "Suggest improvements"
103
+ ]
104
+ selected_prompt = st.selectbox("Select a prompt:", quick_prompts)
105
+ st.markdown("</div>", unsafe_allow_html=True)
106
+
107
+ # Main Content
108
+ st.markdown('<h1 class="title-text">πŸ” Smart Image Analyzer</h1>', unsafe_allow_html=True)
109
+
110
+ # Image Upload Section
111
+ col1, col2, col3 = st.columns([1, 2, 1])
112
+ with col2:
113
+ st.markdown('<div class="upload-box">', unsafe_allow_html=True)
114
+ uploaded_file = st.file_uploader(
115
+ "Drop your image here or click to upload",
116
+ type=['png', 'jpg', 'jpeg'],
117
+ help="Supported formats: PNG, JPG, JPEG"
118
+ )
119
+ st.markdown('</div>', unsafe_allow_html=True)
120
+
121
+ if uploaded_file:
122
+ image = Image.open(uploaded_file)
123
+
124
+ # Image Display and Analysis Section
125
+ col1, col2 = st.columns([1, 1])
126
+
127
+ with col1:
128
+ st.image(image, use_container_width=True, caption="Uploaded Image")
129
+
130
+ with col2:
131
+ st.markdown('<div class="response-box">', unsafe_allow_html=True)
132
+ question = st.text_input(
133
+ "Your Question:",
134
+ value=selected_prompt,
135
+ key="question_input"
136
+ )
137
+
138
+ if st.button("πŸ” Analyze", use_container_width=True):
139
+ if not api_key:
140
+ st.error("⚠️ Please enter your OpenAI API key in the sidebar.")
141
+ else:
142
+ with st.spinner("πŸ”„ Analyzing your image..."):
143
+ response = analyze_image(image, question, api_key)
144
+ st.markdown("### πŸ“ Analysis Result:")
145
+ st.write(response)
146
+
147
+ # Add to history
148
+ st.session_state.history.append({
149
+ "question": question,
150
+ "response": response,
151
+ "timestamp": st.session_state.get("timestamp", "")
152
+ })
153
+ st.markdown('</div>', unsafe_allow_html=True)
154
+
155
+ # History Section
156
+ if st.session_state.history:
157
+ st.markdown("### πŸ“œ Previous Analyses")
158
+ for item in reversed(st.session_state.history[-5:]):
159
+ with st.expander(f"Q: {item['question'][:50]}..."):
160
+ st.write(item['response'])
161
+
162
+ # Footer
163
+ st.markdown("---")
164
+ st.markdown(
165
+ """
166
+ <div style='text-align: center'>
167
+ <p>Built with ❀️ using Streamlit and OpenAI GPT-4 Vision API</p>
168
+ <p>Β© 2024 Smart Image Analyzer</p>
169
+ </div>
170
+ """,
171
+ unsafe_allow_html=True
172
+ )
173
+
174
+ if __name__ == "__main__":
175
+ main()