louiecerv commited on
Commit
9dc0324
·
1 Parent(s): 223c115

fixed the handling of the streamed response

Browse files
Files changed (1) hide show
  1. app.py +83 -76
app.py CHANGED
@@ -3,6 +3,7 @@ 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
@@ -16,40 +17,36 @@ 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
36
  Department of Computer Science
37
  College of Information and Communications Technology
38
  West Visayas State University
39
  """
40
  with st.expander("About"):
41
- st.text(text)
42
 
43
  st.write("Upload an image and select the image analysis task.")
44
 
45
  # File upload for image
46
  uploaded_image = st.file_uploader("Upload an Image", type=["jpg", "jpeg", "png"])
 
 
47
  if uploaded_image is not None:
48
- # Encode the uploaded image to base64
49
- base64_image = base64.b64encode(uploaded_image.getvalue()).decode('utf-8')
 
 
 
 
 
50
 
51
  # Display the uploaded image
52
- st.image(uploaded_image, caption="Uploaded Image", use_container_width=True)
53
 
54
  # List of image analysis tasks
55
  analysis_tasks = [
@@ -66,83 +63,93 @@ def main():
66
  ]
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
  if stream:
 
111
  response_container = st.empty()
112
  content = ""
113
- # Efficiently handle streaming response
114
- for chunk in response.iter_lines():
115
- if len(chunk) > 0:
116
- # Decode the bytes object into a string
117
- chunk_str = chunk.decode('utf-8')
118
- # Remove the "data: " prefix
119
- if chunk_str.startswith("data: "):
120
- chunk_str = chunk_str[6:]
121
- if chunk_str.strip() == "[DONE]":
122
- break
123
- # Check if the string is not empty
124
- if chunk_str.strip() != "":
125
  try:
126
- # Attempt to parse the string as JSON
127
- chunk_dict = json.loads(chunk_str)
128
- # Now you can access the 'choices' key
129
- content += chunk_dict['choices'][0]['delta']['content']
130
- response_container.markdown(content)
 
 
131
  except json.JSONDecodeError as e:
132
- # Handle the error if the string is not valid JSON
133
- print(f"Error parsing JSON: {e}")
134
- print(f"Invalid JSON string: {chunk_str}")
135
 
136
  else:
137
- try:
138
- content = response.json()
139
- content_string = content.get('choices', [{}])[0].get('message', {}).get('content', '')
140
- st.write(f"AI Response: {content_string}")
141
-
142
- st.success("Response generated!")
 
 
 
 
 
 
 
143
 
144
- except Exception as e:
145
- st.error(f"An error occurred: {e}")
146
-
147
  if __name__ == "__main__":
148
- main()
 
3
  import requests
4
  import streamlit as st
5
  import json
6
+ import tempfile
7
 
8
  if "stream" not in st.session_state:
9
  st.session_state.stream = True
 
17
  with open(image_path, "rb") as image_file:
18
  return base64.b64encode(image_file.read()).decode('utf-8')
19
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def main():
21
+ st.title(f"Multimodal Image Analysis with {MODEL_ID}")
22
 
23
+ # Display about section
24
+ about_text = """Prof. Louie F. Cervantes, M. Eng. (Information Engineering)
25
  CCS 229 - Intelligent Systems
26
  Department of Computer Science
27
  College of Information and Communications Technology
28
  West Visayas State University
29
  """
30
  with st.expander("About"):
31
+ st.text(about_text)
32
 
33
  st.write("Upload an image and select the image analysis task.")
34
 
35
  # File upload for image
36
  uploaded_image = st.file_uploader("Upload an Image", type=["jpg", "jpeg", "png"])
37
+ temp_file_path = None
38
+
39
  if uploaded_image is not None:
40
+ with tempfile.NamedTemporaryFile(delete=False) as temp_file:
41
+ temp_file.write(uploaded_image.getvalue())
42
+ temp_file_path = temp_file.name
43
+
44
+ # Encode image as Base64
45
+ with open(temp_file_path, "rb") as f:
46
+ base64_image = base64.b64encode(f.read()).decode()
47
 
48
  # Display the uploaded image
49
+ st.image(uploaded_image, caption="Uploaded Image", use_container_width=True)
50
 
51
  # List of image analysis tasks
52
  analysis_tasks = [
 
63
  ]
64
 
65
  # Task selection dropdown
66
+ selected_task = st.selectbox("Select an image analysis task:", [""] + analysis_tasks)
67
+
68
+ # Checkbox for streaming
69
+ stream = st.checkbox("Begin streaming the AI response as soon as it is available.", value=st.session_state.stream)
70
 
71
  if st.button("Generate Response"):
72
+ if not api_key:
73
+ st.error("API key not found. Please set the NVIDIA_VISION_API_KEY environment variable.")
74
+ return
75
 
76
+ if uploaded_image is None:
77
+ st.error("Please upload an image.")
78
  return
79
 
80
+ if not selected_task:
81
+ st.error("Please select an image analysis task.")
82
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ # Headers for the API call
85
+ headers = {
86
+ "Authorization": f"Bearer {api_key}",
87
+ "Accept": "text/event-stream" if stream else "application/json"
88
+ }
89
+
90
+ # Prepare the multimodal prompt
91
+ payload = {
92
+ "model": MODEL_ID,
93
+ "messages": [
94
+ {
95
+ "role": "user",
96
+ "content": f'{selected_task} <img src="data:image/png;base64,{base64_image}" />'
97
+ }
98
+ ],
99
+ "max_tokens": 512,
100
+ "temperature": 1.0,
101
+ "top_p": 1.0,
102
+ "stream": stream
103
+ }
104
+
105
+ try:
106
  with st.spinner("Processing..."):
107
  response = requests.post(
108
  invoke_url,
109
  headers=headers,
110
  json=payload,
111
+ stream=stream
112
  )
113
+ response.raise_for_status() # Raise exception for HTTP errors
114
 
115
  if stream:
116
+ # Handle streaming response
117
  response_container = st.empty()
118
  content = ""
119
+ for chunk in response.iter_lines(decode_unicode=True):
120
+ if chunk:
121
+ if "[DONE]" in chunk:
122
+ # Handle the end chunk
123
+ st.write("Response generation complete.")
124
+ break
125
+ # Check if the chunk is a JSON string
126
+ elif chunk.startswith("data:"):
127
+ chunk = chunk[5:].strip() # Remove the "data:" prefix
 
 
 
128
  try:
129
+ if len(chunk) > 0:
130
+ chunk_dict = json.loads(chunk)
131
+ if "choices" in chunk_dict and chunk_dict["choices"]:
132
+ delta_content = chunk_dict["choices"][0]["delta"]["content"]
133
+ content += delta_content
134
+ response_container.write(content)
135
+
136
  except json.JSONDecodeError as e:
137
+ st.error(f"Error parsing JSON: {e}")
 
 
138
 
139
  else:
140
+ # Handle non-streaming response
141
+ content = response.json()
142
+ content_string = content.get("choices", [{}])[0].get("message", {}).get("content", "")
143
+ st.write(f"AI Response: {content_string}")
144
+ st.success("Response generated!")
145
+ except requests.exceptions.RequestException as e:
146
+ st.error(f"An error occurred while making the API call: {e}")
147
+ except Exception as e:
148
+ st.error(f"An unexpected error occurred: {e}")
149
+ finally:
150
+ # Clean up temporary file
151
+ if temp_file_path and os.path.exists(temp_file_path):
152
+ os.remove(temp_file_path)
153
 
 
 
 
154
  if __name__ == "__main__":
155
+ main()