DrishtiSharma commited on
Commit
32575e3
·
verified ·
1 Parent(s): e49cf2a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -8
app.py CHANGED
@@ -1,15 +1,29 @@
1
  import streamlit as st
2
  import os
 
 
 
 
 
 
 
 
 
 
 
3
  from datetime import datetime
4
  from pydub import AudioSegment
5
- import tempfile
6
  import pytz
7
- from openai import OpenAI
8
  from langchain.chains import ConversationalRetrievalChain
9
  from langchain.text_splitter import RecursiveCharacterTextSplitter
10
  from langchain_openai import ChatOpenAI, OpenAIEmbeddings
11
  from langchain_community.vectorstores import Chroma
12
  from langchain_community.document_loaders import PyPDFLoader, TextLoader, CSVLoader
 
 
 
 
13
 
14
 
15
  class DocumentRAG:
@@ -39,10 +53,12 @@ class DocumentRAG:
39
  try:
40
  documents = []
41
  for uploaded_file in uploaded_files:
 
42
  temp_file_path = tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]).name
43
  with open(temp_file_path, "wb") as temp_file:
44
  temp_file.write(uploaded_file.read())
45
 
 
46
  if temp_file_path.endswith('.pdf'):
47
  loader = PyPDFLoader(temp_file_path)
48
  elif temp_file_path.endswith('.txt'):
@@ -52,6 +68,7 @@ class DocumentRAG:
52
  else:
53
  return f"Unsupported file type: {uploaded_file.name}"
54
 
 
55
  try:
56
  documents.extend(loader.load())
57
  except Exception as e:
@@ -60,6 +77,7 @@ class DocumentRAG:
60
  if not documents:
61
  return "No valid documents were processed. Please check your files."
62
 
 
63
  text_splitter = RecursiveCharacterTextSplitter(
64
  chunk_size=1000,
65
  chunk_overlap=200,
@@ -67,14 +85,16 @@ class DocumentRAG:
67
  )
68
  documents = text_splitter.split_documents(documents)
69
 
 
70
  combined_text = " ".join([doc.page_content for doc in documents])
71
  self.document_summary = self.generate_summary(combined_text)
72
 
 
73
  embeddings = OpenAIEmbeddings(api_key=self.api_key)
74
  self.document_store = Chroma.from_documents(
75
  documents,
76
  embeddings,
77
- persist_directory=self.chroma_persist_dir
78
  )
79
 
80
  self.qa_chain = ConversationalRetrievalChain.from_llm(
@@ -117,6 +137,8 @@ class DocumentRAG:
117
 
118
  try:
119
  client = OpenAI(api_key=self.api_key)
 
 
120
  script_response = client.chat.completions.create(
121
  model="gpt-4",
122
  messages=[
@@ -135,6 +157,7 @@ class DocumentRAG:
135
  if not script:
136
  return "Error: Failed to generate podcast script.", None
137
 
 
138
  final_audio = AudioSegment.empty()
139
  is_first_speaker = True
140
 
@@ -178,6 +201,47 @@ class DocumentRAG:
178
  except Exception as e:
179
  return f"Error generating podcast: {str(e)}", None
180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
  # Initialize RAG system in session state
183
  if "rag_system" not in st.session_state:
@@ -194,27 +258,56 @@ with st.sidebar:
194
  )
195
  st.markdown("### Steps:")
196
  st.markdown("1. Upload documents.")
197
- st.markdown("2. Generate summaries.")
198
  st.markdown("3. Ask questions.")
199
  st.markdown("4. Create podcasts.")
200
 
201
- # Main App
202
  st.title("Document Analyzer and Podcast Generator")
203
 
 
 
 
 
 
 
204
  uploaded_files = st.file_uploader("Upload files (PDF, TXT, CSV)", accept_multiple_files=True)
205
 
206
  if st.button("Process Documents"):
207
  if uploaded_files:
 
208
  result = st.session_state.rag_system.process_documents(uploaded_files)
209
- st.success(result) if "successfully" in result else st.error(result)
 
 
 
210
  else:
211
  st.warning("No files uploaded.")
212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  if st.session_state.rag_system.document_summary:
214
- st.subheader("Step 2: Generate Podcast")
215
  if st.button("Generate Podcast"):
216
  script, audio_path = st.session_state.rag_system.create_podcast()
217
  if audio_path:
218
  st.text_area("Generated Podcast Script", script, height=200)
219
  st.audio(audio_path, format="audio/mp3")
220
- st.success("Podcast generated successfully!")
 
 
 
 
 
1
  import streamlit as st
2
  import os
3
+ from openai import OpenAI
4
+ import tempfile
5
+ from langchain.chains import ConversationalRetrievalChain
6
+ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import Chroma
9
+ from langchain_community.document_loaders import (
10
+ PyPDFLoader,
11
+ TextLoader,
12
+ CSVLoader
13
+ )
14
  from datetime import datetime
15
  from pydub import AudioSegment
 
16
  import pytz
17
+
18
  from langchain.chains import ConversationalRetrievalChain
19
  from langchain.text_splitter import RecursiveCharacterTextSplitter
20
  from langchain_openai import ChatOpenAI, OpenAIEmbeddings
21
  from langchain_community.vectorstores import Chroma
22
  from langchain_community.document_loaders import PyPDFLoader, TextLoader, CSVLoader
23
+ import os
24
+ import tempfile
25
+ from datetime import datetime
26
+ import pytz
27
 
28
 
29
  class DocumentRAG:
 
53
  try:
54
  documents = []
55
  for uploaded_file in uploaded_files:
56
+ # Save uploaded file to a temporary location
57
  temp_file_path = tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]).name
58
  with open(temp_file_path, "wb") as temp_file:
59
  temp_file.write(uploaded_file.read())
60
 
61
+ # Determine the loader based on the file type
62
  if temp_file_path.endswith('.pdf'):
63
  loader = PyPDFLoader(temp_file_path)
64
  elif temp_file_path.endswith('.txt'):
 
68
  else:
69
  return f"Unsupported file type: {uploaded_file.name}"
70
 
71
+ # Load the documents
72
  try:
73
  documents.extend(loader.load())
74
  except Exception as e:
 
77
  if not documents:
78
  return "No valid documents were processed. Please check your files."
79
 
80
+ # Split text for better processing
81
  text_splitter = RecursiveCharacterTextSplitter(
82
  chunk_size=1000,
83
  chunk_overlap=200,
 
85
  )
86
  documents = text_splitter.split_documents(documents)
87
 
88
+ # Combine text for summary
89
  combined_text = " ".join([doc.page_content for doc in documents])
90
  self.document_summary = self.generate_summary(combined_text)
91
 
92
+ # Create embeddings and initialize retrieval chain
93
  embeddings = OpenAIEmbeddings(api_key=self.api_key)
94
  self.document_store = Chroma.from_documents(
95
  documents,
96
  embeddings,
97
+ persist_directory=self.chroma_persist_dir # Persistent directory for Chroma
98
  )
99
 
100
  self.qa_chain = ConversationalRetrievalChain.from_llm(
 
137
 
138
  try:
139
  client = OpenAI(api_key=self.api_key)
140
+
141
+ # Generate podcast script
142
  script_response = client.chat.completions.create(
143
  model="gpt-4",
144
  messages=[
 
157
  if not script:
158
  return "Error: Failed to generate podcast script.", None
159
 
160
+ # Convert script to audio
161
  final_audio = AudioSegment.empty()
162
  is_first_speaker = True
163
 
 
201
  except Exception as e:
202
  return f"Error generating podcast: {str(e)}", None
203
 
204
+ def generate_summary(self, text):
205
+ """Generate a summary of the provided text."""
206
+ if not self.api_key:
207
+ return "API Key not set. Please set it in the environment variables."
208
+ try:
209
+ client = OpenAI(api_key=self.api_key)
210
+ response = client.chat.completions.create(
211
+ model="gpt-4",
212
+ messages=[
213
+ {"role": "system", "content": "Summarize the document content concisely and provide 3-5 key points for discussion."},
214
+ {"role": "user", "content": text[:4000]}
215
+ ],
216
+ temperature=0.3
217
+ )
218
+ return response.choices[0].message.content
219
+ except Exception as e:
220
+ return f"Error generating summary: {str(e)}"
221
+
222
+ def handle_query(self, question, history):
223
+ """Handle user queries."""
224
+ if not self.qa_chain:
225
+ return history + [("System", "Please process the documents first.")]
226
+ try:
227
+ preface = """
228
+ Instruction: Respond in English. Be professional and concise, keeping the response under 300 words.
229
+ If you cannot provide an answer, say: "I am not sure about this question. Please try asking something else."
230
+ """
231
+ query = f"{preface}\nQuery: {question}"
232
+
233
+ result = self.qa_chain({
234
+ "question": query,
235
+ "chat_history": [(q, a) for q, a in history]
236
+ })
237
+
238
+ if "answer" not in result:
239
+ return history + [("System", "Sorry, an error occurred.")]
240
+
241
+ history.append((question, result["answer"]))
242
+ return history
243
+ except Exception as e:
244
+ return history + [("System", f"Error: {str(e)}")]
245
 
246
  # Initialize RAG system in session state
247
  if "rag_system" not in st.session_state:
 
258
  )
259
  st.markdown("### Steps:")
260
  st.markdown("1. Upload documents.")
261
+ #st.markdown("2. Generate summaries.")
262
  st.markdown("3. Ask questions.")
263
  st.markdown("4. Create podcasts.")
264
 
265
+ # Streamlit UI
266
  st.title("Document Analyzer and Podcast Generator")
267
 
268
+ # Fetch the API key status
269
+ if "OPENAI_API_KEY" not in os.environ or not os.getenv("OPENAI_API_KEY"):
270
+ st.error("The 'OPENAI_API_KEY' environment variable is not set. Please configure it in your hosting environment.")
271
+
272
+ # File upload
273
+ st.subheader("Step 1: Upload Documents")
274
  uploaded_files = st.file_uploader("Upload files (PDF, TXT, CSV)", accept_multiple_files=True)
275
 
276
  if st.button("Process Documents"):
277
  if uploaded_files:
278
+ # Process the uploaded files
279
  result = st.session_state.rag_system.process_documents(uploaded_files)
280
+ if "successfully" in result:
281
+ st.success(result)
282
+ else:
283
+ st.error(result)
284
  else:
285
  st.warning("No files uploaded.")
286
 
287
+ # Document Q&A
288
+ st.subheader("Step 2: Ask Questions")
289
+ if st.session_state.rag_system.qa_chain:
290
+ history = []
291
+ user_question = st.text_input("Ask a question:")
292
+ if st.button("Submit Question"):
293
+ # Handle the user query
294
+ history = st.session_state.rag_system.handle_query(user_question, history)
295
+ for question, answer in history:
296
+ st.chat_message("user").write(question)
297
+ st.chat_message("assistant").write(answer)
298
+ else:
299
+ st.info("Please process documents before asking questions.")
300
+
301
+ # Podcast Generation
302
+ st.subheader("Step 3: Generate Podcast")
303
  if st.session_state.rag_system.document_summary:
 
304
  if st.button("Generate Podcast"):
305
  script, audio_path = st.session_state.rag_system.create_podcast()
306
  if audio_path:
307
  st.text_area("Generated Podcast Script", script, height=200)
308
  st.audio(audio_path, format="audio/mp3")
309
+ st.success("Podcast generated successfully! You can listen to it above.")
310
+ else:
311
+ st.error(script)
312
+ else:
313
+ st.info("Please process documents to generate a podcast.")