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()