Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -3,67 +3,38 @@ import pandas as pd
|
|
3 |
import numpy as np
|
4 |
from transformers import pipeline, BertTokenizer, BertModel
|
5 |
import faiss
|
6 |
-
import torch
|
7 |
-
import json
|
8 |
-
import spaces
|
9 |
|
10 |
# Load CSV data
|
11 |
-
data = pd.read_csv('
|
12 |
|
13 |
-
#
|
14 |
-
|
15 |
-
try:
|
16 |
-
return np.array(json.loads(x), dtype=np.float32) # Ensure the array is of type float32
|
17 |
-
except json.JSONDecodeError as e:
|
18 |
-
print(f"Error decoding JSON: {e}")
|
19 |
-
return np.array([], dtype=np.float32) # Return an empty array or handle it as appropriate
|
20 |
-
|
21 |
-
# Apply the safe_json_loads function to the embedding column
|
22 |
-
data['embedding'] = data['embedding'].apply(safe_json_loads)
|
23 |
-
|
24 |
-
# Filter out any rows with empty embeddings
|
25 |
-
data = data[data['embedding'].apply(lambda x: x.size > 0)]
|
26 |
|
27 |
# Initialize FAISS index
|
28 |
-
dimension = len(data['
|
29 |
-
|
30 |
-
|
31 |
-
# Create FAISS index
|
32 |
-
if faiss.get_num_gpus() > 0:
|
33 |
-
gpu_index = faiss.IndexFlatL2(dimension)
|
34 |
-
gpu_index = faiss.index_cpu_to_gpu(res, 0, gpu_index) # move to GPU
|
35 |
-
else:
|
36 |
-
gpu_index = faiss.IndexFlatL2(dimension) # fall back to CPU
|
37 |
-
|
38 |
-
# Ensure embeddings are stacked as float32
|
39 |
-
embeddings = np.vstack(data['embedding'].values).astype(np.float32)
|
40 |
-
gpu_index.add(embeddings)
|
41 |
-
|
42 |
-
# Check if GPU is available
|
43 |
-
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
44 |
|
45 |
# Load QA model
|
46 |
-
qa_model = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad"
|
47 |
-
|
48 |
-
# Load BERT model and tokenizer
|
49 |
-
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
50 |
-
model = BertModel.from_pretrained('bert-base-uncased').to(device)
|
51 |
|
52 |
# Function to embed the question using BERT
|
53 |
def embed_question(question, model, tokenizer):
|
54 |
-
inputs = tokenizer(question, return_tensors='pt')
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
58 |
|
59 |
# Function to retrieve the relevant document and generate a response
|
60 |
-
@spaces.GPU(duration=120)
|
61 |
def retrieve_and_generate(question):
|
62 |
# Embed the question
|
63 |
question_embedding = embed_question(question, model, tokenizer)
|
64 |
|
65 |
# Search in FAISS index
|
66 |
-
_, indices =
|
67 |
|
68 |
# Retrieve the most relevant document
|
69 |
relevant_doc = data.iloc[indices[0][0]]
|
@@ -77,7 +48,7 @@ def retrieve_and_generate(question):
|
|
77 |
# Create a Gradio interface
|
78 |
interface = gr.Interface(
|
79 |
fn=retrieve_and_generate,
|
80 |
-
inputs=gr.Textbox(lines=2, placeholder="Ask a question about the documents..."),
|
81 |
outputs="text",
|
82 |
title="RAG Chatbot",
|
83 |
description="Ask questions about the documents in the CSV file."
|
|
|
3 |
import numpy as np
|
4 |
from transformers import pipeline, BertTokenizer, BertModel
|
5 |
import faiss
|
|
|
|
|
|
|
6 |
|
7 |
# Load CSV data
|
8 |
+
data = pd.read_csv('RBDx10stats.csv')
|
9 |
|
10 |
+
# Convert embedding column from string to numpy array
|
11 |
+
data['Embedding'] = data['Embedding'].apply(lambda x: np.fromstring(x[1:-1], sep=', '))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
# Initialize FAISS index
|
14 |
+
dimension = len(data['Embedding'][0])
|
15 |
+
index = faiss.IndexFlatL2(dimension)
|
16 |
+
index.add(np.stack(data['Embedding'].values))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
# Load QA model
|
19 |
+
qa_model = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")
|
|
|
|
|
|
|
|
|
20 |
|
21 |
# Function to embed the question using BERT
|
22 |
def embed_question(question, model, tokenizer):
|
23 |
+
inputs = tokenizer(question, return_tensors='pt')
|
24 |
+
outputs = model(**inputs)
|
25 |
+
return outputs.last_hidden_state.mean(dim=1).detach().numpy()
|
26 |
+
|
27 |
+
# Load BERT model and tokenizer
|
28 |
+
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
29 |
+
model = BertModel.from_pretrained('bert-base-uncased')
|
30 |
|
31 |
# Function to retrieve the relevant document and generate a response
|
|
|
32 |
def retrieve_and_generate(question):
|
33 |
# Embed the question
|
34 |
question_embedding = embed_question(question, model, tokenizer)
|
35 |
|
36 |
# Search in FAISS index
|
37 |
+
_, indices = index.search(question_embedding, k=1)
|
38 |
|
39 |
# Retrieve the most relevant document
|
40 |
relevant_doc = data.iloc[indices[0][0]]
|
|
|
48 |
# Create a Gradio interface
|
49 |
interface = gr.Interface(
|
50 |
fn=retrieve_and_generate,
|
51 |
+
inputs=gr.inputs.Textbox(lines=2, placeholder="Ask a question about the documents..."),
|
52 |
outputs="text",
|
53 |
title="RAG Chatbot",
|
54 |
description="Ask questions about the documents in the CSV file."
|