Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from sentence_transformers import SentenceTransformer, util
|
| 3 |
+
import ast
|
| 4 |
+
|
| 5 |
+
# Load the SentenceTransformer model
|
| 6 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 7 |
+
|
| 8 |
+
def compare_embeddings(query, text_lists):
|
| 9 |
+
# Convert string representation of lists to actual lists
|
| 10 |
+
try:
|
| 11 |
+
lists = ast.literal_eval(text_lists)
|
| 12 |
+
except:
|
| 13 |
+
return "Error: Invalid input format for text lists."
|
| 14 |
+
|
| 15 |
+
# Encode the query
|
| 16 |
+
query_embedding = model.encode(query, convert_to_tensor=True)
|
| 17 |
+
|
| 18 |
+
results = []
|
| 19 |
+
for i, lst in enumerate(lists):
|
| 20 |
+
# Encode the list items
|
| 21 |
+
list_embeddings = model.encode(lst, convert_to_tensor=True)
|
| 22 |
+
|
| 23 |
+
# Calculate cosine similarity
|
| 24 |
+
similarities = util.pytorch_cos_sim(query_embedding, list_embeddings)[0]
|
| 25 |
+
|
| 26 |
+
# Calculate average similarity for the list
|
| 27 |
+
avg_similarity = similarities.mean().item()
|
| 28 |
+
|
| 29 |
+
results.append((i, avg_similarity))
|
| 30 |
+
|
| 31 |
+
# Sort results by similarity score (descending)
|
| 32 |
+
results.sort(key=lambda x: x[1], reverse=True)
|
| 33 |
+
|
| 34 |
+
# Format the output
|
| 35 |
+
output = ""
|
| 36 |
+
for i, score in results:
|
| 37 |
+
output += f"List {i}: Similarity score {score:.4f}\n"
|
| 38 |
+
for j, item in enumerate(lists[i]):
|
| 39 |
+
output += f" Element {j}: {item}\n"
|
| 40 |
+
output += "\n"
|
| 41 |
+
|
| 42 |
+
return output
|
| 43 |
+
|
| 44 |
+
# Create the Gradio interface
|
| 45 |
+
iface = gr.Interface(
|
| 46 |
+
fn=compare_embeddings,
|
| 47 |
+
inputs=[
|
| 48 |
+
gr.Textbox(label="Query"),
|
| 49 |
+
gr.Textbox(label="Text Lists (in format [['', ''], ['', ''], ['', '']])"),
|
| 50 |
+
],
|
| 51 |
+
outputs=gr.Textbox(label="Results"),
|
| 52 |
+
title="Embedding Comparison App",
|
| 53 |
+
description="Compare a query with multiple lists of text and find the most relevant list."
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Launch the app
|
| 57 |
+
iface.launch()
|