Spaces:
Runtime error
Runtime error
File size: 11,186 Bytes
df9fb1f e1748b4 df9fb1f 4b9d9a7 df9fb1f |
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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
import streamlit as st
import base64
import os
import json
#from dotenv import load_dotenv
from openai import OpenAI
#from pdf2image import convert_from_path
import io
# Function to encode the image to base64
# def encode_image(image_file):
# return base64.b64encode(image_file.getvalue()).decode("utf-8")
def encode_image(image_files):
base64_images = []
for image_file in image_files:
base64_images.append(base64.b64encode(image_file.getvalue()).decode("utf-8"))
return base64_images
st.set_page_config(page_title="Document/Image AI Analyst", layout="centered", initial_sidebar_state="collapsed")
# Streamlit page setup
st.title("Document/Image AI Analyst: `GPT-4 with Vision` π")
st.write("")
st.write("")
st.write("")
# Retrieve the OpenAI API Key from secrets
# load_dotenv()
# api_key = os.getenv("OPENAI_API_KEY")t
# Guide
st.subheader('What can it do?')
with st.expander('Read more details', expanded=False):
#st.write("There are various use cases that the AI analyst can do!")
st.markdown('- It can describe details found on the images. For instance, it can tell the details on an uploaded passport, such as full name, passport number, country, etc.')
st.markdown('- It can check for validity of images or identification documents. It also checks the legitimacy of documents (if applicable). `Try uploading a suspicious passport picture!`')
st.markdown("- It can compare multiple documents, such as identifying whether a person's photo is the same as the uploaded personal documents. In a comparison use case, feel free to provide extra info (optional) on what comparison you want to perform.")
st.markdown('- And anything else! For a simpler, general demo, upload any image and let it describe what it sees!')
if st.button('Happy prompting and Cheers! π'):
st.balloons()
# new line space
st.write("")
st.subheader('1. We need an OpenAI API key: ')
api_key = st.text_input('',placeholder='Enter your OpenAI API key', type='password', help="You can find your OpenAI API key here: https://platform.openai.com/api-keys. Or if you are provided with one by your organization.")
st.caption('Never share your OpenAI API key to anyone. Note that usage of your OpenAI API key will be billed to your OpenAI account. Keep in mind that an image analysis costs approximately `$0.04`')
# Initialize the OpenAI client with the API key
client = OpenAI(api_key=api_key)
# Initialize messages object
messages = []
# new line space
st.write("")
# File uploader allows user to add their own image
st.subheader('2. Upload Images: ')
uploaded_files = st.file_uploader("", help='Up to five images only.', type=["jpg", "png", "jpeg"], accept_multiple_files=True)
if uploaded_files:
if len(uploaded_files) <= 5:
st.success("You uploaded " + str(len(uploaded_files)) + " images!", icon="β
")
elif len(uploaded_files) > 5:
st.error("More than 5 uploaded images. Please remove.", icon="β")
for uploaded_file in uploaded_files:
with st.expander("Uploaded image: `" + uploaded_file.name + "`", expanded = False):
st.image(uploaded_file, use_column_width=True)
# if uploaded_file:
# # Display the uploaded image
# with st.expander("Image", expanded = True):
# st.image(uploaded_file, caption=uploaded_file.name, use_column_width=True)
# new line space
st.write("")
# Toggle for showing additional details input
st.subheader('3. Details about the images:')
show_details = st.toggle("Add details about the images (optional)", value=False)
st.caption('')
if show_details:
# Text input for additional details about the image, shown only if toggle is True
additional_details = st.text_area(
"Add any additional details or context about the image(s) here:",
placeholder='I am typically able to understand images without context, but feel free to describe what type of analysis you want. For instance, verifying personal documents, checking for falsification or nothing at all (optional)',
disabled=not show_details
)
# new line space
st.write("")
# Button to trigger the analysis
st.subheader('4. Analyze! ')
analyze_button = st.button("Analyse the image(s)", type="secondary")
st.caption('')
# Check if an image has been uploaded, if the API key is available, and if the button has been pressed
if uploaded_files is not None and api_key and analyze_button:
with st.spinner("Analysing the image(s) ..."):
# Encode the image
base64_image = encode_image(uploaded_files)
# Optimized prompt for additional clarity and detail
prompt_text = (
"You are a highly knowledgeable personal document image analysis expert. "
"Your task is to examine the following images in detail. "
"Provide a comprehensive, factual, and accurate explanation of what the images depict. "
"Highlight key elements and their significance, and present your analysis in clear, well-structured markdown format. "
"If applicable, identify any falsification, tampering and editing of the image that could potentially mean the document is not legitimate and untampered. "
"Assume the reader has a basic understanding of how personal documents should be."
"Lastly, include your final verdict on whether the document is legit or needs further checking. Label as [LEGIT] or [NOT LEGIT]"
"Create a detailed image caption in bold explaining in short."
)
if show_details and additional_details:
prompt_text += (
f"\n\nAdditional Context Provided by the User:\n{additional_details}"
)
# IF scenarios for images payload for messages var
if len(uploaded_files) == 1:
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[0]}",
},
],
}
]
elif len(uploaded_files) == 2:
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[0]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[1]}",
},
],
}
]
elif len(uploaded_files) == 3:
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[0]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[1]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[2]}",
},
],
}
]
elif len(uploaded_files) == 4:
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[0]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[1]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[2]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[3]}",
},
],
}
]
elif len(uploaded_files) == 5:
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[0]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[1]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[2]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[3]}",
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image[4]}",
},
],
}
]
elif len(uploaded_files) > 5:
messages = []
# Make the request to the OpenAI API
try:
# Without Stream
# response = client.chat.completions.create(
# model="gpt-4-vision-preview", messages=messages, max_tokens=500, stream=False
# )
# Stream the response
full_response = ""
message_placeholder = st.empty()
for completion in client.chat.completions.create(
model="gpt-4-vision-preview", messages=messages,
max_tokens=1200, stream=True
):
# Check if there is content to display
if completion.choices[0].delta.content is not None:
full_response += completion.choices[0].delta.content
message_placeholder.markdown(full_response + "β")
# Final update to placeholder after the stream ends
message_placeholder.markdown(full_response)
# Display the response in the app
# st.write(response.choices[0].message.content)
except Exception as e:
st.error(f"An error occurred: {e}")
else:
# Warnings for user action required
if not uploaded_files and analyze_button:
st.warning("Please upload at least one image. Up to five.", icon="β οΈ")
if not api_key:
st.error("Please enter your OpenAI API key.", icon="β") |