Spaces:
Runtime error
Runtime error
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="β") |