Download app.py from christyoc1987/WordVector: direct link, hf CLI and curl.
- Browser
- Download file 2.47 kB
-
https://huggingface.co/christyoc1987/WordVector/resolve/main/app.py
- Command line
-
hf download hf://christyoc1987/WordVector/app.py
-
curl -L -o app.py https://huggingface.co/christyoc1987/WordVector/resolve/main/app.py
2.47 kB
| 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() | |