Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Import necessary libraries
|
2 |
+
import PyPDF2
|
3 |
+
from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
import torch
|
6 |
+
from google.colab import files
|
7 |
+
|
8 |
+
# Step 1: Upload the PDF file
|
9 |
+
print("Please upload a PDF file containing the chapter.")
|
10 |
+
uploaded = files.upload()
|
11 |
+
|
12 |
+
# Extract the name of the uploaded file
|
13 |
+
file_name = list(uploaded.keys())[0]
|
14 |
+
|
15 |
+
# Step 2: Extract text from the PDF
|
16 |
+
def extract_text_from_pdf(file_path):
|
17 |
+
text = ""
|
18 |
+
with open(file_path, 'rb') as file:
|
19 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
20 |
+
for page in pdf_reader.pages:
|
21 |
+
text += page.extract_text()
|
22 |
+
return text
|
23 |
+
|
24 |
+
chapter_text = extract_text_from_pdf(file_name)
|
25 |
+
print("Text extracted from the PDF successfully!")
|
26 |
+
|
27 |
+
# Step 3: Split the text into smaller passages
|
28 |
+
def split_text_into_chunks(text, chunk_size=500):
|
29 |
+
"""Split the text into chunks of size chunk_size."""
|
30 |
+
words = text.split()
|
31 |
+
chunks = []
|
32 |
+
for i in range(0, len(words), chunk_size):
|
33 |
+
chunk = " ".join(words[i:i + chunk_size])
|
34 |
+
chunks.append(chunk)
|
35 |
+
return chunks
|
36 |
+
|
37 |
+
passages = split_text_into_chunks(chapter_text)
|
38 |
+
print(f"Chapter split into {len(passages)} passages for RAG processing.")
|
39 |
+
|
40 |
+
# Step 4: Initialize the RAG model and tokenizer
|
41 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
42 |
+
|
43 |
+
# Load the RAG model, tokenizer, and retriever
|
44 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
|
45 |
+
retriever = RagRetriever.from_pretrained(
|
46 |
+
"facebook/rag-token-nq",
|
47 |
+
index_name="custom",
|
48 |
+
passages=passages, # Set passages as the custom index
|
49 |
+
use_dummy_dataset=True, # Dummy dataset required for custom index
|
50 |
+
)
|
51 |
+
model = RagSequenceForGeneration.from_pretrained("facebook/rag-token-nq").to(device)
|
52 |
+
|
53 |
+
# Step 5: Encode passages into embeddings for retrieval
|
54 |
+
sentence_model = SentenceTransformer("sentence-transformers/all-mpnet-base-v2")
|
55 |
+
passage_embeddings = sentence_model.encode(passages, convert_to_tensor=True)
|
56 |
+
retriever.index.set_passages(passages, passage_embeddings.cpu().detach().numpy())
|
57 |
+
print("Passages indexed successfully!")
|
58 |
+
|
59 |
+
# Step 6: Define a function to generate answers
|
60 |
+
def generate_answer(question, passages):
|
61 |
+
inputs = tokenizer.prepare_seq2seq_batch(
|
62 |
+
questions=[question], return_tensors="pt"
|
63 |
+
).to(device)
|
64 |
+
generated_ids = model.generate(**inputs)
|
65 |
+
answer = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
66 |
+
return answer
|
67 |
+
|
68 |
+
# Step 7: Interactive Question-Answering
|
69 |
+
print("\nChapter is ready. You can now ask questions!")
|
70 |
+
while True:
|
71 |
+
user_question = input("\nEnter your question (or type 'exit' to quit): ")
|
72 |
+
if user_question.lower() == "exit":
|
73 |
+
print("Exiting the application. Thank you!")
|
74 |
+
break
|
75 |
+
try:
|
76 |
+
answer = generate_answer(user_question, passages)
|
77 |
+
print(f"Answer: {answer}")
|
78 |
+
except Exception as e:
|
79 |
+
print(f"An error occurred: {e}")
|