Sayandip commited on
Commit
1709b38
·
verified ·
1 Parent(s): fb7c648

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -6
app.py CHANGED
@@ -15,6 +15,14 @@ import google.generativeai as genai
15
  st.set_page_config(page_title="Gemini Q&A App", layout="centered")
16
  st.title("🤖 Q&A - Document & Image")
17
 
 
 
 
 
 
 
 
 
18
  # Load API key
19
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY") or st.secrets.get("GOOGLE_API_KEY")
20
  if not GOOGLE_API_KEY:
@@ -97,7 +105,6 @@ if uploaded_files and question:
97
  file_ext = uploaded_file.name.split('.')[-1].lower()
98
 
99
  if file_ext in ['jpg', 'jpeg', 'png']:
100
- # Store image data for later processing
101
  image_bytes = uploaded_file.read()
102
  encoded_image = base64.b64encode(image_bytes).decode("utf-8")
103
  image_contents.append({
@@ -109,7 +116,6 @@ if uploaded_files and question:
109
  st.image(image_bytes, caption=uploaded_file.name, use_container_width=True)
110
  continue
111
 
112
- # Process document files
113
  temp_file_path = "temp." + file_ext
114
  with open(temp_file_path, "wb") as temp_file:
115
  temp_file.write(uploaded_file.read())
@@ -122,27 +128,47 @@ if uploaded_files and question:
122
  else:
123
  combined_context += f"\n\n---\nDocument: {uploaded_file.name}\n\n{extracted_text}"
124
 
125
- # Process if there's valid content
126
  if combined_context.strip() or image_contents:
127
  with st.spinner("Generating answer..."):
128
  try:
129
  content_blocks = []
130
 
131
- # Add text context
 
 
 
 
 
 
 
 
132
  if combined_context.strip():
133
  content_blocks.append({"text": f"Context:\n{combined_context}"})
134
 
135
  # Add image blocks
136
  content_blocks.extend(image_contents)
137
 
138
- # Add user question
139
  content_blocks.append({"text": f"Question: {question}"})
140
 
141
  response = model.generate_content(contents=content_blocks)
142
  st.success("💡 Answer:")
143
  st.write(response.text)
144
 
 
 
 
 
 
 
145
  except Exception as e:
146
  st.error(f"Error generating answer: {e}")
147
  else:
148
- st.warning("No valid documents or images processed.")
 
 
 
 
 
 
 
 
15
  st.set_page_config(page_title="Gemini Q&A App", layout="centered")
16
  st.title("🤖 Q&A - Document & Image")
17
 
18
+ # Initialize chat history
19
+ if "chat_history" not in st.session_state:
20
+ st.session_state.chat_history = []
21
+
22
+ # Optional: Clear history button
23
+ if st.button("🧹 Clear Chat History"):
24
+ st.session_state.chat_history = []
25
+
26
  # Load API key
27
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY") or st.secrets.get("GOOGLE_API_KEY")
28
  if not GOOGLE_API_KEY:
 
105
  file_ext = uploaded_file.name.split('.')[-1].lower()
106
 
107
  if file_ext in ['jpg', 'jpeg', 'png']:
 
108
  image_bytes = uploaded_file.read()
109
  encoded_image = base64.b64encode(image_bytes).decode("utf-8")
110
  image_contents.append({
 
116
  st.image(image_bytes, caption=uploaded_file.name, use_container_width=True)
117
  continue
118
 
 
119
  temp_file_path = "temp." + file_ext
120
  with open(temp_file_path, "wb") as temp_file:
121
  temp_file.write(uploaded_file.read())
 
128
  else:
129
  combined_context += f"\n\n---\nDocument: {uploaded_file.name}\n\n{extracted_text}"
130
 
 
131
  if combined_context.strip() or image_contents:
132
  with st.spinner("Generating answer..."):
133
  try:
134
  content_blocks = []
135
 
136
+ # Add prior Q&A as part of the context
137
+ if st.session_state.chat_history:
138
+ history_text = "\n\n".join(
139
+ f"Q: {entry['question']}\nA: {entry['answer']}"
140
+ for entry in st.session_state.chat_history
141
+ )
142
+ content_blocks.append({"text": f"Previous conversation:\n{history_text}"})
143
+
144
+ # Add file text content
145
  if combined_context.strip():
146
  content_blocks.append({"text": f"Context:\n{combined_context}"})
147
 
148
  # Add image blocks
149
  content_blocks.extend(image_contents)
150
 
151
+ # Add current question
152
  content_blocks.append({"text": f"Question: {question}"})
153
 
154
  response = model.generate_content(contents=content_blocks)
155
  st.success("💡 Answer:")
156
  st.write(response.text)
157
 
158
+ # Save to session history
159
+ st.session_state.chat_history.append({
160
+ "question": question,
161
+ "answer": response.text
162
+ })
163
+
164
  except Exception as e:
165
  st.error(f"Error generating answer: {e}")
166
  else:
167
+ st.warning("No valid documents or images processed.")
168
+
169
+ # Optional: Show full conversation history
170
+ if st.session_state.chat_history:
171
+ st.markdown("### 🗂️ Chat History")
172
+ for i, entry in enumerate(st.session_state.chat_history, 1):
173
+ st.markdown(f"**Q{i}:** {entry['question']}")
174
+ st.markdown(f"**A{i}:** {entry['answer']}")