Spaces:
Sleeping
Sleeping
File size: 1,719 Bytes
76a10e4 a8af8fb 76a10e4 a8af8fb 76a10e4 3d7d8c9 | 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 | import os
import time
import torch
import numpy as np
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional, Union
from sentence_transformers import SentenceTransformer
app = FastAPI(title="Qwen3-Embedding-4B API")
model = SentenceTransformer("Qwen/Qwen3-Embedding-4B", device="cpu")
DIM = model.get_sentence_embedding_dimension()
class EmbeddingRequest(BaseModel):
input: Union[str, List[str]]
model: str = "Qwen/Qwen3-Embedding-4B"
encoding_format: Optional[str] = "float"
class EmbeddingObject(BaseModel):
object: str = "embedding"
embedding: List[float]
index: int
class Usage(BaseModel):
prompt_tokens: int
total_tokens: int
duration_ms: float
class EmbeddingResponse(BaseModel):
object: str = "list"
data: List[EmbeddingObject]
model: str
usage: Usage
@app.post("/v1/embeddings", response_model=EmbeddingResponse)
async def embed(req: EmbeddingRequest):
texts = req.input if isinstance(req.input, list) else [req.input]
start = time.time()
embeddings = model.encode(texts, normalize_embeddings=True, show_progress_bar=False)
duration = (time.time() - start) * 1000
data = [
EmbeddingObject(embedding=e.tolist(), index=i)
for i, e in enumerate(embeddings)
]
total_tokens = sum(max(1, len(t.split()) * 2) for t in texts)
return EmbeddingResponse(
object="list",
data=data,
model=req.model,
usage=Usage(prompt_tokens=total_tokens, total_tokens=total_tokens, duration_ms=round(duration, 2)),
)
@app.get("/health")
async def health():
return {"status": "ok", "model": "Qwen3-Embedding-4B", "dim": DIM, "backend": "pytorch-cpu"}
|