Sayandip commited on
Commit
cb47b15
·
verified ·
1 Parent(s): bcee343

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -97
app.py CHANGED
@@ -84,115 +84,112 @@ def export_conversation_to_pdf(conversation_history):
84
  return pdf_path
85
 
86
  def main():
87
- # Initialize session state variables
 
 
88
  if "conversation" not in st.session_state:
89
  st.session_state.conversation = []
90
  if "document_text" not in st.session_state:
91
  st.session_state.document_text = ""
92
  if "chat_active" not in st.session_state:
93
  st.session_state.chat_active = True
94
- if "chat_history" not in st.session_state:
95
- st.session_state.chat_history = [] # Initialize chat history
96
-
97
- st.set_page_config(page_title="Gemini Chat QA", layout="wide")
98
- st.title("📄 Chat with Your Document using Gemini (Sayandip+Dhiraj+Fazal)")
99
 
100
- uploaded_files = st.file_uploader(
101
- "Upload one or more documents or images",
102
- type=["docx", "xlsx", "pdf", "csv", "txt", "pptx", "tex", "html", "htm", "jpg", "jpeg", "png"],
103
- accept_multiple_files=True
104
  )
105
 
106
- if uploaded_files:
107
- combined_context = ""
108
- image_contents = []
109
-
110
- for uploaded_file in uploaded_files:
111
- file_ext = uploaded_file.name.split('.')[-1].lower()
112
-
113
- try:
114
- if file_ext == "txt":
115
- combined_context += uploaded_file.read().decode("utf-8")
116
- elif file_ext == "docx":
117
- combined_context += extract_text_from_docx(uploaded_file)
118
- elif file_ext == "csv":
119
- combined_context += extract_text_from_csv(uploaded_file)
120
- elif file_ext == "xlsx":
121
- combined_context += extract_text_from_xlsx(uploaded_file)
122
- elif file_ext == "pptx":
123
- combined_context += extract_text_from_pptx(uploaded_file)
124
- elif file_ext == "pdf":
125
- combined_context += extract_text_from_pdf(uploaded_file)
126
- elif file_ext in ["html", "htm"]:
127
- combined_context += extract_text_from_html(uploaded_file)
128
- elif file_ext == "tex":
129
- combined_context += extract_text_from_tex(uploaded_file)
130
- elif file_ext in ["jpg", "jpeg", "png"]:
131
- image_data = process_image(uploaded_file)
132
- image_contents.append(image_data)
133
- st.image(uploaded_file, caption=uploaded_file.name, use_container_width=True)
134
-
135
- except Exception as e:
136
- st.error(f"Error processing {uploaded_file.name}: {e}")
137
-
138
- if combined_context.strip() or image_contents:
139
- with st.spinner("Generating answer..."):
140
- try:
141
- content_blocks = []
142
-
143
- # Add prior Q&A as part of the context
144
- if st.session_state.conversation:
145
- history_text = "\n\n".join(
146
- f"Q: {entry[0]}\nA: {entry[1]}"
147
- for entry in st.session_state.conversation
148
- )
149
- content_blocks.append({"text": f"Previous conversation:\n{history_text}"})
150
-
151
- # Add file text content
152
- if combined_context.strip():
153
- content_blocks.append({"text": f"Context:\n{combined_context}"})
154
-
155
- # Add image blocks
156
- content_blocks.extend(image_contents)
157
-
158
- # Add current question
159
- user_input = st.text_input("Ask a question about the documents (type 'exit' to stop):")
160
  if user_input.strip().lower() == "exit":
161
  st.session_state.chat_active = False
162
  st.success("Chat ended. Reload to start again.")
163
  else:
164
- content_blocks.append({"text": f"Question: {user_input}"})
165
-
166
- response = client.models.generate_content(
167
- model="gemini-2.0-flash",
168
- contents=content_blocks
169
- )
170
-
171
- st.session_state.conversation.append((user_input, response.text))
172
- st.success("💡 Answer:")
173
- st.write(response.text)
174
-
175
- # Save to session history
176
- st.session_state.chat_history.append({
177
- "question": user_input,
178
- "answer": response.text
179
- })
180
-
181
- except Exception as e:
182
- st.error(f"Error generating answer: {e}")
183
-
184
- else:
185
- st.warning("No valid documents or images processed.")
186
-
187
- if st.session_state.conversation:
188
- pdf_path = export_conversation_to_pdf(st.session_state.conversation)
189
- with open(pdf_path, "rb") as f:
190
- st.download_button(
191
- label="📥 Download Cleaned Conversation as PDF",
192
- data=f,
193
- file_name="clean_conversation.pdf",
194
- mime="application/pdf"
195
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
  if __name__ == "__main__":
198
- main()
 
84
  return pdf_path
85
 
86
  def main():
87
+ st.set_page_config(page_title="Gemini Chat QA", layout="wide")
88
+ st.title("📄 Chat with Your Document using Gemini (Sayandip+Dhiraj+Fazal)")
89
+
90
  if "conversation" not in st.session_state:
91
  st.session_state.conversation = []
92
  if "document_text" not in st.session_state:
93
  st.session_state.document_text = ""
94
  if "chat_active" not in st.session_state:
95
  st.session_state.chat_active = True
 
 
 
 
 
96
 
97
+ uploaded_file = st.file_uploader(
98
+ "Upload a file (.txt, .docx, .csv, .xlsx, .pptx, .pdf, .html, .htm, .tex, .jpg, .jpeg, .png):",
99
+ type=["txt", "docx", "csv", "xlsx", "pptx", "pdf", "html", "htm", "tex", "jpg", "jpeg", "png"]
 
100
  )
101
 
102
+ if uploaded_file and not st.session_state.document_text:
103
+ filetype = uploaded_file.name.split(".")[-1].lower()
104
+ try:
105
+ if filetype == "txt":
106
+ st.session_state.document_text = uploaded_file.read().decode("utf-8")
107
+ elif filetype == "docx":
108
+ st.session_state.document_text = extract_text_from_docx(uploaded_file)
109
+ elif filetype == "csv":
110
+ st.session_state.document_text = extract_text_from_csv(uploaded_file)
111
+ elif filetype == "xlsx":
112
+ st.session_state.document_text = extract_text_from_xlsx(uploaded_file)
113
+ elif filetype == "pptx":
114
+ st.session_state.document_text = extract_text_from_pptx(uploaded_file)
115
+ elif filetype == "pdf":
116
+ st.session_state.document_text = extract_text_from_pdf(uploaded_file)
117
+ elif filetype in ["html", "htm"]:
118
+ st.session_state.document_text = extract_text_from_html(uploaded_file)
119
+ elif filetype == "tex":
120
+ st.session_state.document_text = extract_text_from_tex(uploaded_file)
121
+ elif filetype in ["jpg", "jpeg", "png"]:
122
+ image_data = process_image(uploaded_file)
123
+ st.session_state.document_text = "Image uploaded and processed."
124
+ st.image(uploaded_file, caption=uploaded_file.name, use_container_width=True)
125
+ st.session_state.image_data = image_data # Store the image data for later use
126
+ else:
127
+ st.error("Unsupported file format.")
128
+ except Exception as e:
129
+ st.error(f"Failed to extract text: {e}")
130
+
131
+ if st.session_state.document_text:
132
+ st.markdown("### 💬 Conversation")
133
+ for user_q, gemini_a in st.session_state.conversation:
134
+ st.markdown(f"**You:** {user_q}")
135
+ st.markdown(f"**Gemini:**\\n\\n{gemini_a}")
136
+
137
+ if st.session_state.chat_active:
138
+ with st.form(key="chat_form", clear_on_submit=True):
139
+ user_input = st.text_input("Ask a question about the document (type 'exit' to stop):")
140
+ submit = st.form_submit_button("Send")
141
+
142
+ if submit and user_input:
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  if user_input.strip().lower() == "exit":
144
  st.session_state.chat_active = False
145
  st.success("Chat ended. Reload to start again.")
146
  else:
147
+ with st.spinner("Gemini is thinking..."):
148
+ content_blocks = []
149
+
150
+ # Add prior Q&A as part of the context
151
+ if st.session_state.conversation:
152
+ history_text = "\n\n".join(
153
+ f"Q: {entry[0]}\nA: {entry[1]}"
154
+ for entry in st.session_state.conversation
155
+ )
156
+ content_blocks.append({"text": f"Previous conversation:\n{history_text}"})
157
+
158
+ # Add file text content
159
+ if st.session_state.document_text.strip():
160
+ content_blocks.append({"text": f"Context:\n{st.session_state.document_text}"})
161
+
162
+ # Add image blocks (if image data exists)
163
+ if "image_data" in st.session_state:
164
+ content_blocks.append(st.session_state.image_data)
165
+
166
+ # Add current question
167
+ content_blocks.append({"text": f"Question: {user_input}"})
168
+
169
+ response = client.models.generate_content(
170
+ model="gemini-2.0-flash",
171
+ contents=content_blocks
172
+ )
173
+
174
+ st.session_state.conversation.append((user_input, response.text))
175
+ st.success("💡 Answer:")
176
+ st.write(response.text)
177
+
178
+ # Save to session history
179
+ st.session_state.chat_history.append({
180
+ "question": user_input,
181
+ "answer": response.text
182
+ })
183
+
184
+ if st.session_state.conversation:
185
+ pdf_path = export_conversation_to_pdf(st.session_state.conversation)
186
+ with open(pdf_path, "rb") as f:
187
+ st.download_button(
188
+ label="📥 Download Cleaned Conversation as PDF",
189
+ data=f,
190
+ file_name="clean_conversation.pdf",
191
+ mime="application/pdf"
192
+ )
193
 
194
  if __name__ == "__main__":
195
+ main()