chatbot_copy / app.py
KatieKhamarkhanova's picture
Update app.py
2fb53e0 verified
import gradio as gr
from huggingface_hub import InferenceClient
from sentence_transformers import SentenceTransformer
import torch
import numpy as np
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
# Open the ECOsphere.txt file in read mode with UTF-8 encoding
with open("ECOsphere.txt", "r", encoding="utf-8") as file:
# Read the entire contents of the file and store it in a variable
ECOsphere_text = file.read()
def respond(message, history):
top_results = get_top_chunks( message , chunk_embeddings, cleaned_chunks) # Complete this line
# Print the top results
print(top_results)
messages = [{ "role": "system", "content": f"You are a chatbot that encourage people to live more sustainably. Base your response on the following action {top_results}" }]
if history:
messages.extend(history)
messages.append({"role": "user", "content": message})
response = client.chat_completion(
messages,
max_tokens = 200,
temperature = 0.5
)
try:
content = response["choices"][0]["message"]["content"].strip()
except (KeyError, json.decoder.JSONDecodeError) as e:
print("Error parsing response:", e)
content = "Sorry, I couldn't generate a response."
return content
chatbot = gr.ChatInterface(respond, type="messages")
cleaned_chunks = []
def preprocess_text(text):
# Strip extra whitespace from the beginning and the end of the text
cleaned_text = text.strip()
# Split the cleaned_text by every newline character (\n)
chunks = cleaned_text.split("\n")
# Create an empty list to store cleaned chunks
#cleaned_chunks = []
# Write your for-in loop below to clean each chunk and add it to the cleaned_chunks list
for chunk in chunks:
stripped_chunk = chunk.strip()
cleaned_chunks.append(stripped_chunk)
# Print cleaned_chunks
print(cleaned_chunks)
# Print the length of cleaned_chunks
print(len(cleaned_chunks))
# Return the cleaned_chunks
return cleaned_chunks
cleaned_chunks = preprocess_text(ECOsphere_text)
# Load the pre-trained embedding model that converts text to vectors
model = SentenceTransformer('all-MiniLM-L6-v2')
def create_embeddings(text_chunks):
# Convert each text chunk into a vector embedding and store as a tensor
chunk_embeddings = model.encode(text_chunks, convert_to_tensor=True) # Replace ... with the text_chunks list
# Print the chunk embeddings
print(chunk_embeddings)
# Print the shape of chunk_embeddings
print(chunk_embeddings.shape)
# Return the chunk_embeddings
return chunk_embeddings
chunk_embeddings = create_embeddings(cleaned_chunks)
# Define a function to find the most relevant text chunks for a given query, chunk_embeddings, and text_chunks
def get_top_chunks(query, chunk_embeddings, text_chunks):
query_embedding = model.encode(query, convert_to_tensor=True)
query_embedding_normalized = query_embedding / query_embedding.norm()
chunk_embeddings_normalized = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True)
similarities = torch.matmul(chunk_embeddings_normalized, query_embedding_normalized)
k = min(3, len(text_chunks)) # Fix topk range error
top_indices = torch.topk(similarities, k=k).indices
top_chunks = []
for index in top_indices:
top_chunks.append(text_chunks[index])
return top_chunks
chatbot.launch()