added error handilig
Browse files
app.py
CHANGED
@@ -1,28 +1,35 @@
|
|
1 |
import os
|
2 |
-
import time
|
3 |
import base64
|
4 |
import requests
|
5 |
import streamlit as st
|
|
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
10 |
|
11 |
# Function to encode the image
|
12 |
def encode_image(image_path):
|
13 |
with open(image_path, "rb") as image_file:
|
14 |
return base64.b64encode(image_file.read()).decode('utf-8')
|
15 |
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
23 |
|
24 |
def main():
|
25 |
-
st.title("Multimodal
|
26 |
|
27 |
text = """Prof. Louie F. Cervantes, M. Eng. (Information Engineering)
|
28 |
CCS 229 - Intelligent Systems
|
@@ -60,44 +67,79 @@ def main():
|
|
60 |
|
61 |
# Task selection dropdown
|
62 |
selected_task = st.selectbox("Select an image analysis task:", analysis_tasks)
|
|
|
|
|
63 |
|
64 |
-
# Button to generate response
|
65 |
if st.button("Generate Response"):
|
|
|
|
|
|
|
66 |
if uploaded_image is None or selected_task == "":
|
67 |
-
st.error("Please upload an image and
|
|
|
|
|
68 |
else:
|
|
|
|
|
|
|
|
|
|
|
69 |
# Prepare the multimodal prompt
|
70 |
payload = {
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
}
|
83 |
|
84 |
with st.spinner("Processing..."):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
try:
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
content = response.json()
|
96 |
-
|
97 |
-
st.write(f"AI Response: {
|
98 |
-
|
99 |
-
|
100 |
-
st.error(f"An error occurred: {e}")
|
101 |
|
|
|
|
|
|
|
102 |
if __name__ == "__main__":
|
103 |
main()
|
|
|
1 |
import os
|
|
|
2 |
import base64
|
3 |
import requests
|
4 |
import streamlit as st
|
5 |
+
import json
|
6 |
|
7 |
+
if "stream" not in st.session_state:
|
8 |
+
st.session_state.stream = True
|
9 |
+
|
10 |
+
api_key = os.getenv("NVIDIA_VISION_KEY")
|
11 |
+
MODEL_ID = "llama-3.2-11b-vision-instruct"
|
12 |
+
invoke_url = "https://ai.api.nvidia.com/v1/gr/meta/llama-3.2-11b-vision-instruct/chat/completions"
|
13 |
|
14 |
# Function to encode the image
|
15 |
def encode_image(image_path):
|
16 |
with open(image_path, "rb") as image_file:
|
17 |
return base64.b64encode(image_file.read()).decode('utf-8')
|
18 |
|
19 |
+
def extract_content(chunk):
|
20 |
+
try:
|
21 |
+
decoded_chunk = chunk.decode('utf-8')
|
22 |
+
json_data = decoded_chunk.split('data: ')[1]
|
23 |
+
parsed_data = json.loads(json_data)
|
24 |
+
content = parsed_data['choices'][0]['delta']['content']
|
25 |
+
return content
|
26 |
+
except json.JSONDecodeError as e:
|
27 |
+
#ignore the error
|
28 |
+
return ""
|
29 |
+
|
30 |
|
31 |
def main():
|
32 |
+
st.title("Multimodal Image Analysis with " + MODEL_ID)
|
33 |
|
34 |
text = """Prof. Louie F. Cervantes, M. Eng. (Information Engineering)
|
35 |
CCS 229 - Intelligent Systems
|
|
|
67 |
|
68 |
# Task selection dropdown
|
69 |
selected_task = st.selectbox("Select an image analysis task:", analysis_tasks)
|
70 |
+
|
71 |
+
|
72 |
|
|
|
73 |
if st.button("Generate Response"):
|
74 |
+
st.session_state.stream = st.checkbox("Begin streaming the AI response as soon as it is available.", value=True)
|
75 |
+
stream = st.session_state.stream
|
76 |
+
|
77 |
if uploaded_image is None or selected_task == "":
|
78 |
+
st.error("Please upload an image and select a task.")
|
79 |
+
return
|
80 |
+
|
81 |
else:
|
82 |
+
headers = {
|
83 |
+
"Authorization": f"Bearer {api_key}",
|
84 |
+
"Accept": "text/event-stream" if stream else "application/json"
|
85 |
+
}
|
86 |
+
|
87 |
# Prepare the multimodal prompt
|
88 |
payload = {
|
89 |
+
"model": MODEL_ID,
|
90 |
+
"messages": [
|
91 |
+
{
|
92 |
+
"role": "user",
|
93 |
+
"content": f'{selected_task} <img src="data:image/png;base64,{base64_image}" />'
|
94 |
+
}
|
95 |
+
],
|
96 |
+
"max_tokens": 512,
|
97 |
+
"temperature": 1.00,
|
98 |
+
"top_p": 1.00,
|
99 |
+
"stream": stream
|
100 |
}
|
101 |
|
102 |
with st.spinner("Processing..."):
|
103 |
+
response = requests.post(
|
104 |
+
invoke_url,
|
105 |
+
headers=headers,
|
106 |
+
json=payload,
|
107 |
+
stream=stream # Important for streaming
|
108 |
+
)
|
109 |
+
|
110 |
+
#handle if the AI refused to connect
|
111 |
try:
|
112 |
+
if (
|
113 |
+
json.loads(response).get("type") == "about:blank"
|
114 |
+
and json.loads(response).get("status") == 404):
|
115 |
+
st.error("Resource not found. Please check the URL.")
|
116 |
+
return
|
117 |
+
except json.JSONDecodeError as e:
|
118 |
+
st.error("Resource not found. Please check the URL.")
|
119 |
+
pass
|
120 |
+
|
121 |
+
if stream:
|
122 |
+
print(f"response: {response.text}")
|
123 |
+
|
124 |
+
response_container = st.empty()
|
125 |
+
content = ""
|
126 |
+
# Efficiently handle streaming response
|
127 |
+
for chunk in response.iter_lines():
|
128 |
+
|
129 |
+
if len(chunk) > 0:
|
130 |
+
content += extract_content(chunk)
|
131 |
+
response_container.markdown(content)
|
132 |
+
|
133 |
+
else:
|
134 |
+
try:
|
135 |
content = response.json()
|
136 |
+
content_string = content.get('choices', [{}])[0].get('message', {}).get('content', '')
|
137 |
+
st.write(f"AI Response: {content_string}")
|
138 |
+
|
139 |
+
st.success("Response generated!")
|
|
|
140 |
|
141 |
+
except Exception as e:
|
142 |
+
st.error(f"An error occurred: {e}")
|
143 |
+
|
144 |
if __name__ == "__main__":
|
145 |
main()
|