Spaces:
Sleeping
Sleeping
update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from sentence_transformers import SentenceTransformer
|
| 3 |
import numpy as np
|
|
@@ -5,122 +63,402 @@ from typing import List, Union
|
|
| 5 |
import spaces # ZeroGPU decorator
|
| 6 |
|
| 7 |
# Load model once at startup
|
| 8 |
-
MODEL_NAME = "
|
| 9 |
-
model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
@spaces.GPU(duration=60) # ZeroGPU: allocate GPU for 60 seconds
|
| 12 |
-
def generate_embeddings(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
"""
|
| 14 |
Generate embeddings for text(s)
|
| 15 |
-
|
| 16 |
Args:
|
| 17 |
texts: Single string or list of strings
|
| 18 |
-
|
|
|
|
| 19 |
Returns:
|
| 20 |
-
List of embedding vectors
|
| 21 |
"""
|
| 22 |
# Handle single string
|
| 23 |
if isinstance(texts, str):
|
| 24 |
texts = [texts]
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
# Generate embeddings
|
| 27 |
embeddings = model.encode(
|
| 28 |
texts,
|
| 29 |
convert_to_numpy=True,
|
| 30 |
-
normalize_embeddings=True, #
|
| 31 |
-
show_progress_bar=False
|
|
|
|
| 32 |
)
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# Convert to list for JSON serialization
|
| 35 |
return embeddings.tolist()
|
| 36 |
|
| 37 |
-
def batch_generate(texts_input: str) -> str:
|
| 38 |
"""
|
| 39 |
Gradio interface for batch embedding generation
|
| 40 |
Expects newline-separated texts
|
| 41 |
"""
|
| 42 |
if not texts_input.strip():
|
| 43 |
-
return "Error: Please provide at least one text"
|
| 44 |
-
|
| 45 |
texts = [t.strip() for t in texts_input.split('\n') if t.strip()]
|
| 46 |
-
|
| 47 |
try:
|
| 48 |
-
embeddings = generate_embeddings(texts)
|
| 49 |
-
|
| 50 |
-
result = f"Generated {len(embeddings)} embeddings\n"
|
| 51 |
-
result += f"Dimensions: {len(embeddings[0])}\n
|
|
|
|
| 52 |
result += "First embedding preview:\n"
|
| 53 |
-
result +=
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
return result
|
| 56 |
except Exception as e:
|
| 57 |
-
return f"Error: {str(e)}"
|
| 58 |
|
| 59 |
# Create Gradio interface
|
| 60 |
-
with gr.Blocks(title="FairFate Embeddings API") as demo:
|
| 61 |
gr.Markdown("""
|
| 62 |
-
# FairFate Embeddings API
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
- **Dimensions
|
| 66 |
-
- **
|
| 67 |
-
- **
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
**Endpoint:** `https://your-username-fairfate-embeddings.hf.space/api/predict`
|
| 72 |
-
|
| 73 |
-
**Request:**
|
| 74 |
-
```json
|
| 75 |
-
{
|
| 76 |
-
"data": ["Your text here", "Another text"]
|
| 77 |
-
}
|
| 78 |
-
```
|
| 79 |
-
|
| 80 |
-
**Response:**
|
| 81 |
-
```json
|
| 82 |
-
{
|
| 83 |
-
"data": [[[0.123, -0.456, ...]], [[0.789, -0.012, ...]]]
|
| 84 |
-
}
|
| 85 |
-
```
|
| 86 |
""")
|
| 87 |
-
|
| 88 |
-
with gr.Tab("
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
)
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
submit_btn.click(batch_generate, inputs=input_text, outputs=output_text)
|
| 97 |
-
|
| 98 |
-
with gr.Tab("API Documentation"):
|
| 99 |
gr.Markdown("""
|
| 100 |
-
|
|
|
|
| 101 |
```python
|
| 102 |
import requests
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
response = requests.post(
|
| 105 |
-
|
| 106 |
-
json={
|
|
|
|
|
|
|
|
|
|
| 107 |
)
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
| 109 |
```
|
| 110 |
-
|
| 111 |
-
### JavaScript/TypeScript Example
|
| 112 |
```typescript
|
| 113 |
-
const
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
const result = await response.json();
|
| 122 |
const embeddings = result.data[0];
|
| 123 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
# Launch with API enabled
|
| 126 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
Hugging Face's logo
|
| 2 |
+
Hugging Face
|
| 3 |
+
Models
|
| 4 |
+
Datasets
|
| 5 |
+
Spaces
|
| 6 |
+
Community
|
| 7 |
+
Docs
|
| 8 |
+
Pricing
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
TiniThingsInc
|
| 12 |
+
/
|
| 13 |
+
README.md
|
| 14 |
+
|
| 15 |
+
like
|
| 16 |
+
0
|
| 17 |
+
Sentence Similarity
|
| 18 |
+
sentence-transformers
|
| 19 |
+
|
| 20 |
+
9 languages
|
| 21 |
+
code
|
| 22 |
+
semantic-search
|
| 23 |
+
multilingual
|
| 24 |
+
ttrpg
|
| 25 |
+
classification
|
| 26 |
+
embeddings
|
| 27 |
+
|
| 28 |
+
License:
|
| 29 |
+
apache-2.0
|
| 30 |
+
Model card
|
| 31 |
+
Files and versions
|
| 32 |
+
xet
|
| 33 |
+
Community
|
| 34 |
+
Settings
|
| 35 |
+
README.md
|
| 36 |
+
/
|
| 37 |
+
app.py
|
| 38 |
+
|
| 39 |
+
TiniThingsInc's picture
|
| 40 |
+
TiniThingsInc
|
| 41 |
+
changing to qwen
|
| 42 |
+
22010e1
|
| 43 |
+
verified
|
| 44 |
+
about 23 hours ago
|
| 45 |
+
raw
|
| 46 |
+
|
| 47 |
+
Copy download link
|
| 48 |
+
history
|
| 49 |
+
blame
|
| 50 |
+
edit
|
| 51 |
+
delete
|
| 52 |
+
|
| 53 |
+
16.7 kB
|
| 54 |
+
"""
|
| 55 |
+
FairFate Embeddings API - Qwen3-Embedding-0.6B
|
| 56 |
+
Multilingual semantic embeddings for tabletop RPG product classification
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
import gradio as gr
|
| 60 |
from sentence_transformers import SentenceTransformer
|
| 61 |
import numpy as np
|
|
|
|
| 63 |
import spaces # ZeroGPU decorator
|
| 64 |
|
| 65 |
# Load model once at startup
|
| 66 |
+
MODEL_NAME = "Qwen/Qwen3-Embedding-0.6B"
|
| 67 |
+
print(f"๐ Loading model: {MODEL_NAME}")
|
| 68 |
+
model = SentenceTransformer(MODEL_NAME, trust_remote_code=True)
|
| 69 |
+
print(f"โ
Model loaded successfully")
|
| 70 |
+
print(f" Dimensions: {model.get_sentence_embedding_dimension()}")
|
| 71 |
+
print(f" Max Seq Length: {model.max_seq_length}")
|
| 72 |
+
|
| 73 |
+
# Optional: Add instruction prefix for RPG domain (improves accuracy by 1-5%)
|
| 74 |
+
INSTRUCTION_PREFIX = "Represent this tabletop RPG product for semantic search: "
|
| 75 |
|
| 76 |
@spaces.GPU(duration=60) # ZeroGPU: allocate GPU for 60 seconds
|
| 77 |
+
def generate_embeddings(
|
| 78 |
+
texts: Union[str, List[str]],
|
| 79 |
+
use_instruction: bool = True,
|
| 80 |
+
output_dimensions: int = 1024
|
| 81 |
+
) -> List[List[float]]:
|
| 82 |
"""
|
| 83 |
Generate embeddings for text(s)
|
|
|
|
| 84 |
Args:
|
| 85 |
texts: Single string or list of strings
|
| 86 |
+
use_instruction: Whether to prepend instruction prefix (recommended)
|
| 87 |
+
output_dimensions: Output embedding size (32-1024)
|
| 88 |
Returns:
|
| 89 |
+
List of embedding vectors
|
| 90 |
"""
|
| 91 |
# Handle single string
|
| 92 |
if isinstance(texts, str):
|
| 93 |
texts = [texts]
|
| 94 |
+
|
| 95 |
+
# Add instruction prefix if enabled (Qwen3 is instruction-aware)
|
| 96 |
+
if use_instruction:
|
| 97 |
+
texts = [INSTRUCTION_PREFIX + text for text in texts]
|
| 98 |
+
|
| 99 |
# Generate embeddings
|
| 100 |
embeddings = model.encode(
|
| 101 |
texts,
|
| 102 |
convert_to_numpy=True,
|
| 103 |
+
normalize_embeddings=True, # L2 normalize for cosine similarity
|
| 104 |
+
show_progress_bar=False,
|
| 105 |
+
batch_size=32
|
| 106 |
)
|
| 107 |
+
|
| 108 |
+
# Resize embeddings if needed (MRL - Multilingual Representation Learning)
|
| 109 |
+
if output_dimensions != 1024:
|
| 110 |
+
# Qwen3 supports flexible dimensions (32-1024)
|
| 111 |
+
# Simply truncate for smaller dimensions
|
| 112 |
+
embeddings = embeddings[:, :output_dimensions]
|
| 113 |
+
|
| 114 |
# Convert to list for JSON serialization
|
| 115 |
return embeddings.tolist()
|
| 116 |
|
| 117 |
+
def batch_generate(texts_input: str, use_instruction: bool, output_dims: int) -> str:
|
| 118 |
"""
|
| 119 |
Gradio interface for batch embedding generation
|
| 120 |
Expects newline-separated texts
|
| 121 |
"""
|
| 122 |
if not texts_input.strip():
|
| 123 |
+
return "โ Error: Please provide at least one text"
|
| 124 |
+
|
| 125 |
texts = [t.strip() for t in texts_input.split('\n') if t.strip()]
|
| 126 |
+
|
| 127 |
try:
|
| 128 |
+
embeddings = generate_embeddings(texts, use_instruction, output_dims)
|
| 129 |
+
|
| 130 |
+
result = f"โ
Generated {len(embeddings)} embeddings\n"
|
| 131 |
+
result += f"๐ Dimensions: {len(embeddings[0])}\n"
|
| 132 |
+
result += f"๐ Languages: 100+ supported\n\n"
|
| 133 |
result += "First embedding preview:\n"
|
| 134 |
+
result += f"[{', '.join(f'{x:.3f}' for x in embeddings[0][:10])}...]\n"
|
| 135 |
+
|
| 136 |
+
return result
|
| 137 |
+
except Exception as e:
|
| 138 |
+
return f"โ Error: {str(e)}"
|
| 139 |
+
|
| 140 |
+
def calculate_all_similarities(emb1: np.ndarray, emb2: np.ndarray) -> dict:
|
| 141 |
+
"""
|
| 142 |
+
Calculate comprehensive similarity metrics between two embeddings
|
| 143 |
+
"""
|
| 144 |
+
# Cosine Similarity (for normalized vectors, just dot product)
|
| 145 |
+
cosine = float(np.dot(emb1, emb2))
|
| 146 |
+
|
| 147 |
+
# Euclidean Distance
|
| 148 |
+
euclidean_dist = float(np.linalg.norm(emb1 - emb2))
|
| 149 |
+
euclidean_sim = 1 / (1 + euclidean_dist)
|
| 150 |
+
|
| 151 |
+
# Jaccard Similarity (min/max interpretation for continuous vectors)
|
| 152 |
+
intersection = np.sum(np.minimum(np.abs(emb1), np.abs(emb2)))
|
| 153 |
+
union = np.sum(np.maximum(np.abs(emb1), np.abs(emb2)))
|
| 154 |
+
jaccard = float(intersection / union if union > 0 else 0)
|
| 155 |
+
|
| 156 |
+
# Sorensen-Dice Coefficient
|
| 157 |
+
intersection = np.sum(np.minimum(np.abs(emb1), np.abs(emb2)))
|
| 158 |
+
sum_magnitudes = np.sum(np.abs(emb1)) + np.sum(np.abs(emb2))
|
| 159 |
+
sorensen_dice = float(2 * intersection / sum_magnitudes if sum_magnitudes > 0 else 0)
|
| 160 |
+
|
| 161 |
+
# Manhattan Distance
|
| 162 |
+
manhattan = float(np.sum(np.abs(emb1 - emb2)))
|
| 163 |
+
|
| 164 |
+
# Pearson Correlation
|
| 165 |
+
pearson = float(np.corrcoef(emb1, emb2)[0, 1])
|
| 166 |
+
|
| 167 |
+
return {
|
| 168 |
+
'cosine': cosine,
|
| 169 |
+
'euclidean_distance': euclidean_dist,
|
| 170 |
+
'euclidean_similarity': euclidean_sim,
|
| 171 |
+
'jaccard': jaccard,
|
| 172 |
+
'sorensen_dice': sorensen_dice,
|
| 173 |
+
'manhattan': manhattan,
|
| 174 |
+
'pearson': pearson
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
def interpret_similarity(score: float, metric: str) -> tuple[str, str]:
|
| 178 |
+
"""
|
| 179 |
+
Interpret similarity score with emoji and description
|
| 180 |
+
Returns: (emoji, description)
|
| 181 |
+
"""
|
| 182 |
+
if metric in ['cosine', 'jaccard', 'sorensen_dice', 'euclidean_similarity']:
|
| 183 |
+
if score > 0.9:
|
| 184 |
+
return '๐ข', 'Nearly Identical'
|
| 185 |
+
elif score > 0.7:
|
| 186 |
+
return '๐ข', 'Very Similar'
|
| 187 |
+
elif score > 0.5:
|
| 188 |
+
return '๐ก', 'Moderately Similar'
|
| 189 |
+
elif score > 0.3:
|
| 190 |
+
return '๐ ', 'Somewhat Similar'
|
| 191 |
+
else:
|
| 192 |
+
return '๐ด', 'Different'
|
| 193 |
+
elif metric == 'pearson':
|
| 194 |
+
if score > 0.9:
|
| 195 |
+
return '๐ข', 'Strong Positive Correlation'
|
| 196 |
+
elif score > 0.7:
|
| 197 |
+
return '๐ก', 'Moderate Positive Correlation'
|
| 198 |
+
elif score > 0.3:
|
| 199 |
+
return '๐ ', 'Weak Positive Correlation'
|
| 200 |
+
elif score > -0.3:
|
| 201 |
+
return 'โช', 'No Correlation'
|
| 202 |
+
elif score > -0.7:
|
| 203 |
+
return '๐ ', 'Weak Negative Correlation'
|
| 204 |
+
elif score > -0.9:
|
| 205 |
+
return '๐ก', 'Moderate Negative Correlation'
|
| 206 |
+
else:
|
| 207 |
+
return '๐ด', 'Strong Negative Correlation'
|
| 208 |
+
else:
|
| 209 |
+
return 'โช', 'Unknown'
|
| 210 |
+
|
| 211 |
+
def calculate_similarity(text1: str, text2: str, use_instruction: bool) -> str:
|
| 212 |
+
"""
|
| 213 |
+
Calculate comprehensive similarity metrics between two texts
|
| 214 |
+
"""
|
| 215 |
+
if not text1.strip() or not text2.strip():
|
| 216 |
+
return "โ Error: Please provide both texts"
|
| 217 |
+
|
| 218 |
+
try:
|
| 219 |
+
embeddings = generate_embeddings([text1, text2], use_instruction)
|
| 220 |
+
|
| 221 |
+
# Calculate all similarity metrics
|
| 222 |
+
emb1 = np.array(embeddings[0])
|
| 223 |
+
emb2 = np.array(embeddings[1])
|
| 224 |
+
metrics = calculate_all_similarities(emb1, emb2)
|
| 225 |
+
|
| 226 |
+
# Build result string
|
| 227 |
+
result = "๐ **Comprehensive Similarity Analysis**\n\n"
|
| 228 |
+
|
| 229 |
+
# Cosine Similarity (Primary)
|
| 230 |
+
emoji, interpretation = interpret_similarity(metrics['cosine'], 'cosine')
|
| 231 |
+
result += f"**Cosine Similarity:** {emoji} {metrics['cosine']:.4f}\n"
|
| 232 |
+
result += f"โโ {interpretation}\n\n"
|
| 233 |
+
|
| 234 |
+
# Jaccard Similarity
|
| 235 |
+
emoji, interpretation = interpret_similarity(metrics['jaccard'], 'jaccard')
|
| 236 |
+
result += f"**Jaccard Similarity:** {emoji} {metrics['jaccard']:.4f}\n"
|
| 237 |
+
result += f"โโ {interpretation}\n\n"
|
| 238 |
+
|
| 239 |
+
# Sorensen-Dice Coefficient
|
| 240 |
+
emoji, interpretation = interpret_similarity(metrics['sorensen_dice'], 'sorensen_dice')
|
| 241 |
+
result += f"**Sรธrensen-Dice:** {emoji} {metrics['sorensen_dice']:.4f}\n"
|
| 242 |
+
result += f"โโ {interpretation}\n\n"
|
| 243 |
+
|
| 244 |
+
# Euclidean Distance & Similarity
|
| 245 |
+
result += f"**Euclidean Distance:** {metrics['euclidean_distance']:.4f}\n"
|
| 246 |
+
emoji, interpretation = interpret_similarity(metrics['euclidean_similarity'], 'euclidean_similarity')
|
| 247 |
+
result += f"**Euclidean Similarity:** {emoji} {metrics['euclidean_similarity']:.4f}\n"
|
| 248 |
+
result += f"โโ {interpretation}\n\n"
|
| 249 |
+
|
| 250 |
+
# Manhattan Distance
|
| 251 |
+
result += f"**Manhattan Distance:** {metrics['manhattan']:.2f}\n\n"
|
| 252 |
+
|
| 253 |
+
# Pearson Correlation
|
| 254 |
+
emoji, interpretation = interpret_similarity(metrics['pearson'], 'pearson')
|
| 255 |
+
result += f"**Pearson Correlation:** {emoji} {metrics['pearson']:.4f}\n"
|
| 256 |
+
result += f"โโ {interpretation}\n\n"
|
| 257 |
+
|
| 258 |
+
# Overall assessment (based on cosine as primary)
|
| 259 |
+
result += "---\n**Overall Assessment:**\n"
|
| 260 |
+
cosine_emoji, cosine_interpretation = interpret_similarity(metrics['cosine'], 'cosine')
|
| 261 |
+
result += f"{cosine_emoji} {cosine_interpretation} (Cosine: {metrics['cosine']:.4f})"
|
| 262 |
+
|
| 263 |
return result
|
| 264 |
except Exception as e:
|
| 265 |
+
return f"โ Error: {str(e)}"
|
| 266 |
|
| 267 |
# Create Gradio interface
|
| 268 |
+
with gr.Blocks(title="FairFate Embeddings API - Qwen3", theme=gr.themes.Soft()) as demo:
|
| 269 |
gr.Markdown("""
|
| 270 |
+
# ๐ฒ FairFate Embeddings API
|
| 271 |
+
**Powered by Qwen3-Embedding-0.6B** - #1 Multilingual Embedding Model
|
| 272 |
+
- ๐ **100+ Languages** (English, Spanish, French, German, Chinese, Japanese, etc.)
|
| 273 |
+
- ๐ **1024 Dimensions** (flexible 32-1024)
|
| 274 |
+
- ๐ **32K Context** (massive text support)
|
| 275 |
+
- โก **Instruction-Aware** (optimized for RPG content)
|
| 276 |
+
- ๐ **#1 on MTEB** Multilingual Leaderboard
|
| 277 |
+
Perfect for: Product classification, semantic search, recommendations, multilingual matching
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
""")
|
| 279 |
+
|
| 280 |
+
with gr.Tab("๐ฎ Generate Embeddings"):
|
| 281 |
+
gr.Markdown("""
|
| 282 |
+
Generate semantic embeddings for product descriptions, titles, or any text.
|
| 283 |
+
Enter one text per line for batch processing.
|
| 284 |
+
""")
|
| 285 |
+
|
| 286 |
+
with gr.Row():
|
| 287 |
+
with gr.Column():
|
| 288 |
+
input_text = gr.Textbox(
|
| 289 |
+
label="Input Texts (one per line)",
|
| 290 |
+
placeholder="Example:\nStorm King's Thunder - Epic D&D 5E adventure\nCurse of Strahd - Gothic horror campaign\nPathfinder 2E Core Rulebook",
|
| 291 |
+
lines=8
|
| 292 |
+
)
|
| 293 |
+
use_inst = gr.Checkbox(label="Use instruction prefix (recommended for RPG content)", value=True)
|
| 294 |
+
output_dims = gr.Slider(
|
| 295 |
+
minimum=32, maximum=1024, value=1024, step=32,
|
| 296 |
+
label="Output Dimensions"
|
| 297 |
+
)
|
| 298 |
+
submit_btn = gr.Button("Generate Embeddings", variant="primary")
|
| 299 |
+
|
| 300 |
+
with gr.Column():
|
| 301 |
+
output_text = gr.Textbox(label="Results", lines=12)
|
| 302 |
+
|
| 303 |
+
submit_btn.click(batch_generate, inputs=[input_text, use_inst, output_dims], outputs=output_text)
|
| 304 |
+
|
| 305 |
+
gr.Examples(
|
| 306 |
+
examples=[
|
| 307 |
+
["D&D 5E epic fantasy adventure with dragons and dungeons", True, 1024],
|
| 308 |
+
["Cyberpunk shadowrun detective noir campaign\nPathfinder 2E beginner box starter set\nCall of Cthulhu horror investigation", True, 1024],
|
| 309 |
+
],
|
| 310 |
+
inputs=[input_text, use_inst, output_dims],
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
with gr.Tab("๐ Similarity Calculator"):
|
| 314 |
+
gr.Markdown("""
|
| 315 |
+
**Comprehensive Similarity Analysis** - Compare two texts using multiple metrics:
|
| 316 |
+
- **Cosine Similarity**: Angle between vectors (best for semantic meaning)
|
| 317 |
+
- **Jaccard Similarity**: Intersection over union (set-like comparison)
|
| 318 |
+
- **Sรธrensen-Dice**: Weighted intersection (emphasizes shared features)
|
| 319 |
+
- **Euclidean Distance/Similarity**: Straight-line distance in vector space
|
| 320 |
+
- **Manhattan Distance**: Grid-based distance (L1 norm)
|
| 321 |
+
- **Pearson Correlation**: Linear relationship between vectors
|
| 322 |
+
Perfect for duplicate detection, classification testing, and understanding product relationships!
|
| 323 |
+
""")
|
| 324 |
+
|
| 325 |
+
with gr.Row():
|
| 326 |
+
with gr.Column():
|
| 327 |
+
text1 = gr.Textbox(
|
| 328 |
+
label="First Text",
|
| 329 |
+
placeholder="Storm King's Thunder - Giant-themed D&D adventure",
|
| 330 |
+
lines=3
|
| 331 |
+
)
|
| 332 |
+
text2 = gr.Textbox(
|
| 333 |
+
label="Second Text",
|
| 334 |
+
placeholder="Princes of the Apocalypse - Elemental evil campaign",
|
| 335 |
+
lines=3
|
| 336 |
+
)
|
| 337 |
+
use_inst_sim = gr.Checkbox(label="Use instruction prefix", value=True)
|
| 338 |
+
calc_btn = gr.Button("Calculate Similarity", variant="primary")
|
| 339 |
+
|
| 340 |
+
with gr.Column():
|
| 341 |
+
similarity_output = gr.Textbox(label="Similarity Result", lines=8)
|
| 342 |
+
|
| 343 |
+
calc_btn.click(calculate_similarity, inputs=[text1, text2, use_inst_sim], outputs=similarity_output)
|
| 344 |
+
|
| 345 |
+
gr.Examples(
|
| 346 |
+
examples=[
|
| 347 |
+
["D&D 5E fantasy adventure", "Dungeons and Dragons fifth edition module", True],
|
| 348 |
+
["Horror investigation mystery", "Comedy fantasy lighthearted fun", True],
|
| 349 |
+
["Pathfinder 2E rulebook", "D&D 5E Player's Handbook", True],
|
| 350 |
+
],
|
| 351 |
+
inputs=[text1, text2, use_inst_sim],
|
| 352 |
)
|
| 353 |
+
|
| 354 |
+
with gr.Tab("๐ API Documentation"):
|
|
|
|
|
|
|
|
|
|
| 355 |
gr.Markdown("""
|
| 356 |
+
## ๐ Quick Start
|
| 357 |
+
### Python
|
| 358 |
```python
|
| 359 |
import requests
|
| 360 |
+
import numpy as np
|
| 361 |
+
url = "https://YOUR_USERNAME-fairfate-embeddings.hf.space/api/predict"
|
| 362 |
+
# Generate embeddings
|
| 363 |
+
texts = [
|
| 364 |
+
"Storm King's Thunder - Epic D&D 5E adventure",
|
| 365 |
+
"Curse of Strahd - Gothic horror campaign"
|
| 366 |
+
]
|
| 367 |
response = requests.post(
|
| 368 |
+
url,
|
| 369 |
+
json={
|
| 370 |
+
"data": [texts, True, 1024], # [texts, use_instruction, dimensions]
|
| 371 |
+
"fn_index": 0 # Index of generate_embeddings function
|
| 372 |
+
}
|
| 373 |
)
|
| 374 |
+
result = response.json()
|
| 375 |
+
embeddings = result["data"][0]
|
| 376 |
+
print(f"Generated {len(embeddings)} embeddings")
|
| 377 |
+
print(f"Dimensions: {len(embeddings[0])}")
|
| 378 |
```
|
| 379 |
+
### TypeScript/JavaScript
|
|
|
|
| 380 |
```typescript
|
| 381 |
+
const url = 'https://YOUR_USERNAME-fairfate-embeddings.hf.space/api/predict';
|
| 382 |
+
const response = await fetch(url, {
|
| 383 |
+
method: 'POST',
|
| 384 |
+
headers: { 'Content-Type': 'application/json' },
|
| 385 |
+
body: JSON.stringify({
|
| 386 |
+
data: [
|
| 387 |
+
["Your text here", "Another text"],
|
| 388 |
+
true, // use_instruction
|
| 389 |
+
1024 // output_dimensions
|
| 390 |
+
],
|
| 391 |
+
fn_index: 0
|
| 392 |
+
})
|
| 393 |
+
});
|
| 394 |
const result = await response.json();
|
| 395 |
const embeddings = result.data[0];
|
| 396 |
```
|
| 397 |
+
### cURL
|
| 398 |
+
```bash
|
| 399 |
+
curl -X POST \\
|
| 400 |
+
https://YOUR_USERNAME-fairfate-embeddings.hf.space/api/predict \\
|
| 401 |
+
-H "Content-Type: application/json" \\
|
| 402 |
+
-d '{
|
| 403 |
+
"data": [["Your text here"], true, 1024],
|
| 404 |
+
"fn_index": 0
|
| 405 |
+
}'
|
| 406 |
+
```
|
| 407 |
+
## ๐ Parameters
|
| 408 |
+
| Parameter | Type | Default | Description |
|
| 409 |
+
|-----------|------|---------|-------------|
|
| 410 |
+
| `texts` | string[] | required | Array of texts to embed |
|
| 411 |
+
| `use_instruction` | boolean | true | Add instruction prefix (improves accuracy) |
|
| 412 |
+
| `output_dimensions` | number | 1024 | Output size (32-1024) |
|
| 413 |
+
## ๐ฏ Use Cases
|
| 414 |
+
- **Product Classification**: Auto-tag by genre, system, theme
|
| 415 |
+
- **Semantic Search**: Find by meaning, not keywords
|
| 416 |
+
- **Recommendations**: "Similar products"
|
| 417 |
+
- **Duplicate Detection**: Find similar listings
|
| 418 |
+
- **Multilingual Matching**: Cross-language similarity
|
| 419 |
+
## โก Performance
|
| 420 |
+
| Batch Size | GPU Throughput | CPU Throughput |
|
| 421 |
+
|------------|----------------|----------------|
|
| 422 |
+
| 1 | ~800/sec | ~80/sec |
|
| 423 |
+
| 32 | ~4000/sec | ~250/sec |
|
| 424 |
+
## ๐ Supported Languages
|
| 425 |
+
English, Spanish, French, German, Italian, Portuguese, Russian, Polish, Dutch, Czech,
|
| 426 |
+
Chinese, Japanese, Korean, Arabic, Hebrew, Hindi, Thai, Vietnamese, Indonesian,
|
| 427 |
+
Turkish, Swedish, Norwegian, Danish, Finnish, Greek, Romanian, Hungarian, and 80+ more!
|
| 428 |
+
## ๐ Citation
|
| 429 |
+
```bibtex
|
| 430 |
+
@misc{qwen3embedding2025,
|
| 431 |
+
title={Qwen3 Embedding},
|
| 432 |
+
author={Alibaba Cloud},
|
| 433 |
+
year={2025},
|
| 434 |
+
url={https://github.com/QwenLM/Qwen3-Embedding}
|
| 435 |
+
}
|
| 436 |
+
```
|
| 437 |
""")
|
| 438 |
+
|
| 439 |
+
with gr.Tab("โน๏ธ Model Info"):
|
| 440 |
+
gr.Markdown(f"""
|
| 441 |
+
## Model Details
|
| 442 |
+
- **Model:** {MODEL_NAME}
|
| 443 |
+
- **Dimensions:** {model.get_sentence_embedding_dimension()}
|
| 444 |
+
- **Max Sequence Length:** {model.max_seq_length} tokens
|
| 445 |
+
- **Languages:** 100+
|
| 446 |
+
- **License:** Apache 2.0
|
| 447 |
+
- **Normalization:** L2 normalized (ready for cosine similarity)
|
| 448 |
+
## Advantages
|
| 449 |
+
โ
**Best Multilingual Performance** - #1 on MTEB leaderboard
|
| 450 |
+
โ
**Massive Context** - 32K tokens (vs 512 for most models)
|
| 451 |
+
โ
**Instruction-Aware** - Can customize for specific domains
|
| 452 |
+
โ
**Flexible Dimensions** - 32 to 1024 dimensions
|
| 453 |
+
โ
**Code-Switching** - Handles mixed-language text
|
| 454 |
+
## Resources
|
| 455 |
+
- [Model Card](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B)
|
| 456 |
+
- [GitHub](https://github.com/QwenLM/Qwen3-Embedding)
|
| 457 |
+
- [Blog Post](https://qwenlm.github.io/blog/qwen3-embedding/)
|
| 458 |
+
- [MTEB Leaderboard](https://huggingface.co/spaces/mteb/leaderboard)
|
| 459 |
+
""")
|
| 460 |
+
|
| 461 |
# Launch with API enabled
|
| 462 |
+
if __name__ == "__main__":
|
| 463 |
+
demo.launch()
|
| 464 |
+
|