OlamideKayode commited on
Commit
705dedb
·
verified ·
1 Parent(s): d6cd132

Upload app.py with huggingface_hub

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