toajibul commited on
Commit
0094797
·
verified ·
1 Parent(s): 8374ace

Upload app.py with huggingface_hub

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