Update app.py
Browse files
app.py
CHANGED
@@ -6,58 +6,118 @@ For more information on `huggingface_hub` Inference API support, please check th
|
|
6 |
"""
|
7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
9 |
|
10 |
-
|
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 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
44 |
-
"""
|
45 |
-
demo = gr.ChatInterface(
|
46 |
-
respond,
|
47 |
-
additional_inputs=[
|
48 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
49 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
50 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
51 |
-
gr.Slider(
|
52 |
-
minimum=0.1,
|
53 |
-
maximum=1.0,
|
54 |
-
value=0.95,
|
55 |
-
step=0.05,
|
56 |
-
label="Top-p (nucleus sampling)",
|
57 |
-
),
|
58 |
-
],
|
59 |
-
)
|
60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
if __name__ == "__main__":
|
63 |
demo.launch()
|
|
|
6 |
"""
|
7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
9 |
+
# -*- coding: utf-8 -*-
|
10 |
+
"""juri_chatbot.ipynb
|
11 |
|
12 |
+
Automatically generated by Colab.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
Original file is located at
|
15 |
+
https://colab.research.google.com/drive/1o40EH1zkgiGTxJERwU7Tr2b2hb5DPdLX
|
16 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
+
from google.colab import drive
|
19 |
+
drive.mount('/content/gdrive')
|
20 |
+
|
21 |
+
if torch.cuda.is_available():
|
22 |
+
print("CUDA is available! 🚀")
|
23 |
+
num_gpus = torch.cuda.device_count()
|
24 |
+
print(f"Number of available GPUs: {num_gpus}")
|
25 |
+
devices = [torch.device(f"cuda:{i}") for i in range(num_gpus)]
|
26 |
+
else:
|
27 |
+
print("CUDA is not available. Switching to CPU.")
|
28 |
+
devices = [torch.device("cpu")]
|
29 |
+
|
30 |
+
print("Selected devices:", devices)
|
31 |
+
|
32 |
+
pip install gradio
|
33 |
+
|
34 |
+
pip install sentence_transformers
|
35 |
+
|
36 |
+
import gradio as gr
|
37 |
+
import pandas as pd
|
38 |
+
import transformers
|
39 |
+
import torch
|
40 |
+
from sentence_transformers import SentenceTransformer, util
|
41 |
+
|
42 |
+
# Load the SBERT model
|
43 |
+
sbert_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
44 |
+
|
45 |
+
# Function to initialize the Llama 3 8B model pipeline
|
46 |
+
def initiate_pipeline():
|
47 |
+
model = "meta-llama/Meta-Llama-3-8B-Instruct"
|
48 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
49 |
+
return transformers.pipeline(
|
50 |
+
"text-generation",
|
51 |
+
model=model,
|
52 |
+
model_kwargs={"torch_dtype": torch.bfloat16},
|
53 |
+
device=device,
|
54 |
+
)
|
55 |
+
|
56 |
+
# Initialize the model
|
57 |
+
llama_model = initiate_pipeline()
|
58 |
+
|
59 |
+
# Load the Q&A pairs from the CSV
|
60 |
+
qa_data = pd.read_csv("/content/gdrive/MyDrive/Colab Notebooks/rag_juri_cv.csv")
|
61 |
+
|
62 |
+
# Function to retrieve the top 5 relevant Q&A pairs using Sentence-BERT
|
63 |
+
def retrieve_top_k(query, k=5):
|
64 |
+
# Combine the questions from the CSV into a list
|
65 |
+
questions = qa_data['QUESTION'].tolist()
|
66 |
+
|
67 |
+
# Encode the questions and the query using Sentence-BERT
|
68 |
+
question_embeddings = sbert_model.encode(questions, convert_to_tensor=True)
|
69 |
+
query_embedding = sbert_model.encode(query, convert_to_tensor=True)
|
70 |
+
|
71 |
+
# Compute cosine similarities between the query and all questions
|
72 |
+
cosine_scores = util.pytorch_cos_sim(query_embedding, question_embeddings).flatten()
|
73 |
+
|
74 |
+
# Get the indices of the top k most similar questions
|
75 |
+
top_k_indices = torch.topk(cosine_scores, k=k).indices.cpu()
|
76 |
+
|
77 |
+
# Retrieve the corresponding Q&A pairs
|
78 |
+
top_k_qa = qa_data.iloc[top_k_indices]
|
79 |
+
|
80 |
+
return top_k_qa
|
81 |
+
|
82 |
+
def chatbot(query):
|
83 |
+
# Retrieve the top 5 relevant Q&A pairs
|
84 |
+
top_k_qa = retrieve_top_k(query)
|
85 |
+
|
86 |
+
# Generate the prefix, body, and suffix for the prompt
|
87 |
+
prefix = """
|
88 |
+
<|begin_of_text|><|start_header_id|>user<|end_header_id|>You are a chatbot specialized in answering questions about Juri Grosjean's CV.
|
89 |
+
Please only use the information provided in the context to answer the question.
|
90 |
+
Here is the question to answer:
|
91 |
+
""" + query + "\n\n"
|
92 |
+
|
93 |
+
context = "This is the context information to answer the question:\n"
|
94 |
+
for index, row in top_k_qa.iterrows():
|
95 |
+
context += f"Information {index}: {row['ANSWER']}\n\n"
|
96 |
+
|
97 |
+
suffix = "<|eot_id|><|start_header_id|>assistant<|end_header_id|>"
|
98 |
+
|
99 |
+
prompt = prefix + context + suffix
|
100 |
+
|
101 |
+
# Generate a response
|
102 |
+
outputs = llama_model(
|
103 |
+
prompt,
|
104 |
+
max_new_tokens=500,
|
105 |
+
do_sample=True,
|
106 |
+
temperature=0.6,
|
107 |
+
top_p=0.9,
|
108 |
+
)
|
109 |
+
|
110 |
+
# Extract and return the chatbot's answer
|
111 |
+
output = outputs[0]["generated_text"]
|
112 |
+
return output.split("assistant")[-1].strip()
|
113 |
+
|
114 |
+
|
115 |
+
# Set up the Gradio interface
|
116 |
+
demo = gr.Interface(
|
117 |
+
fn=chatbot,
|
118 |
+
inputs=gr.Textbox(lines=5, placeholder="Ask a question about Juri Grosjean's CV"),
|
119 |
+
outputs="text"
|
120 |
+
)
|
121 |
|
122 |
if __name__ == "__main__":
|
123 |
demo.launch()
|