Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,13 +3,12 @@ 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,
|
9 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
10 |
from huggingface_hub import login
|
11 |
|
12 |
-
#
|
13 |
hf_token = os.environ.get("HUGGINGFACE_TOKEN")
|
14 |
if not hf_token:
|
15 |
raise ValueError("β οΈ Please set the HUGGINGFACE_TOKEN environment variable.")
|
@@ -18,42 +17,37 @@ login(token=hf_token)
|
|
18 |
# Load embedding model
|
19 |
embed_model = SentenceTransformer("BAAI/bge-base-en-v1.5")
|
20 |
|
21 |
-
#
|
22 |
-
model_id = "
|
23 |
-
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
24 |
-
model =
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
# Globals
|
28 |
index = None
|
29 |
doc_texts = []
|
30 |
|
31 |
-
# Extract text from PDF or TXT
|
32 |
def extract_text(file):
|
33 |
text = ""
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
filename = file.name
|
43 |
-
|
44 |
-
if filename.endswith(".pdf"):
|
45 |
-
pdf_stream = BytesIO(file_bytes)
|
46 |
-
doc = fitz.open(stream=pdf_stream, filetype="pdf")
|
47 |
-
for page in doc:
|
48 |
-
text += page.get_text()
|
49 |
-
elif filename.endswith(".txt"):
|
50 |
-
text = file_bytes.decode("utf-8")
|
51 |
else:
|
52 |
return "β Unsupported file type."
|
53 |
return text
|
54 |
|
55 |
-
|
56 |
-
# Process the file, build FAISS index
|
57 |
def process_file(file):
|
58 |
global index, doc_texts
|
59 |
text = extract_text(file)
|
@@ -68,42 +62,42 @@ def process_file(file):
|
|
68 |
index = faiss.IndexFlatL2(dim)
|
69 |
index.add(embeddings)
|
70 |
|
71 |
-
return "β
File processed!
|
72 |
|
73 |
-
# Generate answer
|
74 |
def generate_answer(question):
|
75 |
global index, doc_texts
|
76 |
if index is None or not doc_texts:
|
77 |
-
return "β οΈ Please upload and process a
|
78 |
|
79 |
question_emb = embed_model.encode([question], convert_to_numpy=True)
|
80 |
_, I = index.search(question_emb, k=3)
|
81 |
context = "\n".join([doc_texts[i] for i in I[0]])
|
82 |
|
83 |
-
prompt = f"""
|
84 |
|
85 |
Context:
|
86 |
{context}
|
87 |
|
88 |
Question: {question}
|
89 |
-
"""
|
90 |
|
91 |
-
|
92 |
-
return
|
93 |
|
94 |
# Gradio UI
|
95 |
-
with gr.Blocks(title="RAG Chatbot (
|
96 |
-
gr.Markdown("## π Upload PDF/TXT and Ask Questions
|
97 |
|
98 |
with gr.Row():
|
99 |
-
file_input = gr.File(label="π Upload
|
100 |
-
|
101 |
|
102 |
with gr.Row():
|
103 |
-
|
104 |
-
|
105 |
|
106 |
-
file_input.change(fn=process_file, inputs=file_input, outputs=
|
107 |
-
|
108 |
|
109 |
demo.launch()
|
|
|
3 |
import fitz # PyMuPDF
|
4 |
import faiss
|
5 |
import numpy as np
|
|
|
6 |
from sentence_transformers import SentenceTransformer
|
7 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
8 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
9 |
from huggingface_hub import login
|
10 |
|
11 |
+
# Load Hugging Face Token from environment
|
12 |
hf_token = os.environ.get("HUGGINGFACE_TOKEN")
|
13 |
if not hf_token:
|
14 |
raise ValueError("β οΈ Please set the HUGGINGFACE_TOKEN environment variable.")
|
|
|
17 |
# Load embedding model
|
18 |
embed_model = SentenceTransformer("BAAI/bge-base-en-v1.5")
|
19 |
|
20 |
+
# Load small, fast LLM (great for CPU)
|
21 |
+
model_id = "tiiuae/falcon-rw-1b"
|
22 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, token=hf_token)
|
23 |
+
model = AutoModelForCausalLM.from_pretrained(
|
24 |
+
model_id,
|
25 |
+
device_map={"": "cpu"},
|
26 |
+
torch_dtype="auto",
|
27 |
+
token=hf_token
|
28 |
+
)
|
29 |
+
llm = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
30 |
|
31 |
# Globals
|
32 |
index = None
|
33 |
doc_texts = []
|
34 |
|
35 |
+
# Extract text from PDF or TXT (handle Hugging Face Spaces file upload)
|
36 |
def extract_text(file):
|
37 |
text = ""
|
38 |
+
file_path = file.name if hasattr(file, 'name') else file
|
39 |
+
if file_path.endswith(".pdf"):
|
40 |
+
with fitz.open(file_path) as doc:
|
41 |
+
for page in doc:
|
42 |
+
text += page.get_text()
|
43 |
+
elif file_path.endswith(".txt"):
|
44 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
45 |
+
text = f.read()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
else:
|
47 |
return "β Unsupported file type."
|
48 |
return text
|
49 |
|
50 |
+
# Process file and build FAISS index
|
|
|
51 |
def process_file(file):
|
52 |
global index, doc_texts
|
53 |
text = extract_text(file)
|
|
|
62 |
index = faiss.IndexFlatL2(dim)
|
63 |
index.add(embeddings)
|
64 |
|
65 |
+
return "β
File processed successfully! Ask your question below."
|
66 |
|
67 |
+
# Generate answer
|
68 |
def generate_answer(question):
|
69 |
global index, doc_texts
|
70 |
if index is None or not doc_texts:
|
71 |
+
return "β οΈ Please upload and process a document first."
|
72 |
|
73 |
question_emb = embed_model.encode([question], convert_to_numpy=True)
|
74 |
_, I = index.search(question_emb, k=3)
|
75 |
context = "\n".join([doc_texts[i] for i in I[0]])
|
76 |
|
77 |
+
prompt = f"""[System: You are a helpful assistant. Answer based on the context.]
|
78 |
|
79 |
Context:
|
80 |
{context}
|
81 |
|
82 |
Question: {question}
|
83 |
+
Answer:"""
|
84 |
|
85 |
+
result = llm(prompt, max_new_tokens=200, do_sample=True, temperature=0.7)
|
86 |
+
return result[0]["generated_text"].split("Answer:")[-1].strip()
|
87 |
|
88 |
# Gradio UI
|
89 |
+
with gr.Blocks(title="RAG Chatbot (CPU-Optimized)") as demo:
|
90 |
+
gr.Markdown("## π Upload PDF/TXT and Ask Questions (Fast CPU RAG Bot)")
|
91 |
|
92 |
with gr.Row():
|
93 |
+
file_input = gr.File(label="π Upload PDF or TXT", file_types=[".pdf", ".txt"])
|
94 |
+
upload_output = gr.Textbox(label="Upload Status", interactive=False)
|
95 |
|
96 |
with gr.Row():
|
97 |
+
question_input = gr.Textbox(label="β Ask a Question", placeholder="E.g. What is the document about?")
|
98 |
+
answer_output = gr.Textbox(label="π¬ Answer", interactive=False)
|
99 |
|
100 |
+
file_input.change(fn=process_file, inputs=file_input, outputs=upload_output)
|
101 |
+
question_input.submit(fn=generate_answer, inputs=question_input, outputs=answer_output)
|
102 |
|
103 |
demo.launch()
|