File size: 1,796 Bytes
959e501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import gradio as gr
import torch
import numpy as np
from sentence_transformers import SentenceTransformer, util

# Load pre-trained transformer model for vectorization
model = SentenceTransformer("all-MiniLM-L6-v2")

# Predefined correct answer (can be a phrase, word, or number)
correct_answer = "AI is powerful"

# Convert correct answer into vector
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
    
    # Vectorize user input
    user_vector = model.encode(user_input, convert_to_tensor=True)
    
    # Compute similarity score (cosine similarity)
    similarity_score = util.pytorch_cos_sim(user_vector, correct_vector).item()
    
    # Set a threshold for winning
    threshold = 0.9
    
    # Game logic: Check if user wins
    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

# Gradio UI
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])

# Launch the Gradio app
if __name__ == "__main__":
    demo.launch()