Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,64 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
)
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
)
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import zipfile
|
| 3 |
+
import torch
|
| 4 |
+
import faiss
|
| 5 |
+
import numpy as np
|
| 6 |
import gradio as gr
|
| 7 |
+
from transformers import GPT2Tokenizer, AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
from langchain.document_loaders import TextLoader
|
| 10 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 11 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 12 |
+
from langchain.vectorstores import FAISS as LangChainFAISS
|
| 13 |
+
from langchain.docstore import InMemoryDocstore
|
| 14 |
+
from langchain.schema import Document
|
| 15 |
+
from langchain.llms import HuggingFacePipeline
|
| 16 |
+
|
| 17 |
+
# === 1. Extract the Knowledge Base ZIP ===
|
| 18 |
+
if os.path.exists("md_knowledge_base.zip"):
|
| 19 |
+
with zipfile.ZipFile("md_knowledge_base.zip", "r") as zip_ref:
|
| 20 |
+
zip_ref.extractall("md_knowledge_base")
|
| 21 |
+
print("✅ Knowledge base extracted.")
|
| 22 |
+
|
| 23 |
+
# === 2. Load Markdown Files ===
|
| 24 |
+
KB_PATH = "md_knowledge_base"
|
| 25 |
+
files = [os.path.join(dp, f) for dp, _, fn in os.walk(KB_PATH) for f in fn if f.endswith(".md")]
|
| 26 |
+
docs = [doc for f in files for doc in TextLoader(f, encoding="utf-8").load()]
|
| 27 |
+
print(f"✅ Loaded {len(docs)} documents.")
|
| 28 |
+
|
| 29 |
+
# === 3. Chunking ===
|
| 30 |
+
def get_dynamic_chunk_size(text):
|
| 31 |
+
if len(text) < 1000:
|
| 32 |
+
return 300
|
| 33 |
+
elif len(text) < 5000:
|
| 34 |
+
return 500
|
| 35 |
+
else:
|
| 36 |
+
return 1000
|
| 37 |
+
|
| 38 |
+
chunks = []
|
| 39 |
+
for doc in docs:
|
| 40 |
+
chunk_size = get_dynamic_chunk_size(doc.page_content)
|
| 41 |
+
chunk_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=100)
|
| 42 |
+
chunks.extend(chunk_splitter.split_documents([doc]))
|
| 43 |
+
texts = [chunk.page_content for chunk in chunks]
|
| 44 |
+
|
| 45 |
+
# === 4. Vectorstore (FAISS) ===
|
| 46 |
+
embed_model_id = "distilbert-base-uncased"
|
| 47 |
+
embedder = SentenceTransformer(embed_model_id)
|
| 48 |
+
embeddings = embedder.encode(texts, show_progress_bar=False)
|
| 49 |
+
|
| 50 |
+
dim = embeddings.shape[1]
|
| 51 |
+
index = faiss.IndexFlatL2(dim)
|
| 52 |
+
index.add(np.array(embeddings, dtype="float32"))
|
| 53 |
+
|
| 54 |
+
docs = [Document(page_content=t) for t in texts]
|
| 55 |
+
docstore = InMemoryDocstore({str(i): docs[i] for i in range(len(docs))})
|
| 56 |
+
id_map = {i: str(i) for i in range(len(docs))}
|
| 57 |
+
embed_fn = HuggingFaceEmbeddings(model_name=embed_model_id)
|
| 58 |
+
|
| 59 |
+
vectorstore = LangChainFAISS(
|
| 60 |
+
index=index,
|
| 61 |
+
docstore=docstore,
|
| 62 |
+
index_to_docstore_id=id_map,
|
| 63 |
+
embedding_function=embed_fn
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# === 5. Load Falcon-e-1B-Instruct ===
|
| 68 |
+
# model_id = "tiiuae/falcon-e-1b-instruct"
|
| 69 |
+
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
| 70 |
+
model = AutoModelForCausalLM.from_pretrained("gpt2").to("cuda" if torch.cuda.is_available() else "cpu")
|
| 71 |
+
|
| 72 |
+
text_gen_pipeline = pipeline(
|
| 73 |
+
"text-generation",
|
| 74 |
+
model=model,
|
| 75 |
+
tokenizer=tokenizer,
|
| 76 |
+
torch_dtype=torch.bfloat16,
|
| 77 |
+
device=0 if torch.cuda.is_available() else -1,
|
| 78 |
+
return_full_text=False,
|
| 79 |
+
do_sample=False,
|
| 80 |
+
max_new_tokens=200,
|
| 81 |
+
pad_token_id=tokenizer.eos_token_id
|
| 82 |
)
|
| 83 |
|
| 84 |
+
llm = HuggingFacePipeline(pipeline=text_gen_pipeline)
|
| 85 |
+
|
| 86 |
+
# === 6. Prompt Format and Q&A ===
|
| 87 |
+
def truncate_context(context, max_length=1024):
|
| 88 |
+
tokens = tokenizer.encode(context)
|
| 89 |
+
if len(tokens) > max_length:
|
| 90 |
+
tokens = tokens[:max_length]
|
| 91 |
+
return tokenizer.decode(tokens, skip_special_tokens=True)
|
| 92 |
+
|
| 93 |
+
def format_prompt(context, question):
|
| 94 |
+
return (
|
| 95 |
+
"You are the Cambridge University Assistant—a friendly, knowledgeable chatbot dedicated to "
|
| 96 |
+
"helping students with questions about courses, admissions, tuition fees, and student life. "
|
| 97 |
+
"Use ONLY the information provided in the context below to answer the question. "
|
| 98 |
+
"If the answer cannot be found in the context, reply: \"I’m sorry, but I don’t have that "
|
| 99 |
+
"information available right now.\"\n\n"
|
| 100 |
+
f"Context:\n{truncate_context(context)}\n\n"
|
| 101 |
+
f"Student Question: {question}\n"
|
| 102 |
+
"Assistant Answer:"
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
def answer_fn(question):
|
| 106 |
+
docs = vectorstore.similarity_search(question, k=5)
|
| 107 |
+
if not docs:
|
| 108 |
+
return "I'm sorry, I couldn't find any relevant information for your query."
|
| 109 |
+
context = "\n\n".join(d.page_content for d in docs)
|
| 110 |
+
prompt = format_prompt(context, question)
|
| 111 |
+
try:
|
| 112 |
+
response = llm.invoke(prompt).strip()
|
| 113 |
+
return response
|
| 114 |
+
except Exception as e:
|
| 115 |
+
return f"An error occurred: {e}"
|
| 116 |
+
|
| 117 |
+
# === 7. Gradio Interface ===
|
| 118 |
+
def chat_fn(user_message, history):
|
| 119 |
+
bot_response = answer_fn(user_message)
|
| 120 |
+
history = history + [(user_message, bot_response)]
|
| 121 |
+
return history, history
|
| 122 |
+
|
| 123 |
+
with gr.Blocks() as demo:
|
| 124 |
+
gr.Markdown("## 📘 University of Cambridge Assistant")
|
| 125 |
+
chatbot = gr.Chatbot()
|
| 126 |
+
state = gr.State([])
|
| 127 |
+
user_input = gr.Textbox(placeholder="Ask a question about Cambridge...", show_label=False)
|
| 128 |
+
|
| 129 |
+
user_input.submit(fn=chat_fn, inputs=[user_input, state], outputs=[chatbot, state])
|
| 130 |
|
| 131 |
+
demo.launch()
|
|
|