Alfredo273's picture
Update model dimension
0ac7406
import os
import numpy as np
from gensim.models import FastText
from sklearn.metrics.pairwise import cosine_similarity
import gradio as gr
# Load the FastText model (make sure the model path is correct)
model_path = "vibecheck-fasttext/cc.en.100.bin" # Replace with the correct model path
model = FastText.load_fasttext_format("./cc.en.300.bin")
def get_vector(word):
try:
return model.wv[word]
except KeyError:
return np.zeros(model.vector_size)
def average_vector(words):
vectors = [get_vector(word) for word in words.split()]
return np.mean(vectors, axis=0)
def vector_to_word(vector):
# Convert the string representation of the vector back to an actual numpy array
vector = np.fromstring(vector[1:-1], sep=' ')
result = model.wv.most_similar(positive=[vector], topn=1)
return result[0][0]
def find_closest_emotion(final_vibe):
emotion_words = [
"Happy", "Sad", "Angry", "Joyful", "Depressed", "Anxious", "Content",
"Excited", "Bored", "Nostalgic", "Frustrated", "Hopeful", "Afraid",
"Confident", "Jealous", "Grateful", "Lonely", "Overwhelmed", "Relaxed",
"Amused", "Curious", "Ashamed", "Sympathetic", "Disappointed", "Proud",
"Guilty", "Enthusiastic", "Empathetic", "Shocked", "Calm", "Inspired",
"Disgusted", "Indifferent", "Romantic", "Surprised", "Tense", "Euphoric",
"Melancholic", "Restless", "Serene", "Sensual"
]
max_similarity = -1
closest_emotion = None
for word in emotion_words:
word_vec = get_vector(word)
similarity = cosine_similarity(final_vibe, word_vec)
if similarity > max_similarity:
max_similarity = similarity
closest_emotion = word
return closest_emotion
def cosine_similarity(vec_a, vec_b):
return np.dot(vec_a, vec_b) / (np.linalg.norm(vec_a) * np.linalg.norm(vec_b))
def process_function(action, *args):
if action == "get_vector":
return get_vector(*args)
elif action == "average_vector":
return average_vector(*args)
elif action == "vector_to_word":
return vector_to_word(*args)
elif action == "find_closest_emotion":
return find_closest_emotion(*args)
else:
raise ValueError("Invalid action specified.")
iface = gr.Interface(
fn=process_function,
inputs=[
gr.Dropdown(choices=["get_vector", "average_vector", "vector_to_word", "find_closest_emotion"], label="Action"),
gr.Textbox(label="Input Data")
],
outputs=gr.Textbox()
)
if __name__ == "__main__":
iface.launch(server_name="0.0.0.0", server_port=int(os.environ.get('PORT', 7860)))