Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoTokenizer, AutoModel
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# Load the tokenizer and model from Hugging Face
|
| 6 |
+
tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
| 7 |
+
model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
| 8 |
+
|
| 9 |
+
def compute_similarity(text1, text2):
|
| 10 |
+
# Tokenize the input texts
|
| 11 |
+
inputs = tokenizer([text1, text2], padding=True, truncation=True, return_tensors='pt')
|
| 12 |
+
|
| 13 |
+
# Get the embeddings
|
| 14 |
+
with torch.no_grad():
|
| 15 |
+
outputs = model(**inputs)
|
| 16 |
+
|
| 17 |
+
# Compute the mean pooling for both embeddings
|
| 18 |
+
embeddings = outputs.last_hidden_state.mean(dim=1)
|
| 19 |
+
|
| 20 |
+
# Compute the cosine similarity
|
| 21 |
+
similarity = torch.nn.functional.cosine_similarity(embeddings[0], embeddings[1], dim=0)
|
| 22 |
+
|
| 23 |
+
return similarity.item()
|
| 24 |
+
|
| 25 |
+
# Define the Gradio interface
|
| 26 |
+
iface = gr.Interface(
|
| 27 |
+
fn=compute_similarity,
|
| 28 |
+
inputs=[gr.inputs.Textbox(lines=2, placeholder="Enter first sentence here..."), gr.inputs.Textbox(lines=2, placeholder="Enter second sentence here...")],
|
| 29 |
+
outputs="text",
|
| 30 |
+
title="Text Similarity Model",
|
| 31 |
+
description="Compute the similarity between two sentences using a pre-trained Hugging Face model."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Launch the Gradio app
|
| 35 |
+
if __name__ == "__main__":
|
| 36 |
+
iface.launch()
|