Sayandip commited on
Commit
739715e
·
verified ·
1 Parent(s): abfb305

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -91
app.py CHANGED
@@ -94,102 +94,102 @@ def main():
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()
 
94
  if "chat_active" not in st.session_state:
95
  st.session_state.chat_active = True
96
 
97
+ uploaded_files = st.file_uploader(
98
+ "Upload one or more documents or images",
99
+ type=["docx", "xlsx", "pdf", "csv", "txt", "pptx", "tex", "html", "htm", "jpg", "jpeg", "png"],
100
+ accept_multiple_files=True
101
  )
102
 
103
+ if uploaded_files:
104
+ combined_context = ""
105
+ image_contents = []
106
+
107
+ for uploaded_file in uploaded_files:
108
+ file_ext = uploaded_file.name.split('.')[-1].lower()
109
+
110
+ try:
111
+ if file_ext == "txt":
112
+ combined_context += uploaded_file.read().decode("utf-8")
113
+ elif file_ext == "docx":
114
+ combined_context += extract_text_from_docx(uploaded_file)
115
+ elif file_ext == "csv":
116
+ combined_context += extract_text_from_csv(uploaded_file)
117
+ elif file_ext == "xlsx":
118
+ combined_context += extract_text_from_xlsx(uploaded_file)
119
+ elif file_ext == "pptx":
120
+ combined_context += extract_text_from_pptx(uploaded_file)
121
+ elif file_ext == "pdf":
122
+ combined_context += extract_text_from_pdf(uploaded_file)
123
+ elif file_ext in ["html", "htm"]:
124
+ combined_context += extract_text_from_html(uploaded_file)
125
+ elif file_ext == "tex":
126
+ combined_context += extract_text_from_tex(uploaded_file)
127
+ elif file_ext in ["jpg", "jpeg", "png"]:
128
+ image_data = process_image(uploaded_file)
129
+ image_contents.append(image_data)
130
+ st.image(uploaded_file, caption=uploaded_file.name, use_container_width=True)
131
+
132
+ except Exception as e:
133
+ st.error(f"Error processing {uploaded_file.name}: {e}")
134
+
135
+ if combined_context.strip() or image_contents:
136
+ with st.spinner("Generating answer..."):
137
+ try:
138
+ content_blocks = []
139
+
140
+ # Add prior Q&A as part of the context
141
+ if st.session_state.conversation:
142
+ history_text = "\n\n".join(
143
+ f"Q: {entry[0]}\nA: {entry[1]}"
144
+ for entry in st.session_state.conversation
145
+ )
146
+ content_blocks.append({"text": f"Previous conversation:\n{history_text}"})
147
+
148
+ # Add file text content
149
+ if combined_context.strip():
150
+ content_blocks.append({"text": f"Context:\n{combined_context}"})
151
+
152
+ # Add image blocks
153
+ content_blocks.extend(image_contents)
154
+
155
+ # Add current question
156
+ user_input = st.text_input("Ask a question about the documents (type 'exit' to stop):")
157
  if user_input.strip().lower() == "exit":
158
  st.session_state.chat_active = False
159
  st.success("Chat ended. Reload to start again.")
160
  else:
161
+ content_blocks.append({"text": f"Question: {user_input}"})
162
+
163
+ response = client.models.generate_content(
164
+ model="gemini-2.0-flash",
165
+ contents=content_blocks
166
+ )
167
+
168
+ st.session_state.conversation.append((user_input, response.text))
169
+ st.success("💡 Answer:")
170
+ st.write(response.text)
171
+
172
+ # Save to session history
173
+ st.session_state.chat_history.append({
174
+ "question": user_input,
175
+ "answer": response.text
176
+ })
177
+
178
+ except Exception as e:
179
+ st.error(f"Error generating answer: {e}")
180
+
181
+ else:
182
+ st.warning("No valid documents or images processed.")
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="Conversation.pdf",
191
+ mime="application/pdf"
192
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
  if __name__ == "__main__":
195
+ main()