Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,28 +1,49 @@
|
|
1 |
import gradio as gr
|
2 |
import requests
|
|
|
3 |
import os
|
4 |
|
|
|
5 |
API_URL = "https://api-inference.huggingface.co/models/sentence-transformers/paraphrase-mpnet-base-v2"
|
6 |
-
|
7 |
-
|
8 |
-
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
9 |
|
10 |
def get_embedding(text):
|
11 |
-
response = requests.post(
|
12 |
-
API_URL,
|
13 |
-
headers=headers,
|
14 |
-
json={"inputs": text}
|
15 |
-
)
|
16 |
if response.status_code == 200:
|
17 |
-
return response.json()
|
18 |
else:
|
19 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
|
|
21 |
iface = gr.Interface(
|
22 |
-
fn=
|
23 |
-
inputs=
|
|
|
|
|
|
|
24 |
outputs="json",
|
25 |
-
title="
|
|
|
26 |
)
|
27 |
|
28 |
-
iface.launch()
|
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
+
import numpy as np
|
4 |
import os
|
5 |
|
6 |
+
# إعدادات الموديل
|
7 |
API_URL = "https://api-inference.huggingface.co/models/sentence-transformers/paraphrase-mpnet-base-v2"
|
8 |
+
HEADERS = {"Authorization": f"Bearer {os.getenv('HUGGINGFACE_API_TOKEN')}"}
|
|
|
|
|
9 |
|
10 |
def get_embedding(text):
|
11 |
+
response = requests.post(API_URL, headers=HEADERS, json={"inputs": text})
|
|
|
|
|
|
|
|
|
12 |
if response.status_code == 200:
|
13 |
+
return np.array(response.json()[0])
|
14 |
else:
|
15 |
+
return None
|
16 |
+
|
17 |
+
def cosine_similarity(vec1, vec2):
|
18 |
+
if vec1 is None or vec2 is None:
|
19 |
+
return "❌ Error fetching embeddings"
|
20 |
+
dot = np.dot(vec1, vec2)
|
21 |
+
norm_a = np.linalg.norm(vec1)
|
22 |
+
norm_b = np.linalg.norm(vec2)
|
23 |
+
if norm_a == 0 or norm_b == 0:
|
24 |
+
return 0.0
|
25 |
+
return float(dot / (norm_a * norm_b))
|
26 |
+
|
27 |
+
def compare_sentences(sentence1, sentence2):
|
28 |
+
embedding1 = get_embedding(sentence1)
|
29 |
+
embedding2 = get_embedding(sentence2)
|
30 |
+
similarity = cosine_similarity(embedding1, embedding2)
|
31 |
+
return {
|
32 |
+
"Sentence 1": sentence1,
|
33 |
+
"Sentence 2": sentence2,
|
34 |
+
"Cosine Similarity": round(similarity, 4) if isinstance(similarity, float) else similarity
|
35 |
+
}
|
36 |
|
37 |
+
# واجهة Gradio
|
38 |
iface = gr.Interface(
|
39 |
+
fn=compare_sentences,
|
40 |
+
inputs=[
|
41 |
+
gr.Textbox(label="Sentence 1", placeholder="Enter the first sentence..."),
|
42 |
+
gr.Textbox(label="Sentence 2", placeholder="Enter the second sentence...")
|
43 |
+
],
|
44 |
outputs="json",
|
45 |
+
title="Sentence Similarity using HuggingFace API",
|
46 |
+
description="Compares two sentences using the `paraphrase-mpnet-base-v2` model and returns the cosine similarity."
|
47 |
)
|
48 |
|
49 |
+
iface.launch(share=True)
|