OlamideKayode commited on
Commit
2b4552c
·
verified ·
1 Parent(s): f6ac2c4

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +127 -60
app.py CHANGED
@@ -1,64 +1,131 @@
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
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()