|
|
import gradio as gr |
|
|
import torch |
|
|
import numpy as np |
|
|
from sentence_transformers import SentenceTransformer, util |
|
|
|
|
|
|
|
|
model = SentenceTransformer("all-MiniLM-L6-v2") |
|
|
|
|
|
|
|
|
correct_answer = "AI is powerful" |
|
|
|
|
|
|
|
|
correct_vector = model.encode(correct_answer, convert_to_tensor=True) |
|
|
|
|
|
def check_answer(user_input): |
|
|
""" Function to compare user input with the correct answer """ |
|
|
|
|
|
if not user_input.strip(): |
|
|
return "Please enter a valid input.", 0.0 |
|
|
|
|
|
|
|
|
user_vector = model.encode(user_input, convert_to_tensor=True) |
|
|
|
|
|
|
|
|
similarity_score = util.pytorch_cos_sim(user_vector, correct_vector).item() |
|
|
|
|
|
|
|
|
threshold = 0.9 |
|
|
|
|
|
|
|
|
if similarity_score >= threshold: |
|
|
return f"๐ Congratulations! Your input is {similarity_score*100:.2f}% similar. You won!", similarity_score |
|
|
else: |
|
|
return f"โ Try again! Your input is {similarity_score*100:.2f}% similar. Retry or Exit.", similarity_score |
|
|
|
|
|
|
|
|
with gr.Blocks() as demo: |
|
|
gr.Markdown("# Transformer-Based AI Game ๐ฎ") |
|
|
gr.Markdown("### Enter a phrase that closely matches the correct answer to win!") |
|
|
|
|
|
user_input = gr.Textbox(label="Your Input") |
|
|
submit_btn = gr.Button("Submit") |
|
|
|
|
|
output_text = gr.Textbox(label="Game Result", interactive=False) |
|
|
output_score = gr.Number(label="Similarity Score", interactive=False) |
|
|
|
|
|
submit_btn.click(check_answer, inputs=[user_input], outputs=[output_text, output_score]) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch() |
|
|
|