Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoTokenizer, AutoModel
|
3 |
+
import torch
|
4 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
# Load the model and tokenizer
|
8 |
+
model_name = "nasa-impact/nasa-smd-ibm-st-v2"
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
10 |
+
model = AutoModel.from_pretrained(model_name)
|
11 |
+
|
12 |
+
def encode_text(text):
|
13 |
+
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True)
|
14 |
+
outputs = model(**inputs)
|
15 |
+
return outputs.last_hidden_state.mean(dim=1).detach().numpy()
|
16 |
+
|
17 |
+
def find_best_response(user_input, response_pool):
|
18 |
+
user_embedding = encode_text(user_input)
|
19 |
+
response_embeddings = np.array([encode_text(resp) for resp in response_pool])
|
20 |
+
similarities = cosine_similarity(user_embedding, response_embeddings).flatten()
|
21 |
+
best_response_index = np.argmax(similarities)
|
22 |
+
return response_pool[best_response_index]
|
23 |
+
|
24 |
+
# Define some example responses for the chatbot to choose from
|
25 |
+
response_pool = [
|
26 |
+
"Hello! How can I help you today?",
|
27 |
+
"I'm here to assist you with any questions you have.",
|
28 |
+
"What would you like to know more about?",
|
29 |
+
"Can you please provide more details?",
|
30 |
+
"I'm not sure about that. Could you clarify?"
|
31 |
+
]
|
32 |
+
|
33 |
+
def chatbot(user_input):
|
34 |
+
best_response = find_best_response(user_input, response_pool)
|
35 |
+
return best_response
|
36 |
+
|
37 |
+
# Create the Gradio interface
|
38 |
+
iface = gr.Interface(
|
39 |
+
fn=chatbot,
|
40 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter your message here..."),
|
41 |
+
outputs="text",
|
42 |
+
title="Bi-encoder Chatbot",
|
43 |
+
description="A simple chatbot using a bi-encoder model to find the best response."
|
44 |
+
)
|
45 |
+
|
46 |
+
# Launch the interface
|
47 |
+
iface.launch()
|