Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import openai
|
4 |
+
import streamlit as st
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
from models.blip_model import extract_image_details
|
9 |
+
from models.gpt_model import generate_response
|
10 |
+
|
11 |
+
# Load environment variables from .env file
|
12 |
+
load_dotenv()
|
13 |
+
|
14 |
+
# Set OpenAI API key
|
15 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
16 |
+
|
17 |
+
# Initialize session state for image details
|
18 |
+
if "image_details" not in st.session_state:
|
19 |
+
st.session_state.image_details = ""
|
20 |
+
|
21 |
+
st.title("Image to Text Response with RAG")
|
22 |
+
|
23 |
+
# File uploader for image upload
|
24 |
+
uploaded_file = st.file_uploader("Upload an Image", type=["jpg", "jpeg", "png"])
|
25 |
+
|
26 |
+
if uploaded_file is not None:
|
27 |
+
if "uploaded_file" not in st.session_state or uploaded_file != st.session_state.uploaded_file:
|
28 |
+
st.session_state.uploaded_file = uploaded_file
|
29 |
+
|
30 |
+
# Clear previous messages
|
31 |
+
st.session_state.messages = []
|
32 |
+
|
33 |
+
# Show loading status while processing the image
|
34 |
+
with st.status("Processing image...", state="running"):
|
35 |
+
image = Image.open(uploaded_file)
|
36 |
+
st.session_state.image_details = extract_image_details(image)
|
37 |
+
|
38 |
+
st.success("Image processed successfully.")
|
39 |
+
else:
|
40 |
+
st.stop()
|
41 |
+
|
42 |
+
# Chat interface
|
43 |
+
if st.session_state.image_details:
|
44 |
+
st.write("### Ask a question about the image")
|
45 |
+
|
46 |
+
if "messages" not in st.session_state:
|
47 |
+
st.session_state.messages = []
|
48 |
+
|
49 |
+
# Display chat messages
|
50 |
+
for message in st.session_state.messages:
|
51 |
+
with st.chat_message(message["role"]):
|
52 |
+
st.write(message["content"])
|
53 |
+
|
54 |
+
# Chat input
|
55 |
+
prompt = st.chat_input("Ask something about the image")
|
56 |
+
if prompt:
|
57 |
+
# Add user message to session state
|
58 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
59 |
+
|
60 |
+
# Generate response
|
61 |
+
response = generate_response([st.session_state.image_details], prompt)
|
62 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
63 |
+
|
64 |
+
# Display user message
|
65 |
+
with st.chat_message("user"):
|
66 |
+
st.write(prompt)
|
67 |
+
|
68 |
+
# Display assistant message
|
69 |
+
with st.chat_message("assistant"):
|
70 |
+
st.write(response)
|