Spaces:
Sleeping
Sleeping
add app.py file
Browse files
app.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import requests
|
| 5 |
+
import torch
|
| 6 |
+
from tqdm.auto import tqdm
|
| 7 |
+
from transformers import BertModel, BertTokenizer
|
| 8 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 9 |
+
|
| 10 |
+
# CourseFAQBot class
|
| 11 |
+
class CourseFAQBot:
|
| 12 |
+
def __init__(self, model_name="bert-base-uncased", docs_url=None, batch_size=8):
|
| 13 |
+
self.tokenizer = BertTokenizer.from_pretrained(model_name)
|
| 14 |
+
self.model = BertModel.from_pretrained(model_name)
|
| 15 |
+
self.model.eval() # Set the model to evaluation mode if not training
|
| 16 |
+
self.batch_size = batch_size
|
| 17 |
+
self.df = self._download_and_process_documents(docs_url)
|
| 18 |
+
self.document_embeddings = self.compute_embeddings(self.df['text'].tolist())
|
| 19 |
+
|
| 20 |
+
def _download_and_process_documents(self, docs_url):
|
| 21 |
+
"""
|
| 22 |
+
Download and process the document data.
|
| 23 |
+
"""
|
| 24 |
+
docs_response = requests.get(docs_url)
|
| 25 |
+
documents_raw = docs_response.json()
|
| 26 |
+
|
| 27 |
+
documents = []
|
| 28 |
+
for course in documents_raw:
|
| 29 |
+
course_name = course['course']
|
| 30 |
+
for doc in course['documents']:
|
| 31 |
+
doc['course'] = course_name
|
| 32 |
+
documents.append(doc)
|
| 33 |
+
|
| 34 |
+
# Create the DataFrame
|
| 35 |
+
return pd.DataFrame(documents, columns=['course', 'section', 'question', 'text'])
|
| 36 |
+
|
| 37 |
+
def make_batches(self, seq, n):
|
| 38 |
+
"""
|
| 39 |
+
Split a sequence into batches of size n.
|
| 40 |
+
"""
|
| 41 |
+
result = []
|
| 42 |
+
for i in range(0, len(seq), n):
|
| 43 |
+
batch = seq[i:i+n]
|
| 44 |
+
result.append(batch)
|
| 45 |
+
return result
|
| 46 |
+
|
| 47 |
+
def compute_embeddings(self, texts):
|
| 48 |
+
"""
|
| 49 |
+
Compute embeddings for a list of texts using a pre-trained transformer model.
|
| 50 |
+
"""
|
| 51 |
+
text_batches = self.make_batches(texts, self.batch_size)
|
| 52 |
+
all_embeddings = []
|
| 53 |
+
|
| 54 |
+
for batch in tqdm(text_batches, desc="Computing embeddings"):
|
| 55 |
+
encoded_input = self.tokenizer(batch, padding=True, truncation=True, return_tensors='pt')
|
| 56 |
+
with torch.no_grad():
|
| 57 |
+
outputs = self.model(**encoded_input)
|
| 58 |
+
hidden_states = outputs.last_hidden_state
|
| 59 |
+
batch_embeddings = hidden_states.mean(dim=1)
|
| 60 |
+
batch_embeddings_np = batch_embeddings.cpu().numpy()
|
| 61 |
+
all_embeddings.append(batch_embeddings_np)
|
| 62 |
+
|
| 63 |
+
final_embeddings = np.vstack(all_embeddings)
|
| 64 |
+
return final_embeddings
|
| 65 |
+
|
| 66 |
+
def query(self, query_text, top_n=10):
|
| 67 |
+
"""
|
| 68 |
+
Perform a query to find the most relevant documents.
|
| 69 |
+
"""
|
| 70 |
+
query_embedding = self.compute_embeddings([query_text])
|
| 71 |
+
similarities = cosine_similarity(query_embedding, self.document_embeddings).flatten()
|
| 72 |
+
top_n_indices = similarities.argsort()[-top_n:][::-1]
|
| 73 |
+
top_n_documents = self.df.iloc[top_n_indices]
|
| 74 |
+
return top_n_documents
|
| 75 |
+
|
| 76 |
+
# Streamlit application
|
| 77 |
+
st.title("FAQ Search Engine for DataTalks")
|
| 78 |
+
|
| 79 |
+
# Initialize CourseFAQBot
|
| 80 |
+
docs_url = 'https://github.com/alexeygrigorev/llm-rag-workshop/raw/main/notebooks/documents.json'
|
| 81 |
+
faq_bot = CourseFAQBot(docs_url=docs_url)
|
| 82 |
+
|
| 83 |
+
# Input fields for query and filters
|
| 84 |
+
query = st.text_input("Enter your query:")
|
| 85 |
+
courses = st.multiselect("Select course(s):", options=faq_bot.df['course'].unique())
|
| 86 |
+
|
| 87 |
+
# Search button
|
| 88 |
+
if st.button("Search"):
|
| 89 |
+
results = faq_bot.query(query)
|
| 90 |
+
|
| 91 |
+
# Filter results by selected courses if any
|
| 92 |
+
if courses:
|
| 93 |
+
results = results[results['course'].isin(courses)]
|
| 94 |
+
|
| 95 |
+
# Display results with space in between
|
| 96 |
+
for i, result in enumerate(results.to_dict(orient='records')):
|
| 97 |
+
st.write(f"### Result {i+1}")
|
| 98 |
+
st.write(f"**Course**: {result['course']}")
|
| 99 |
+
st.write(f"**Section**: {result['section']}")
|
| 100 |
+
st.write(f"**Question**: {result['question']}")
|
| 101 |
+
st.write(f"**Text**: {result['text']}")
|
| 102 |
+
st.write("") # Adds a blank space between results
|
| 103 |
+
st.markdown("---")
|