fishytorts commited on
Commit
df9fb1f
·
1 Parent(s): d0ab7f5

first version

Browse files
Files changed (1) hide show
  1. app.py +276 -0
app.py CHANGED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import base64
3
+ import os
4
+ import json
5
+ from dotenv import load_dotenv
6
+ from openai import OpenAI
7
+
8
+ #from pdf2image import convert_from_path
9
+ import io
10
+
11
+ # Function to encode the image to base64
12
+ # def encode_image(image_file):
13
+ # return base64.b64encode(image_file.getvalue()).decode("utf-8")
14
+
15
+ def encode_image(image_files):
16
+ base64_images = []
17
+
18
+ for image_file in image_files:
19
+ base64_images.append(base64.b64encode(image_file.getvalue()).decode("utf-8"))
20
+
21
+ return base64_images
22
+
23
+ st.set_page_config(page_title="Document/Image AI Analyst", layout="centered", initial_sidebar_state="collapsed")
24
+ # Streamlit page setup
25
+ st.title("Document/Image AI Analyst: `GPT-4 with Vision` 👀")
26
+ st.write("")
27
+ st.write("")
28
+ st.write("")
29
+
30
+ # Retrieve the OpenAI API Key from secrets
31
+ load_dotenv()
32
+ # api_key = os.getenv("OPENAI_API_KEY")t
33
+
34
+ # Guide
35
+ st.subheader('What can it do?')
36
+ with st.expander('Read more details', expanded=False):
37
+ #st.write("There are various use cases that the AI analyst can do!")
38
+ 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.')
39
+ 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!`')
40
+ 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.")
41
+ st.markdown('- And anything else! For a simpler, general demo, upload any image and let it describe what it sees!')
42
+ if st.button('Happy prompting and Cheers! 🎈'):
43
+ st.balloons()
44
+
45
+ # new line space
46
+ st.write("")
47
+
48
+ st.subheader('1. We need an OpenAI API key: ')
49
+ 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.")
50
+ 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`')
51
+
52
+ # Initialize the OpenAI client with the API key
53
+ client = OpenAI(api_key=api_key)
54
+ # Initialize messages object
55
+ messages = []
56
+
57
+
58
+ # new line space
59
+ st.write("")
60
+
61
+ # File uploader allows user to add their own image
62
+ st.subheader('2. Upload Images: ')
63
+ uploaded_files = st.file_uploader("", help='Up to five images only.', type=["jpg", "png", "jpeg"], accept_multiple_files=True)
64
+
65
+
66
+
67
+
68
+
69
+ if uploaded_files:
70
+ if len(uploaded_files) <= 5:
71
+ st.success("You uploaded " + str(len(uploaded_files)) + " images!", icon="✅")
72
+ elif len(uploaded_files) > 5:
73
+ st.error("More than 5 uploaded images. Please remove.", icon="❌")
74
+
75
+ for uploaded_file in uploaded_files:
76
+ with st.expander("Uploaded image: `" + uploaded_file.name + "`", expanded = False):
77
+ st.image(uploaded_file, use_column_width=True)
78
+
79
+ # if uploaded_file:
80
+ # # Display the uploaded image
81
+ # with st.expander("Image", expanded = True):
82
+ # st.image(uploaded_file, caption=uploaded_file.name, use_column_width=True)
83
+
84
+ # new line space
85
+ st.write("")
86
+
87
+ # Toggle for showing additional details input
88
+ st.subheader('3. Details about the images:')
89
+ show_details = st.toggle("Add details about the images (optional)", value=False)
90
+ st.caption('')
91
+
92
+ if show_details:
93
+ # Text input for additional details about the image, shown only if toggle is True
94
+ additional_details = st.text_area(
95
+ "Add any additional details or context about the image(s) here:",
96
+ 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)',
97
+ disabled=not show_details
98
+ )
99
+
100
+
101
+ # new line space
102
+ st.write("")
103
+
104
+ # Button to trigger the analysis
105
+ st.subheader('4. Analyze! ')
106
+ analyze_button = st.button("Analyse the image(s)", type="secondary")
107
+ st.caption('')
108
+
109
+ # Check if an image has been uploaded, if the API key is available, and if the button has been pressed
110
+ if uploaded_files is not None and api_key and analyze_button:
111
+
112
+ with st.spinner("Analysing the image(s) ..."):
113
+ # Encode the image
114
+ base64_image = encode_image(uploaded_files)
115
+
116
+ # Optimized prompt for additional clarity and detail
117
+ prompt_text = (
118
+ "You are a highly knowledgeable personal document image analysis expert. "
119
+ "Your task is to examine the following images in detail. "
120
+ "Provide a comprehensive, factual, and accurate explanation of what the images depict. "
121
+ "Highlight key elements and their significance, and present your analysis in clear, well-structured markdown format. "
122
+ "If applicable, identify any falsification, tampering and editing of the image that could potentially mean the document is not legitimate and untampered. "
123
+ "Assume the reader has a basic understanding of how personal documents should be."
124
+ "Lastly, include your final verdict on whether the document is legit or needs further checking. Label as [LEGIT] or [NOT LEGIT]"
125
+ "Create a detailed image caption in bold explaining in short."
126
+ )
127
+
128
+ if show_details and additional_details:
129
+ prompt_text += (
130
+ f"\n\nAdditional Context Provided by the User:\n{additional_details}"
131
+ )
132
+
133
+ # IF scenarios for images payload for messages var
134
+ if len(uploaded_files) == 1:
135
+ messages = [
136
+ {
137
+ "role": "user",
138
+ "content": [
139
+ {"type": "text", "text": prompt_text},
140
+ {
141
+ "type": "image_url",
142
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
143
+ },
144
+ ],
145
+ }
146
+ ]
147
+ elif len(uploaded_files) == 2:
148
+ messages = [
149
+ {
150
+ "role": "user",
151
+ "content": [
152
+ {"type": "text", "text": prompt_text},
153
+ {
154
+ "type": "image_url",
155
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
156
+ },
157
+ {
158
+ "type": "image_url",
159
+ "image_url": f"data:image/jpeg;base64,{base64_image[1]}",
160
+ },
161
+ ],
162
+ }
163
+ ]
164
+ elif len(uploaded_files) == 3:
165
+ messages = [
166
+ {
167
+ "role": "user",
168
+ "content": [
169
+ {"type": "text", "text": prompt_text},
170
+ {
171
+ "type": "image_url",
172
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
173
+ },
174
+ {
175
+ "type": "image_url",
176
+ "image_url": f"data:image/jpeg;base64,{base64_image[1]}",
177
+ },
178
+ {
179
+ "type": "image_url",
180
+ "image_url": f"data:image/jpeg;base64,{base64_image[2]}",
181
+ },
182
+ ],
183
+ }
184
+ ]
185
+ elif len(uploaded_files) == 4:
186
+ messages = [
187
+ {
188
+ "role": "user",
189
+ "content": [
190
+ {"type": "text", "text": prompt_text},
191
+ {
192
+ "type": "image_url",
193
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
194
+ },
195
+ {
196
+ "type": "image_url",
197
+ "image_url": f"data:image/jpeg;base64,{base64_image[1]}",
198
+ },
199
+ {
200
+ "type": "image_url",
201
+ "image_url": f"data:image/jpeg;base64,{base64_image[2]}",
202
+ },
203
+ {
204
+ "type": "image_url",
205
+ "image_url": f"data:image/jpeg;base64,{base64_image[3]}",
206
+ },
207
+ ],
208
+ }
209
+ ]
210
+ elif len(uploaded_files) == 5:
211
+ messages = [
212
+ {
213
+ "role": "user",
214
+ "content": [
215
+ {"type": "text", "text": prompt_text},
216
+ {
217
+ "type": "image_url",
218
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
219
+ },
220
+ {
221
+ "type": "image_url",
222
+ "image_url": f"data:image/jpeg;base64,{base64_image[1]}",
223
+ },
224
+ {
225
+ "type": "image_url",
226
+ "image_url": f"data:image/jpeg;base64,{base64_image[2]}",
227
+ },
228
+ {
229
+ "type": "image_url",
230
+ "image_url": f"data:image/jpeg;base64,{base64_image[3]}",
231
+ },
232
+ {
233
+ "type": "image_url",
234
+ "image_url": f"data:image/jpeg;base64,{base64_image[4]}",
235
+ },
236
+ ],
237
+ }
238
+ ]
239
+ elif len(uploaded_files) > 5:
240
+ messages = []
241
+
242
+
243
+
244
+ # Make the request to the OpenAI API
245
+ try:
246
+ # Without Stream
247
+
248
+ # response = client.chat.completions.create(
249
+ # model="gpt-4-vision-preview", messages=messages, max_tokens=500, stream=False
250
+ # )
251
+
252
+ # Stream the response
253
+ full_response = ""
254
+ message_placeholder = st.empty()
255
+
256
+ for completion in client.chat.completions.create(
257
+ model="gpt-4-vision-preview", messages=messages,
258
+ max_tokens=1200, stream=True
259
+ ):
260
+ # Check if there is content to display
261
+ if completion.choices[0].delta.content is not None:
262
+ full_response += completion.choices[0].delta.content
263
+ message_placeholder.markdown(full_response + "▌")
264
+ # Final update to placeholder after the stream ends
265
+ message_placeholder.markdown(full_response)
266
+
267
+ # Display the response in the app
268
+ # st.write(response.choices[0].message.content)
269
+ except Exception as e:
270
+ st.error(f"An error occurred: {e}")
271
+ else:
272
+ # Warnings for user action required
273
+ if not uploaded_files and analyze_button:
274
+ st.warning("Please upload at least one image. Up to five.", icon="⚠️")
275
+ if not api_key:
276
+ st.error("Please enter your OpenAI API key.", icon="❌")