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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #langchain imports
9
+ from langchain.chains import RetrievalQA
10
+ from langchain.text_splitter import CharacterTextSplitter
11
+ from langchain_community.document_loaders import TextLoader
12
+ from langchain_community.vectorstores import Chroma
13
+ from langchain_openai import OpenAIEmbeddings
14
+ from langchain.chains import create_qa_with_sources_chain
15
+ from langchain.chains.combine_documents.stuff import StuffDocumentsChain
16
+ from langchain.prompts import PromptTemplate
17
+ from langchain_openai import ChatOpenAI
18
+ from langchain.schema import Document
19
+
20
+ from langchain.chains.query_constructor.base import AttributeInfo
21
+ from langchain.retrievers.self_query.base import SelfQueryRetriever
22
+
23
+
24
+ #from pdf2image import convert_from_path
25
+ import io
26
+ import json
27
+ import re
28
+
29
+ # Function to encode the image to base64
30
+ # def encode_image(image_file):
31
+ # return base64.b64encode(image_file.getvalue()).decode("utf-8")
32
+
33
+ def encode_image(image_files):
34
+ base64_images = []
35
+
36
+ for image_file in image_files:
37
+ base64_images.append(base64.b64encode(image_file.getvalue()).decode("utf-8"))
38
+
39
+ return base64_images, image_files
40
+
41
+ st.set_page_config(page_title="Document/Image AI Analyst", layout="centered", initial_sidebar_state="collapsed")
42
+ # Streamlit page setup
43
+ st.title("Document/Image AI Analyst: `GPT-4 with Vision` πŸ‘€")
44
+ st.write("")
45
+ st.write("")
46
+ st.write("")
47
+
48
+ # Retrieve the OpenAI API Key from secrets
49
+ #load_dotenv()
50
+ # api_key = os.getenv("OPENAI_API_KEY")t
51
+
52
+ # Guide
53
+ st.subheader('What can it do?')
54
+ with st.expander('Read more details', expanded=False):
55
+ #st.write("There are various use cases that the AI analyst can do!")
56
+ 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.')
57
+ 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!`')
58
+ 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.")
59
+ st.markdown('- And anything else! For a simpler, general demo, upload any image and let it describe what it sees!')
60
+ if st.button('Happy prompting and Cheers! 🎈'):
61
+ st.balloons()
62
+
63
+ # new line space
64
+ st.write("")
65
+
66
+ st.subheader('1. We need an OpenAI API key: ')
67
+ 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.")
68
+ 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`')
69
+
70
+ # Initialize the OpenAI client with the API key
71
+ client = OpenAI(api_key=api_key)
72
+ # Initialize messages object
73
+ messages = []
74
+
75
+
76
+ # new line space
77
+ st.write("")
78
+
79
+ # File uploader allows user to add their own image
80
+ st.subheader('2. Upload Images: ')
81
+ uploaded_files = st.file_uploader("", help='Up to five images only.', type=["jpg", "png", "jpeg"], accept_multiple_files=True)
82
+
83
+
84
+ #############
85
+
86
+ # loader = TextLoader("./kb_document_requirements_v1.txt", encoding="utf-8")
87
+ # documents = loader.load()
88
+
89
+ # text_splitter = CharacterTextSplitter(chunk_size=300, chunk_overlap=0) #you reduced chunk_size from 1000
90
+ # texts = text_splitter.split_documents(documents)
91
+ # for i, text in enumerate(texts):
92
+ # text.metadata["source"] = f"{i+1}-page"
93
+ # embeddings = OpenAIEmbeddings(api_key=api_key)
94
+ # docsearch = Chroma.from_documents(texts, embeddings)
95
+
96
+ # llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613", api_key=api_key)
97
+ # qa_chain = create_qa_with_sources_chain(llm)
98
+
99
+ # doc_prompt = PromptTemplate(
100
+ # template="Content: {page_content}\nSource: {source}",
101
+ # input_variables=["page_content", "source"],
102
+ # )
103
+
104
+ # final_qa_chain = StuffDocumentsChain(
105
+ # llm_chain=qa_chain,
106
+ # document_variable_name="context",
107
+ # document_prompt=doc_prompt,
108
+ # )
109
+
110
+ # retrieval_qa = RetrievalQA(
111
+ # retriever=docsearch.as_retriever(), combine_documents_chain=final_qa_chain
112
+ # )
113
+ #############
114
+
115
+ # Retrieve the OpenAI API Key from secrets
116
+ load_dotenv()
117
+ api_key = os.getenv("OPENAI_API_KEY")
118
+
119
+ # docs = [
120
+ # Document(
121
+ # page_content="Rules and requirements of IELTS",
122
+ # metadata={"type": "english proficiency certification", "name": "ielts", "filename": "./docs/ielts_kb_doc.txt"},
123
+ # ),
124
+ # Document(
125
+ # page_content="Rules and requirements of IELTS UKVI Academic",
126
+ # metadata={"type": "english proficiency certification", "name": "ielts ukvi", "filename": "./docs/pearson_pte_kb_doc.txt"},
127
+ # ),
128
+ # Document(
129
+ # page_content="Rules and requirements of TOEFL iBT (Test of English as a Foreign Language internet-based test)",
130
+ # metadata={"type": "english proficiency certification", "name": "toefl", "filename": "./docs/toefl_kb_doc.txt"},
131
+ # ),
132
+ # Document(
133
+ # page_content="Rules and requirements of Pearson PTE Academic",
134
+ # metadata={"type": "english proficiency certification", "name": "pearson pte academic", "filename": "./docs/ielts_kb_doc.txt"},
135
+ # ),
136
+ # Document(
137
+ # page_content="Requirements of international passport",
138
+ # metadata={"type": "passport", "name": "international passport", "filename": "./docs/passport_kb_doc.txt"},
139
+ # ),
140
+ # ]
141
+
142
+ # docsearch = Chroma.from_documents(docs, OpenAIEmbeddings(), persist_directory="./knowledge_base")
143
+
144
+ # load from disk
145
+ docsearch = Chroma(persist_directory="./knowledge_base", embedding_function=OpenAIEmbeddings())
146
+
147
+ metadata_field_info = [
148
+ AttributeInfo(
149
+ name="type",
150
+ description="The type of document",
151
+ type="string",
152
+ ),
153
+ AttributeInfo(
154
+ name="name",
155
+ description="The name of the document",
156
+ type="string",
157
+ ),
158
+ AttributeInfo(
159
+ name="filename",
160
+ description="The file name of the document",
161
+ type="string",
162
+ ),
163
+ ]
164
+
165
+ document_content_description = "Type of a document"
166
+ llm = ChatOpenAI(temperature=0)
167
+
168
+ retriever = SelfQueryRetriever.from_llm(
169
+ llm,
170
+ docsearch,
171
+ document_content_description,
172
+ metadata_field_info,
173
+ enable_limit=True,
174
+ search_kwargs={"k": 1}
175
+ )
176
+
177
+ # This sample for querying
178
+ # results = retriever.invoke("requirements in passport")
179
+ # st.write("RESULTS: ", results)
180
+ #############
181
+ if uploaded_files:
182
+ if len(uploaded_files) <= 5:
183
+ st.success("You uploaded " + str(len(uploaded_files)) + " images!", icon="βœ…")
184
+ elif len(uploaded_files) > 5:
185
+ st.error("More than 5 uploaded images. Please remove.", icon="❌")
186
+
187
+ file_names = [file.name for file in uploaded_files]
188
+ print("Filenames: ", file_names)
189
+
190
+ for uploaded_file in uploaded_files:
191
+ with st.expander("Uploaded image: `" + uploaded_file.name + "`", expanded = False):
192
+ st.image(uploaded_file, use_column_width=True)
193
+
194
+ # if uploaded_file:
195
+ # # Display the uploaded image
196
+ # with st.expander("Image", expanded = True):
197
+ # st.image(uploaded_file, caption=uploaded_file.name, use_column_width=True)
198
+
199
+ # new line space
200
+ st.write("")
201
+
202
+ # Toggle for showing additional details input
203
+ st.subheader('3. Details about the images:')
204
+ show_details = st.toggle("Add details about the images (optional)", value=False)
205
+ st.caption('')
206
+
207
+ if show_details:
208
+ # Text input for additional details about the image, shown only if toggle is True
209
+ additional_details = st.text_area(
210
+ "Add any additional details or context about the image(s) here:",
211
+ 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)',
212
+ disabled=not show_details
213
+ )
214
+
215
+
216
+ # new line space
217
+ st.write("")
218
+
219
+ # Button to trigger the analysis
220
+ st.subheader('4. Analyze! ')
221
+ analyze_button = st.button("Analyse the image(s)", type="secondary")
222
+ st.caption('')
223
+
224
+ # Check if an image has been uploaded, if the API key is available, and if the button has been pressed
225
+ if uploaded_files is not None and api_key and analyze_button:
226
+
227
+ with st.spinner("Analysing the image(s) ..."):
228
+ # Encode the image
229
+ base64_image, filenames = encode_image(uploaded_files)
230
+ #print("base64 images: ", filenames)
231
+
232
+ #kb_details = ("")
233
+
234
+ # Optimized prompt for additional clarity and detail
235
+
236
+ prompt_text = (
237
+ "You are a highly knowledgeable student admission document identifier. Evaluate each document and identify what type of admission document it is. "
238
+ "Write your output as a JSON object mapping of the document file name and the type of document you identified, using double-quote, not single-quote. "
239
+ "The format of the output must be enclosed in curly-brackets. "
240
+ f"\n\nYou are provided with these corresponding document file names in order:\n{file_names}"
241
+ )
242
+
243
+
244
+ if show_details and additional_details:
245
+ prompt_text += (
246
+ f"\n\nAdditional Context Provided by the User:\n{additional_details}"
247
+ #f"\n\nGeneral Admissions Guide on how to verify student admission documents:\n{kb_details}"
248
+
249
+ )
250
+
251
+ # IF scenarios for images payload for messages var
252
+ if len(uploaded_files) == 1:
253
+ messages = [
254
+ {
255
+ "role": "user",
256
+ "content": [
257
+ {"type": "text", "text": prompt_text},
258
+ {
259
+ "type": "image_url",
260
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
261
+ },
262
+ ],
263
+ }
264
+ ]
265
+ elif len(uploaded_files) == 2:
266
+ messages = [
267
+ {
268
+ "role": "user",
269
+ "content": [
270
+ {"type": "text", "text": prompt_text},
271
+ {
272
+ "type": "image_url",
273
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
274
+ },
275
+ {
276
+ "type": "image_url",
277
+ "image_url": f"data:image/jpeg;base64,{base64_image[1]}",
278
+ },
279
+ ],
280
+ }
281
+ ]
282
+ elif len(uploaded_files) == 3:
283
+ messages = [
284
+ {
285
+ "role": "user",
286
+ "content": [
287
+ {"type": "text", "text": prompt_text},
288
+ {
289
+ "type": "image_url",
290
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
291
+ },
292
+ {
293
+ "type": "image_url",
294
+ "image_url": f"data:image/jpeg;base64,{base64_image[1]}",
295
+ },
296
+ {
297
+ "type": "image_url",
298
+ "image_url": f"data:image/jpeg;base64,{base64_image[2]}",
299
+ },
300
+ ],
301
+ }
302
+ ]
303
+ elif len(uploaded_files) == 4:
304
+ messages = [
305
+ {
306
+ "role": "user",
307
+ "content": [
308
+ {"type": "text", "text": prompt_text},
309
+ {
310
+ "type": "image_url",
311
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
312
+ },
313
+ {
314
+ "type": "image_url",
315
+ "image_url": f"data:image/jpeg;base64,{base64_image[1]}",
316
+ },
317
+ {
318
+ "type": "image_url",
319
+ "image_url": f"data:image/jpeg;base64,{base64_image[2]}",
320
+ },
321
+ {
322
+ "type": "image_url",
323
+ "image_url": f"data:image/jpeg;base64,{base64_image[3]}",
324
+ },
325
+ ],
326
+ }
327
+ ]
328
+ elif len(uploaded_files) == 5:
329
+ messages = [
330
+ {
331
+ "role": "user",
332
+ "content": [
333
+ {"type": "text", "text": prompt_text},
334
+ {
335
+ "type": "image_url",
336
+ "image_url": f"data:image/jpeg;base64,{base64_image[0]}",
337
+ },
338
+ {
339
+ "type": "image_url",
340
+ "image_url": f"data:image/jpeg;base64,{base64_image[1]}",
341
+ },
342
+ {
343
+ "type": "image_url",
344
+ "image_url": f"data:image/jpeg;base64,{base64_image[2]}",
345
+ },
346
+ {
347
+ "type": "image_url",
348
+ "image_url": f"data:image/jpeg;base64,{base64_image[3]}",
349
+ },
350
+ {
351
+ "type": "image_url",
352
+ "image_url": f"data:image/jpeg;base64,{base64_image[4]}",
353
+ },
354
+ ],
355
+ }
356
+ ]
357
+ elif len(uploaded_files) > 5:
358
+ messages = []
359
+
360
+
361
+
362
+ # Make the request to the OpenAI API
363
+ try:
364
+ ##################
365
+ # STEP 1: Identify and map filenames to type of document
366
+ full_response = ''
367
+ message_placeholder = st.empty()
368
+
369
+ for completion in client.chat.completions.create(
370
+ model="gpt-4-vision-preview", messages=messages,
371
+ max_tokens=1200, stream=True,
372
+ ):
373
+ # Check if there is content to display
374
+ if completion.choices[0].delta.content is not None:
375
+ full_response += completion.choices[0].delta.content
376
+ message_placeholder.markdown(full_response + "β–Œ")
377
+ # Final update to placeholder after the stream ends
378
+ #message_placeholder.text(full_response)
379
+
380
+ #full_response = '{"filename1": "Give full information about IELTS Test Result without summarizing", "filename2": "Give full information about TOEFL Test results without summarizing"}'
381
+ ##################
382
+ # STEP 2: perform validation via KB retrieval
383
+ # STEP 2.1: Retrieval individual info and concat into an array
384
+
385
+ # Clean up format:
386
+ json_response = re.search(r'\{.*\}', full_response, re.DOTALL).group()
387
+
388
+ full_response_json = json.loads(json_response)
389
+
390
+ # Display identified documents
391
+ # Initialize an empty list to store markdown lines
392
+ markdown_list = []
393
+
394
+ # Iterate through the dictionary and format each item
395
+ for filename, content in full_response_json.items():
396
+ markdown_list.append(f"- {filename} is a {content}")
397
+
398
+ # Join the list into a single string with newline characters
399
+ markdown_string = '\n'.join(markdown_list)
400
+ message_placeholder.markdown("**Identified Documents:**\n\n" + markdown_string)
401
+
402
+ ### TO DO : The ABOVE code can be in a function or object.
403
+ # Initialize an empty array to store the results
404
+ retrieved_knowledge = []
405
+
406
+ # Iterate over each item in the full_response dictionary
407
+ #for filename, details in full_response_json.items():
408
+ st.subheader("5. Analysis Results")
409
+ for i, (filename, details) in enumerate(full_response_json.items()):
410
+
411
+ with st.expander(details):
412
+ file_content = ""
413
+ # perform query to KB, details is the query
414
+ results = retriever.invoke(details)
415
+
416
+ # Step 1: Access the first Document
417
+ document = results[0]
418
+
419
+ # Step 2: Retrieve the filename from the metadata
420
+ kb_retrieved_filename = document.metadata['filename']
421
+
422
+ # Step 3: Open the file using the extracted filename
423
+ with open(kb_retrieved_filename, 'r') as file:
424
+ file_content = file.read()
425
+
426
+ ### TO DO: NOW perform the actual validation
427
+ prompt_text_validation = (
428
+ "You are a highly knowledgeable student admission document image verifier. "
429
+ "Your task is to examine the image in detail. "
430
+ #"Provide a comprehensive, factual, and accurate explanation of what each image depict and classify them based on which student admission document it is. "
431
+ "Verify and compare whether the details in the document image is valid by checking the provided DOCUMENT REQUIREMENTS. "
432
+ "Highlight key elements on the document image that is valid and invalid, and present your analysis in clear, well-structured markdown format. "
433
+ "If applicable, identify any falsification, tampering and editing of the image that could potentially mean the document is not valid and was tampered. "
434
+ #"Assume the reader has a basic understanding of how student admission documents should be."
435
+ "Lastly, include your final verdict on whether the document is legit or needs further checking. Label as [LEGIT], [NEED FURTHER CHECKING] or [NOT LEGIT]"
436
+ f"\n\nDOCUMENT REQUIREMENTS that must be met to be considered valid:\n{file_content}"
437
+ )
438
+
439
+ messages = [
440
+ {
441
+ "role": "user",
442
+ "content": [
443
+ {"type": "text", "text": prompt_text_validation},
444
+ {
445
+ "type": "image_url",
446
+ "image_url": f"data:image/jpeg;base64,{base64_image[i]}",
447
+ },
448
+ ],
449
+ }
450
+ ]
451
+
452
+ validation_response = ''
453
+ validation_placeholder = st.empty()
454
+
455
+ prompt_message = ''
456
+
457
+
458
+ #prompt_placeholder = st.write("COMPLETE PROMPT", prompt_text_validation)
459
+
460
+ for completion in client.chat.completions.create(
461
+ model="gpt-4-vision-preview", messages=messages,
462
+ max_tokens=1200, stream=True
463
+ ):
464
+ # Check if there is content to display
465
+ if completion.choices[0].delta.content is not None:
466
+ validation_response += completion.choices[0].delta.content
467
+ validation_placeholder.markdown(validation_response + "β–Œ")
468
+ # Final update to validation placeholder after the stream ends
469
+
470
+ #validation_placeholder.text(validation_response)
471
+
472
+ # Now you can work with file_content
473
+ #print(file_content)
474
+ # add data to array
475
+ #retrieved_knowledge.append(validation_response)
476
+
477
+ validation_placeholder.markdown(validation_response)
478
+
479
+
480
+ # Display the response in the app
481
+ # st.write(response.choices[0].message.content)
482
+ except Exception as e:
483
+ st.error(f"An error occurred: {e}")
484
+ else:
485
+ # Warnings for user action required
486
+ if not uploaded_files and analyze_button:
487
+ st.warning("Please upload at least one image. Up to five.", icon="⚠️")
488
+ if not api_key:
489
+ st.error("Please enter your OpenAI API key.", icon="❌")