import fasttext import gradio as gr from gradio import components as components import numpy as np model = "cc.en.300.bin" model = fasttext.load_model(model) def get_cosine(a, b): cosine_similarity = np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) return cosine_similarity def get_score(targets, answers, th): th = float(th) results = [] targets = targets.split(",") target_len = len(targets) answers = answers.split(",") # th = 0.6 for i, target in enumerate(targets): if target[0]==" ": target=target[1:] # if i>2:break target_vector = model.get_word_vector(target.lower()) cosine_list = [] # compare all of answer data for answer in answers: answer_vector = model.get_word_vector(answer.lower()) cosine = get_cosine(target_vector, answer_vector) cosine_list.append(cosine) # comparison is over threshold -> true else -> false # results.append(max(cosine_list)>th) # reject answer once it is used if max(cosine_list)>th: argmax = cosine_list.index(max(cosine_list)) results.append(max(cosine_list)) answers.remove(answers[argmax]) if len(answers)==0: break if len(results)==0: return 0 result = int(sum(results) / len(results) * 100) # result = sum(results) / target_len return result def my_app(targets, answers, th): return get_score(targets, answers, th) inputs = [ components.Textbox(label="Targets"), components.Textbox(label="Answers"), components.Textbox(label="Threshold", value=0.6), ] output = components.Textbox(label="Output") app = gr.Interface( fn=my_app, inputs=inputs, outputs=output ) app.launch( app_kwargs={"docs_url":"/docs"} )