Sentance_Vector / SentanceVector.py
christyoc1987's picture
Create SentanceVector.py
b902a75 verified
Raw History Blame Contribute Delete
2.81 kB
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()