Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,29 +1,15 @@
|
|
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,12 +39,10 @@ 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,7 +52,6 @@ class DocumentRAG:
|
|
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,7 +60,6 @@ class DocumentRAG:
|
|
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,16 +67,14 @@ class DocumentRAG:
|
|
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
|
98 |
)
|
99 |
|
100 |
self.qa_chain = ConversationalRetrievalChain.from_llm(
|
@@ -137,8 +117,6 @@ class DocumentRAG:
|
|
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,7 +135,6 @@ class DocumentRAG:
|
|
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,98 +178,43 @@ class DocumentRAG:
|
|
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:
|
248 |
st.session_state.rag_system = DocumentRAG()
|
249 |
|
250 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
251 |
st.title("Document Analyzer and Podcast Generator")
|
252 |
|
253 |
-
# Fetch the API key status
|
254 |
-
if "OPENAI_API_KEY" not in os.environ or not os.getenv("OPENAI_API_KEY"):
|
255 |
-
st.error("The 'OPENAI_API_KEY' environment variable is not set. Please configure it in your hosting environment.")
|
256 |
-
|
257 |
-
# File upload
|
258 |
-
st.subheader("Step 1: Upload Documents")
|
259 |
uploaded_files = st.file_uploader("Upload files (PDF, TXT, CSV)", accept_multiple_files=True)
|
260 |
|
261 |
if st.button("Process Documents"):
|
262 |
if uploaded_files:
|
263 |
-
# Process the uploaded files
|
264 |
result = st.session_state.rag_system.process_documents(uploaded_files)
|
265 |
-
if "successfully" in result
|
266 |
-
st.success(result)
|
267 |
-
else:
|
268 |
-
st.error(result)
|
269 |
else:
|
270 |
st.warning("No files uploaded.")
|
271 |
|
272 |
-
# Document Q&A
|
273 |
-
st.subheader("Step 2: Ask Questions")
|
274 |
-
if st.session_state.rag_system.qa_chain:
|
275 |
-
history = []
|
276 |
-
user_question = st.text_input("Ask a question:")
|
277 |
-
if st.button("Submit Question"):
|
278 |
-
# Handle the user query
|
279 |
-
history = st.session_state.rag_system.handle_query(user_question, history)
|
280 |
-
for question, answer in history:
|
281 |
-
st.chat_message("user").write(question)
|
282 |
-
st.chat_message("assistant").write(answer)
|
283 |
-
else:
|
284 |
-
st.info("Please process documents before asking questions.")
|
285 |
-
|
286 |
-
# Podcast Generation
|
287 |
-
st.subheader("Step 3: Generate Podcast")
|
288 |
if st.session_state.rag_system.document_summary:
|
|
|
289 |
if st.button("Generate Podcast"):
|
290 |
script, audio_path = st.session_state.rag_system.create_podcast()
|
291 |
if audio_path:
|
292 |
st.text_area("Generated Podcast Script", script, height=200)
|
293 |
st.audio(audio_path, format="audio/mp3")
|
294 |
-
st.success("Podcast generated successfully!
|
295 |
-
else:
|
296 |
-
st.error(script)
|
297 |
-
else:
|
298 |
-
st.info("Please process documents to generate a podcast.")
|
|
|
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 |
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 |
else:
|
53 |
return f"Unsupported file type: {uploaded_file.name}"
|
54 |
|
|
|
55 |
try:
|
56 |
documents.extend(loader.load())
|
57 |
except Exception as e:
|
|
|
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 |
)
|
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 |
|
118 |
try:
|
119 |
client = OpenAI(api_key=self.api_key)
|
|
|
|
|
120 |
script_response = client.chat.completions.create(
|
121 |
model="gpt-4",
|
122 |
messages=[
|
|
|
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 |
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:
|
184 |
st.session_state.rag_system = DocumentRAG()
|
185 |
|
186 |
+
# Sidebar
|
187 |
+
with st.sidebar:
|
188 |
+
st.title("About")
|
189 |
+
st.markdown(
|
190 |
+
"""
|
191 |
+
This app is inspired by the [RAG_HW HuggingFace Space](https://huggingface.co/spaces/wint543/RAG_HW).
|
192 |
+
It allows users to upload documents, generate summaries, ask questions, and create podcasts.
|
193 |
+
"""
|
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!")
|
|
|
|
|
|
|
|