Spaces:
Sleeping
Sleeping
File size: 12,243 Bytes
56f66cf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
import gradio as gr
import torch
import numpy as np
from transformers import AutoTokenizer, AutoModel
from typing import List, Union
import json
import logging
import os
from sentence_transformers import SentenceTransformer
import time
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Model configuration
MODEL_NAME = "Qwen/Qwen3-Embedding-0.6B" # Qwen3 Embedding model
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
MAX_LENGTH = 512
# Global variables for model and tokenizer
model = None
tokenizer = None
sentence_transformer = None
def load_model():
"""Load the Qwen model and tokenizer"""
global model, tokenizer, sentence_transformer
try:
logger.info(f"Loading model on device: {DEVICE}")
# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
model = AutoModel.from_pretrained(
MODEL_NAME,
trust_remote_code=True,
torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
device_map="auto" if DEVICE == "cuda" else None
)
if DEVICE == "cpu":
model = model.to(DEVICE)
model.eval()
# Also load sentence transformer as backup
sentence_transformer = SentenceTransformer('all-MiniLM-L6-v2')
logger.info("Model loaded successfully")
return True
except Exception as e:
logger.error(f"Error loading model: {str(e)}")
return False
def generate_embeddings(texts: Union[str, List[str]]) -> Union[List[float], List[List[float]]]:
"""Generate embeddings for input text(s) using Qwen3 Embedding model"""
global model, tokenizer, sentence_transformer
try:
# Ensure texts is a list
if isinstance(texts, str):
texts = [texts]
single_text = True
else:
single_text = False
# Truncate texts if too long
texts = [text[:MAX_LENGTH] for text in texts]
embeddings = []
for text in texts:
try:
# Method 1: Try using the Qwen3 embedding model directly
if model and tokenizer:
inputs = tokenizer(
text,
return_tensors="pt",
padding=True,
truncation=True,
max_length=MAX_LENGTH
).to(DEVICE)
with torch.no_grad():
outputs = model(**inputs)
# For Qwen3 embedding model, use the pooled output
if hasattr(outputs, 'pooler_output') and outputs.pooler_output is not None:
embedding = outputs.pooler_output.squeeze().cpu().numpy()
else:
# Fallback to mean pooling of last hidden state
embedding = outputs.last_hidden_state.mean(dim=1).squeeze().cpu().numpy()
embeddings.append(embedding.tolist())
else:
# Method 2: Fallback to sentence transformer
if sentence_transformer:
embedding = sentence_transformer.encode(text)
embeddings.append(embedding.tolist())
else:
raise Exception("No model available")
except Exception as e:
logger.warning(f"Error generating embedding for text: {str(e)}")
# Fallback to sentence transformer
if sentence_transformer:
embedding = sentence_transformer.encode(text)
embeddings.append(embedding.tolist())
else:
# Return zero vector as last resort
embeddings.append([0.0] * 1024) # Qwen3-Embedding-0.6B has 1024 dimensions
return embeddings[0] if single_text else embeddings
except Exception as e:
logger.error(f"Error in generate_embeddings: {str(e)}")
# Return zero vectors as fallback
if single_text:
return [0.0] * 1024
else:
return [[0.0] * 1024] * len(texts)
def compute_similarity(embedding1: List[float], embedding2: List[float]) -> float:
"""Compute cosine similarity between two embeddings"""
try:
# Convert to numpy arrays
emb1 = np.array(embedding1)
emb2 = np.array(embedding2)
# Compute cosine similarity
dot_product = np.dot(emb1, emb2)
norm1 = np.linalg.norm(emb1)
norm2 = np.linalg.norm(emb2)
if norm1 == 0 or norm2 == 0:
return 0.0
similarity = dot_product / (norm1 * norm2)
return float(similarity)
except Exception as e:
logger.error(f"Error computing similarity: {str(e)}")
return 0.0
def batch_embedding_interface(texts: str) -> str:
"""Interface for batch embedding generation"""
try:
# Split texts by newlines
text_list = [text.strip() for text in texts.split('\n') if text.strip()]
if not text_list:
return json.dumps([])
# Generate embeddings
embeddings = generate_embeddings(text_list)
# Return as JSON string
return json.dumps(embeddings)
except Exception as e:
logger.error(f"Error in batch_embedding_interface: {str(e)}")
return json.dumps([])
def single_embedding_interface(text: str) -> str:
"""Interface for single embedding generation"""
try:
if not text.strip():
return json.dumps([])
# Generate embedding
embedding = generate_embeddings(text)
# Return as JSON string
return json.dumps(embedding)
except Exception as e:
logger.error(f"Error in single_embedding_interface: {str(e)}")
return json.dumps([])
def similarity_interface(embedding1: str, embedding2: str) -> float:
"""Interface for computing similarity between two embeddings"""
try:
# Parse embeddings from JSON strings
emb1 = json.loads(embedding1)
emb2 = json.loads(embedding2)
# Compute similarity
similarity = compute_similarity(emb1, emb2)
return similarity
except Exception as e:
logger.error(f"Error in similarity_interface: {str(e)}")
return 0.0
def health_check():
"""Health check endpoint"""
return {"status": "healthy", "model_loaded": model is not None}
# Create Gradio interface
def create_interface():
"""Create the Gradio interface"""
with gr.Blocks(
title="Qwen Embedding Model",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 1200px !important;
margin: auto !important;
}
"""
) as interface:
gr.Markdown("""
# Qwen Embedding Model API
This space provides a stable API for generating text embeddings using the Qwen model.
The API supports both single text and batch processing.
""")
with gr.Tab("Single Text Embedding"):
gr.Markdown("Generate embedding for a single text input.")
with gr.Row():
with gr.Column():
single_text_input = gr.Textbox(
label="Input Text",
placeholder="Enter text to generate embedding...",
lines=3
)
single_btn = gr.Button("Generate Embedding", variant="primary")
with gr.Column():
single_output = gr.Textbox(
label="Embedding (JSON)",
lines=10,
interactive=False
)
single_btn.click(
single_embedding_interface,
inputs=[single_text_input],
outputs=[single_output]
)
with gr.Tab("Batch Text Embedding"):
gr.Markdown("Generate embeddings for multiple texts (one per line).")
with gr.Row():
with gr.Column():
batch_text_input = gr.Textbox(
label="Input Texts (one per line)",
placeholder="Enter multiple texts, one per line...",
lines=5
)
batch_btn = gr.Button("Generate Embeddings", variant="primary")
with gr.Column():
batch_output = gr.Textbox(
label="Embeddings (JSON)",
lines=10,
interactive=False
)
batch_btn.click(
batch_embedding_interface,
inputs=[batch_text_input],
outputs=[batch_output]
)
with gr.Tab("Similarity Calculator"):
gr.Markdown("Compute cosine similarity between two embeddings.")
with gr.Row():
with gr.Column():
emb1_input = gr.Textbox(
label="Embedding 1 (JSON)",
placeholder='["0.1", "0.2", ...]',
lines=3
)
emb2_input = gr.Textbox(
label="Embedding 2 (JSON)",
placeholder='["0.1", "0.2", ...]',
lines=3
)
sim_btn = gr.Button("Compute Similarity", variant="primary")
with gr.Column():
similarity_output = gr.Number(
label="Cosine Similarity",
precision=4
)
sim_btn.click(
similarity_interface,
inputs=[emb1_input, emb2_input],
outputs=[similarity_output]
)
with gr.Tab("API Documentation"):
gr.Markdown("""
## API Endpoints
### 1. Single Text Embedding
**POST** `/api/predict`
```json
{
"data": ["Your text here"]
}
```
### 2. Batch Text Embedding
**POST** `/api/predict`
```json
{
"data": [["Text 1", "Text 2", "Text 3"]]
}
```
### 3. Health Check
**GET** `/health`
Returns: `{"status": "healthy", "model_loaded": true}`
## Response Format
All endpoints return embeddings as JSON arrays of floating-point numbers.
""")
return interface
def main():
"""Main function to run the application"""
logger.info("Starting Qwen Embedding Model API...")
# Load model
if not load_model():
logger.error("Failed to load model. Exiting...")
return
# Create and launch interface
interface = create_interface()
# Launch with public access
interface.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
show_error=True,
quiet=False
)
if __name__ == "__main__":
main()
|