Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,23 +1,24 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
|
| 4 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 5 |
import faiss
|
| 6 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
| 7 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
-
import fitz # PyMuPDF
|
| 9 |
from huggingface_hub import login
|
| 10 |
|
| 11 |
-
# Authenticate
|
| 12 |
hf_token = os.environ.get("HUGGINGFACE_TOKEN")
|
| 13 |
-
if
|
| 14 |
-
raise ValueError("Please set the HUGGINGFACE_TOKEN environment variable")
|
| 15 |
login(token=hf_token)
|
| 16 |
|
| 17 |
-
# Load embedding model
|
| 18 |
embed_model = SentenceTransformer("BAAI/bge-base-en-v1.5")
|
| 19 |
|
| 20 |
-
# Load LLM
|
| 21 |
model_id = "mistralai/Mistral-7B-Instruct-v0.1"
|
| 22 |
tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=hf_token)
|
| 23 |
model = AutoModelForCausalLM.from_pretrained(
|
|
@@ -28,67 +29,77 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 28 |
)
|
| 29 |
llm = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 30 |
|
| 31 |
-
#
|
| 32 |
index = None
|
| 33 |
doc_texts = []
|
| 34 |
|
| 35 |
-
#
|
| 36 |
def extract_text(file):
|
|
|
|
|
|
|
| 37 |
if file.name.endswith(".pdf"):
|
| 38 |
-
|
| 39 |
-
doc = fitz.open(
|
| 40 |
for page in doc:
|
| 41 |
text += page.get_text()
|
| 42 |
-
return text
|
| 43 |
elif file.name.endswith(".txt"):
|
| 44 |
-
|
| 45 |
else:
|
| 46 |
-
return "β
|
|
|
|
| 47 |
|
| 48 |
-
#
|
| 49 |
def process_file(file):
|
| 50 |
global index, doc_texts
|
| 51 |
text = extract_text(file)
|
| 52 |
if text.startswith("β"):
|
| 53 |
return text
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
| 58 |
|
|
|
|
| 59 |
dim = embeddings.shape[1]
|
| 60 |
index = faiss.IndexFlatL2(dim)
|
| 61 |
-
index.add(
|
| 62 |
|
| 63 |
return "β
File processed successfully. You can now ask questions!"
|
| 64 |
|
| 65 |
-
# Generate answer
|
| 66 |
def generate_answer(question):
|
| 67 |
global index, doc_texts
|
| 68 |
-
if index is None or
|
| 69 |
return "β οΈ Please upload and process a file first."
|
| 70 |
-
|
| 71 |
-
question_embedding = embed_model.encode([question])
|
| 72 |
-
_, I = index.search(np.array(question_embedding), k=3)
|
| 73 |
-
context = "\n".join([doc_texts[i] for i in I[0]])
|
| 74 |
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
|
|
|
|
|
|
| 77 |
Context:
|
| 78 |
{context}
|
| 79 |
|
| 80 |
Question: {question}
|
| 81 |
Answer:"""
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
|
|
|
| 85 |
|
| 86 |
-
# Gradio UI
|
| 87 |
-
with gr.Blocks(title="RAG Chatbot") as demo:
|
| 88 |
-
gr.Markdown("## π
|
| 89 |
|
| 90 |
with gr.Row():
|
| 91 |
-
file_input = gr.File(label="π Upload
|
| 92 |
upload_status = gr.Textbox(label="π₯ Upload Status", interactive=False)
|
| 93 |
|
| 94 |
with gr.Row():
|
|
@@ -98,4 +109,5 @@ with gr.Blocks(title="RAG Chatbot") as demo:
|
|
| 98 |
file_input.change(fn=process_file, inputs=file_input, outputs=upload_status)
|
| 99 |
question_box.submit(fn=generate_answer, inputs=question_box, outputs=answer_box)
|
| 100 |
|
|
|
|
| 101 |
demo.launch()
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
import fitz # PyMuPDF
|
|
|
|
| 4 |
import faiss
|
| 5 |
import numpy as np
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 9 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
|
| 10 |
from huggingface_hub import login
|
| 11 |
|
| 12 |
+
# 1. Authenticate HuggingFace
|
| 13 |
hf_token = os.environ.get("HUGGINGFACE_TOKEN")
|
| 14 |
+
if not hf_token:
|
| 15 |
+
raise ValueError("β οΈ Please set the HUGGINGFACE_TOKEN environment variable.")
|
| 16 |
login(token=hf_token)
|
| 17 |
|
| 18 |
+
# 2. Load embedding model
|
| 19 |
embed_model = SentenceTransformer("BAAI/bge-base-en-v1.5")
|
| 20 |
|
| 21 |
+
# 3. Load LLM (Mistral 7B Instruct with 4-bit quantization)
|
| 22 |
model_id = "mistralai/Mistral-7B-Instruct-v0.1"
|
| 23 |
tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=hf_token)
|
| 24 |
model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
| 29 |
)
|
| 30 |
llm = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 31 |
|
| 32 |
+
# 4. Globals
|
| 33 |
index = None
|
| 34 |
doc_texts = []
|
| 35 |
|
| 36 |
+
# 5. Extract text from uploaded file
|
| 37 |
def extract_text(file):
|
| 38 |
+
text = ""
|
| 39 |
+
file_bytes = file.read()
|
| 40 |
if file.name.endswith(".pdf"):
|
| 41 |
+
pdf_stream = BytesIO(file_bytes)
|
| 42 |
+
doc = fitz.open(stream=pdf_stream, filetype="pdf")
|
| 43 |
for page in doc:
|
| 44 |
text += page.get_text()
|
|
|
|
| 45 |
elif file.name.endswith(".txt"):
|
| 46 |
+
text = file_bytes.decode("utf-8")
|
| 47 |
else:
|
| 48 |
+
return "β Unsupported file type. Only PDF and TXT are allowed."
|
| 49 |
+
return text
|
| 50 |
|
| 51 |
+
# 6. Process the file: split text, create embeddings, build FAISS index
|
| 52 |
def process_file(file):
|
| 53 |
global index, doc_texts
|
| 54 |
text = extract_text(file)
|
| 55 |
if text.startswith("β"):
|
| 56 |
return text
|
| 57 |
|
| 58 |
+
# Split text
|
| 59 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50)
|
| 60 |
+
doc_texts = splitter.split_text(text)
|
| 61 |
+
|
| 62 |
+
# Create embeddings
|
| 63 |
+
embeddings = embed_model.encode(doc_texts, convert_to_numpy=True)
|
| 64 |
|
| 65 |
+
# Build FAISS index
|
| 66 |
dim = embeddings.shape[1]
|
| 67 |
index = faiss.IndexFlatL2(dim)
|
| 68 |
+
index.add(embeddings)
|
| 69 |
|
| 70 |
return "β
File processed successfully. You can now ask questions!"
|
| 71 |
|
| 72 |
+
# 7. Generate answer based on question + retrieved context
|
| 73 |
def generate_answer(question):
|
| 74 |
global index, doc_texts
|
| 75 |
+
if index is None or not doc_texts:
|
| 76 |
return "β οΈ Please upload and process a file first."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
# Embed the question
|
| 79 |
+
question_emb = embed_model.encode([question], convert_to_numpy=True)
|
| 80 |
+
_, I = index.search(question_emb, k=3)
|
| 81 |
+
|
| 82 |
+
# Build context
|
| 83 |
+
context = "\n".join([doc_texts[i] for i in I[0]])
|
| 84 |
|
| 85 |
+
# Prompt
|
| 86 |
+
prompt = f"""[System: You are a helpful assistant. Answer strictly based on the context. Do not hallucinate.]
|
| 87 |
Context:
|
| 88 |
{context}
|
| 89 |
|
| 90 |
Question: {question}
|
| 91 |
Answer:"""
|
| 92 |
|
| 93 |
+
# Generate response
|
| 94 |
+
response = llm(prompt, max_new_tokens=300, do_sample=True, temperature=0.7)
|
| 95 |
+
return response[0]["generated_text"].split("Answer:")[-1].strip()
|
| 96 |
|
| 97 |
+
# 8. Gradio UI
|
| 98 |
+
with gr.Blocks(title="π§ RAG Chatbot") as demo:
|
| 99 |
+
gr.Markdown("## π Retrieval-Augmented Generation Chatbot\nUpload a `.pdf` or `.txt` and ask questions from the content.")
|
| 100 |
|
| 101 |
with gr.Row():
|
| 102 |
+
file_input = gr.File(label="π Upload PDF/TXT", file_types=[".pdf", ".txt"])
|
| 103 |
upload_status = gr.Textbox(label="π₯ Upload Status", interactive=False)
|
| 104 |
|
| 105 |
with gr.Row():
|
|
|
|
| 109 |
file_input.change(fn=process_file, inputs=file_input, outputs=upload_status)
|
| 110 |
question_box.submit(fn=generate_answer, inputs=question_box, outputs=answer_box)
|
| 111 |
|
| 112 |
+
# 9. Launch the app
|
| 113 |
demo.launch()
|