File size: 2,470 Bytes
c235095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import gradio as gr
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np

# Load model
model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')

def process_words(word_input):
    words = [w.strip() for w in word_input.split(',') if w.strip()]
    embeddings = model.encode(words).tolist()
    
    short_preview = "\n".join([f"๐Ÿ”น {word}" for word in words])
    
    full_embedding_display = "\n\n".join(
        [f"๐Ÿ”น **{word}**: {np.round(vec, 4).tolist()}" for word, vec in zip(words, embeddings)]
    )
    
    return short_preview, full_embedding_display, words, embeddings

def ask_question(question, words, embeddings):
    if not words or not embeddings:
        return "โš ๏ธ Please enter words first."
    
    q_embedding = model.encode([question])[0]
    similarities = cosine_similarity([q_embedding], embeddings)[0]

    top_n = 3
    top_indices = np.argsort(similarities)[::-1][:top_n]
    
    top_matches = "\n".join(
        [f"โœ… **{words[i]}** (Similarity: {similarities[i]:.4f})" for i in top_indices]
    )
    
    full_scores = "\n".join(
        [f"- {word}: {similarities[i]:.4f}" for i, word in enumerate(words)]
    )
    
    return f"๐Ÿ” **Top Matches:**\n{top_matches}\n\n๐Ÿ“Š **All Similarities:**\n{full_scores}"

with gr.Blocks() as demo:
    gr.Markdown("## ๐Ÿ” Semantic Search on Custom Word Embeddings")
    
    with gr.Row():
        word_input = gr.Textbox(placeholder="e.g., jesus, AI, christ, bird", label="Enter Words (comma-separated)")
        generate_btn = gr.Button("Generate Embeddings")

    preview = gr.Markdown(label="Words Entered")
    full_embedding_output = gr.Markdown(label="Embeddings")
    word_list_state = gr.State()
    embedding_state = gr.State()

    with gr.Accordion("๐Ÿ”ฝ View Full Embeddings", open=False):
        full_display = gr.Markdown()

    generate_btn.click(fn=process_words, 
                       inputs=word_input, 
                       outputs=[preview, full_display, word_list_state, embedding_state])

    with gr.Row():
        question_input = gr.Textbox(placeholder="Ask a question here...", label="Semantic Question")
        ask_btn = gr.Button("Submit")

    answer_output = gr.Markdown(label="Answer")

    ask_btn.click(fn=ask_question, 
                  inputs=[question_input, word_list_state, embedding_state], 
                  outputs=answer_output)

demo.launch()