Spaces:
Build error
Build error
File size: 2,813 Bytes
b902a75 | 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 72 73 74 75 76 | import gradio as gr
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
# Load sentence transformer model
model = SentenceTransformer("sentence-transformers/all-mpnet-base-v2")
def process_sentences(sentences_text):
sentences = [s.strip() for s in sentences_text.split('\n') if s.strip()]
embeddings = model.encode(sentences).tolist()
preview = "\n".join([f"๐น {s}" for s in sentences])
full_embedding = "\n\n".join([
f"๐น **{s}**:\n{np.round(vec, 4).tolist()}" for s, vec in zip(sentences, embeddings)
])
return preview, full_embedding, sentences, embeddings
def ask_question(question, sentences, embeddings):
if not sentences or not embeddings:
return "โ ๏ธ Please enter sentences first."
q_embedding = model.encode([question])[0]
similarities = cosine_similarity([q_embedding], embeddings)[0]
top_idx = np.argmax(similarities)
top_sentence = sentences[top_idx]
top_score = similarities[top_idx]
score_table = "\n".join([f"- {sentences[i]}: **{similarities[i]:.4f}**" for i in range(len(sentences))])
return f"โ
Closest sentence: **{top_sentence}** (Similarity: {top_score:.4f})\n\n๐ All Scores:\n{score_table}"
# Gradio UI
with gr.Blocks() as demo:
gr.Markdown("## ๐ง Sentence Embedding Search")
with gr.Row():
sentence_input = gr.Textbox(
lines=6,
placeholder="Enter up to 5 sentences (one per line)",
label="Enter Sentences"
)
generate_btn = gr.Button("Generate Embeddings")
sentence_preview = gr.Markdown(label="Entered Sentences")
sentence_embedding_full = gr.Markdown()
sentence_list_state = gr.State()
embedding_state = gr.State()
with gr.Accordion("๐ฝ View Full Embeddings", open=False):
gr.Markdown("Embeddings per sentence:")
# Fix: Update the component instance using its update method
# We pass the current value of sentence_embedding_full as the value to be updated
# sentence_embedding_full.update(value=sentence_embedding_full)
full_display = gr.Markdown() #changed to markdown for this accordion
generate_btn.click(
fn=process_sentences,
inputs=sentence_input,
outputs=[sentence_preview, full_display, sentence_list_state, embedding_state] #change this output to full_display
)
with gr.Row():
question_input = gr.Textbox(placeholder="Ask your question...", label="Semantic Question")
ask_btn = gr.Button("Submit")
question_output = gr.Markdown(label="Answer")
ask_btn.click(
fn=ask_question,
inputs=[question_input, sentence_list_state, embedding_state],
outputs=[question_output]
)
demo.launch() |