poemsforaphrodite commited on
Commit
68c6779
1 Parent(s): 643cfc9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +252 -0
app.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from openai import OpenAI
4
+ from PyPDF2 import PdfReader
5
+ import requests
6
+ from youtube_transcript_api import YouTubeTranscriptApi, NoTranscriptFound
7
+ from urllib.parse import urlparse, parse_qs
8
+ from pinecone import Pinecone
9
+ import uuid
10
+ from dotenv import load_dotenv
11
+ import time
12
+ from concurrent.futures import ThreadPoolExecutor, as_completed
13
+ from itertools import islice
14
+
15
+ load_dotenv()
16
+
17
+ # Set up OpenAI client
18
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
19
+
20
+ # Set up Pinecone
21
+ pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))
22
+
23
+ # Get index name and URL from .env
24
+ index_name = os.getenv("PINECONE_INDEX_NAME")
25
+ index_url = os.getenv("PINECONE_INDEX_URL")
26
+
27
+ index = pc.Index(index_name, url=index_url)
28
+
29
+ def get_embedding(text):
30
+ response = client.embeddings.create(input=text, model="text-embedding-3-large")
31
+ return response.data[0].embedding
32
+
33
+ def chunk_text(text, content_type):
34
+ if content_type == "YouTube":
35
+ return [text] # Return the entire text as a single chunk for YouTube
36
+ else: # Default for PDF and Web Link
37
+ chunk_size = 2000
38
+ content_length = len(text)
39
+ return [text[i:i+chunk_size] for i in range(0, content_length, chunk_size)]
40
+
41
+ def process_pdf(file):
42
+ reader = PdfReader(file)
43
+ text = ""
44
+ for page in reader.pages:
45
+ text += page.extract_text() + "\n"
46
+ return chunk_text(text, "PDF")
47
+
48
+ def process_web_link(url):
49
+ response = requests.get(url)
50
+ return chunk_text(response.text, "Web")
51
+
52
+ def process_youtube_link(url):
53
+ try:
54
+ video_id = extract_video_id(url)
55
+ transcript = YouTubeTranscriptApi.get_transcript(video_id)
56
+ full_text = " ".join([entry['text'] for entry in transcript])
57
+ print("Transcript obtained from YouTube API")
58
+ return [full_text] # Return the full text as a single chunk
59
+ except NoTranscriptFound:
60
+ print("No transcript found for this YouTube video.")
61
+ return []
62
+
63
+ def extract_video_id(url):
64
+ parsed_url = urlparse(url)
65
+ if parsed_url.hostname == 'youtu.be':
66
+ return parsed_url.path[1:]
67
+ if parsed_url.hostname in ('www.youtube.com', 'youtube.com'):
68
+ if parsed_url.path == '/watch':
69
+ return parse_qs(parsed_url.query)['v'][0]
70
+ if parsed_url.path[:7] == '/embed/':
71
+ return parsed_url.path.split('/')[2]
72
+ if parsed_url.path[:3] == '/v/':
73
+ return parsed_url.path.split('/')[2]
74
+ return None
75
+
76
+ def process_upload(upload_type, file_or_link, file_name=None):
77
+ print(f"Starting process_upload for {upload_type}")
78
+ doc_id = str(uuid.uuid4())
79
+ print(f"Generated doc_id: {doc_id}")
80
+
81
+ if upload_type == "PDF":
82
+ chunks = process_pdf(file_or_link)
83
+ doc_name = file_name or "Uploaded PDF"
84
+ elif upload_type == "Web Link":
85
+ chunks = process_web_link(file_or_link)
86
+ doc_name = file_or_link
87
+ elif upload_type == "YouTube Link":
88
+ chunks = process_youtube_link(file_or_link)
89
+ doc_name = f"YouTube: {file_or_link}"
90
+ else:
91
+ print("Invalid upload type")
92
+ return "Invalid upload type"
93
+
94
+ vectors = []
95
+ with ThreadPoolExecutor() as executor:
96
+ futures = [executor.submit(process_chunk, chunk, doc_id, i, upload_type, doc_name) for i, chunk in enumerate(chunks)]
97
+
98
+ for future in as_completed(futures):
99
+ vectors.append(future.result())
100
+ # Update progress
101
+ progress = len(vectors) / len(chunks)
102
+ st.session_state.upload_progress.progress(progress)
103
+
104
+ print(f"Generated {len(vectors)} vectors")
105
+
106
+ # Upsert vectors in batches
107
+ batch_size = 100 # Adjust this value as needed
108
+ for i in range(0, len(vectors), batch_size):
109
+ batch = list(islice(vectors, i, i + batch_size))
110
+ index.upsert(vectors=batch)
111
+ print(f"Upserted batch {i//batch_size + 1} of {len(vectors)//batch_size + 1}")
112
+
113
+ print("All vectors upserted to Pinecone")
114
+
115
+ return f"Processing complete for {upload_type}. Document Name: {doc_name}"
116
+
117
+ def process_chunk(chunk, doc_id, i, upload_type, doc_name):
118
+ embedding = get_embedding(chunk)
119
+ return (f"{doc_id}_{i}", embedding, {
120
+ "text": chunk,
121
+ "type": upload_type,
122
+ "doc_id": doc_id,
123
+ "doc_name": doc_name,
124
+ "chunk_index": i
125
+ })
126
+
127
+ def get_relevant_context(query, top_k=5):
128
+ print(f"Getting relevant context for query: {query}")
129
+ query_embedding = get_embedding(query)
130
+
131
+ search_results = index.query(vector=query_embedding, top_k=top_k, include_metadata=True)
132
+ print(f"Found {len(search_results['matches'])} relevant results")
133
+
134
+ # Sort results by similarity score (higher is better)
135
+ sorted_results = sorted(search_results['matches'], key=lambda x: x['score'], reverse=True)
136
+
137
+ context = "\n".join([result['metadata']['text'] for result in sorted_results])
138
+ return context, sorted_results
139
+
140
+ def chat_with_ai(message):
141
+ print(f"Chatting with AI, message: {message}")
142
+ context, results = get_relevant_context(message)
143
+ print(f"Retrieved context, length: {len(context)}")
144
+
145
+ messages = [
146
+ {"role": "system", "content": "You are a helpful assistant. Use the following information to answer the user's question, but don't mention the context directly in your response. If the information isn't in the context, say you don't know."},
147
+ {"role": "system", "content": f"Context: {context}"},
148
+ {"role": "user", "content": message}
149
+ ]
150
+
151
+ response = client.chat.completions.create(
152
+ model="gpt-4o-mini",
153
+ messages=messages
154
+ )
155
+ print("Received response from OpenAI")
156
+
157
+ ai_response = response.choices[0].message.content
158
+
159
+ # Prepare source information
160
+ sources = [
161
+ {
162
+ "doc_id": result['metadata']['doc_id'],
163
+ "doc_name": result['metadata']['doc_name'],
164
+ "chunk_index": result['metadata']['chunk_index'],
165
+ "text": result['metadata']['text'],
166
+ "type": result['metadata']['type'],
167
+ "score": result['score']
168
+ }
169
+ for result in results
170
+ ]
171
+
172
+ return ai_response, sources
173
+
174
+ def clear_database():
175
+ print("Clearing database...")
176
+ index.delete(delete_all=True)
177
+ print("Database cleared")
178
+ return "Database cleared successfully."
179
+
180
+ # Streamlit UI
181
+ st.set_page_config(layout="wide")
182
+ st.title("Upload and Chat with PDFs, Web Links, and YouTube Videos")
183
+
184
+ # Create three columns
185
+ col1, col2, col3 = st.columns([1, 1, 1])
186
+
187
+ with col1:
188
+ st.header("Upload")
189
+
190
+ # PDF upload
191
+ uploaded_files = st.file_uploader("Choose one or more PDF files", type="pdf", accept_multiple_files=True)
192
+
193
+ # Web Link input
194
+ web_link = st.text_input("Enter a Web Link")
195
+
196
+ # YouTube Link input
197
+ youtube_link = st.text_input("Enter a YouTube Link")
198
+
199
+ if st.button("Process All"):
200
+ st.session_state.upload_progress = st.progress(0)
201
+ with st.spinner("Processing uploads..."):
202
+ results = []
203
+ if uploaded_files:
204
+ for file in uploaded_files:
205
+ pdf_result = process_upload("PDF", file, file.name)
206
+ results.append(pdf_result)
207
+ if web_link:
208
+ web_result = process_upload("Web Link", web_link)
209
+ results.append(web_result)
210
+ if youtube_link:
211
+ youtube_result = process_upload("YouTube Link", youtube_link)
212
+ results.append(youtube_result)
213
+
214
+ if results:
215
+ for result in results:
216
+ st.success(result)
217
+ else:
218
+ st.warning("No content uploaded. Please provide at least one input.")
219
+ st.session_state.upload_progress.empty()
220
+
221
+ if st.button("Clear Database"):
222
+ result = clear_database()
223
+ st.success(result)
224
+
225
+ with col2:
226
+ st.header("Chat")
227
+ user_input = st.text_input("Ask a question about the uploaded content:")
228
+ if st.button("Send"):
229
+ if user_input:
230
+ print(f"Sending user input: {user_input}")
231
+ st.session_state.chat_progress = st.progress(0)
232
+ response, sources = chat_with_ai(user_input)
233
+ st.session_state.chat_progress.progress(1.0)
234
+ st.markdown("**You:** " + user_input)
235
+ st.markdown("**AI:** " + response)
236
+
237
+ # Store sources in session state for display in col3
238
+ st.session_state.sources = sources
239
+ st.session_state.chat_progress.empty()
240
+ else:
241
+ print("Empty user input")
242
+ st.warning("Please enter a question.")
243
+
244
+ with col3:
245
+ st.header("Source Chunks")
246
+ if 'sources' in st.session_state and st.session_state.sources:
247
+ for i, source in enumerate(st.session_state.sources, 1):
248
+ with st.expander(f"Source {i} - {source['type']} ({source['doc_name']}) - Score: {source['score']}"):
249
+ st.markdown(f"**Chunk Index:** {source['chunk_index']}")
250
+ st.text(source['text'])
251
+ else:
252
+ st.info("Ask a question to see source chunks here.")