Spaces:
Sleeping
Sleeping
File size: 7,738 Bytes
a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 c4a3c75 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 a6c1838 5d47b99 |
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 |
import streamlit as st
import base64
from openai import OpenAI
from PIL import Image
import io
import cv2
import numpy as np
# Configure app
st.set_page_config(
page_title="AI Vision Assistant",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for futuristic design
st.markdown("""
<style>
/* Main colors */
:root {
--primary: #6366f1;
--secondary: #10b981;
--dark: #1e293b;
--light: #f8fafc;
}
/* Main container */
.stApp {
background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
color: var(--light);
}
/* Headers */
h1, h2, h3, h4, h5, h6 {
color: var(--light) !important;
font-family: 'Inter', sans-serif;
}
/* Sidebar */
[data-testid="stSidebar"] {
background: linear-gradient(195deg, #0f172a 0%, #1e40af 100%) !important;
}
/* Buttons */
.stButton>button {
background: var(--primary) !important;
color: white !important;
border: none;
border-radius: 8px;
padding: 10px 24px;
font-weight: 500;
transition: all 0.3s;
}
.stButton>button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}
/* File uploader */
[data-testid="stFileUploader"] {
border: 2px dashed var(--primary) !important;
border-radius: 12px !important;
padding: 20px !important;
}
/* Markdown output */
.markdown-text {
background: rgba(30, 41, 59, 0.7) !important;
border-radius: 12px;
padding: 20px;
border-left: 4px solid var(--secondary);
animation: fadeIn 0.5s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
/* Streamlit text input */
.stTextInput>div>div>input {
background: rgba(15, 23, 42, 0.7) !important;
color: white !important;
border: 1px solid #334155 !important;
}
</style>
""", unsafe_allow_html=True)
# App title and description
st.title("π Optimus Alpha | Live Vision Assistant")
# Initialize OpenAI client
@st.cache_resource
def get_client():
return OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key='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' # Replace with your actual key
)
# ===== Camera/Upload Selection =====
input_method = st.radio(
"Select input method:",
["Live Camera", "Upload Image"],
horizontal=True
)
# ===== Camera Section =====
captured_image = None
if input_method == "Live Camera":
st.subheader("Live Camera Feed")
run_camera = st.checkbox("Start Camera", value=False)
FRAME_WINDOW = st.empty()
if run_camera:
try:
cap = cv2.VideoCapture(1)
if not cap.isOpened():
st.error("Could not access camera. Please:")
st.markdown("""
- Check camera permissions
- Ensure no other app is using the camera
- Try reconnecting the camera
""")
run_camera = False
else:
capture_col, stop_col = st.columns(2)
with capture_col:
capture_button = st.button("πΈ Capture Image")
with stop_col:
stop_button = st.button("π Stop Camera")
if stop_button:
cap.release()
st.rerun()
while run_camera:
ret, frame = cap.read()
if not ret:
st.error("Failed to capture frame")
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
FRAME_WINDOW.image(frame)
if capture_button:
captured_image = frame
cap.release()
st.rerun()
break
except Exception as e:
st.error(f"Camera error: {str(e)}")
run_camera = False
# ===== Upload Section =====
else:
st.subheader("Upload Image")
uploaded_file = st.file_uploader(
"Choose an image file",
type=["jpg", "jpeg", "png"],
label_visibility="collapsed"
)
if uploaded_file:
try:
captured_image = Image.open(uploaded_file)
st.image(captured_image, caption="Uploaded Image", width=300)
except Exception as e:
st.error(f"Error loading image: {str(e)}")
# ===== Image Analysis Section =====
if captured_image is not None:
st.subheader("AI Analysis")
# Convert to PIL Image if from OpenCV
if isinstance(captured_image, np.ndarray):
image = Image.fromarray(captured_image)
else:
image = captured_image
user_prompt = st.text_input(
"Ask about the image:",
placeholder="e.g. 'What is in this image?' or 'Explain this diagram'",
key="user_prompt"
)
if st.button("Analyze Image", type="primary"):
try:
# Convert image to base64
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
# Prepare messages
messages = [
{
"role": "system",
"content": """You are an expert vision assistant. Analyze images with:
- Clear, structured responses
- Bullet points for multiple objects
- Concise explanations
- Highlight important findings in bold"""
},
{
"role": "user",
"content": [
{
"type": "text",
"text": user_prompt if user_prompt else "Describe this image in detail"
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{image_base64}"
}
}
]
}
]
# Stream the response
response_container = st.empty()
full_response = ""
client = get_client()
stream = client.chat.completions.create(
model="openrouter/optimus-alpha",
messages=messages,
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
full_response += chunk.choices[0].delta.content
response_container.markdown(f"""
<div class="markdown-text">
{full_response}
</div>
""", unsafe_allow_html=True)
except Exception as e:
st.error(f"Analysis error: {str(e)}")
# Sidebar
with st.sidebar:
st.image("https://via.placeholder.com/200", width=200) # Replace with your logo
st.markdown("""
*Powered by OpenRouter*
""")
st.markdown("---")
st.markdown("""
**Tips:**
- For best results, use clear, well-lit images
- Ask specific questions for detailed answers
""")
st.markdown("Made with β€οΈ by Koshur AI")
|