Spaces:
Sleeping
Sleeping
File size: 8,361 Bytes
90582e1 253dbcb 90582e1 253dbcb 90582e1 d521c64 90582e1 253dbcb 90582e1 d521c64 90582e1 253dbcb 90582e1 253dbcb 90582e1 253dbcb d521c64 90582e1 d521c64 90582e1 d521c64 90582e1 d521c64 253dbcb d521c64 253dbcb d521c64 90582e1 253dbcb 90582e1 253dbcb 90582e1 253dbcb | 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 | import time
from typing import Any
import base64
import numpy as np
import torch
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, ConfigDict
from sentence_transformers import SentenceTransformer
torch.set_grad_enabled(False)
torch.set_num_threads(2)
APP_TITLE = "ollama-code-embed"
MODEL_ID = "jinaai/jina-code-embeddings-0.5b"
MODEL_NAME = "code-embed"
MODEL_ALIASES = [
MODEL_NAME,
f"{MODEL_NAME}:latest",
MODEL_ID,
f"{MODEL_ID}:latest",
]
MODEL_CREATED_AT = "2026-03-11T00:00:00Z"
MODEL_DIMENSIONS = 896
SERVER_VERSION = "0.11.0"
app = FastAPI(title=APP_TITLE, version="1.0.0")
_model: SentenceTransformer | None = None
_loaded_at_ns: int | None = None
_load_duration_ns: int = 0
def model_card(name: str) -> dict[str, Any]:
return {
"name": name,
"model": name,
"modified_at": MODEL_CREATED_AT,
"size": 0,
"digest": MODEL_ID,
"details": {
"format": "sentence-transformers",
"family": "jina",
"families": ["jina", "embedding"],
"parameter_size": "0.5B",
"quantization_level": "F32",
},
}
class CompatibleRequest(BaseModel):
model_config = ConfigDict(extra="allow")
class EmbedRequest(CompatibleRequest):
model: str = MODEL_NAME
input: str | list[str] | None = None
prompt: str | None = None
truncate: bool = True
dimensions: int | None = None
options: dict[str, Any] | None = None
keep_alive: str | int | None = None
class OpenAIEmbeddingRequest(CompatibleRequest):
model: str = MODEL_ID
input: str | list[str]
encoding_format: str = "float"
dimensions: int | None = None
user: str | None = None
def get_model() -> SentenceTransformer:
global _model, _loaded_at_ns, _load_duration_ns
if _model is None:
started = time.perf_counter_ns()
_model = SentenceTransformer(MODEL_ID, trust_remote_code=True, device="cpu")
_load_duration_ns = time.perf_counter_ns() - started
_loaded_at_ns = time.time_ns()
return _model
@app.on_event("startup")
def preload_model() -> None:
get_model()
def normalize_inputs(request: EmbedRequest) -> list[str]:
if request.input is not None:
return request.input if isinstance(request.input, list) else [request.input]
if request.prompt is not None:
return [request.prompt]
raise HTTPException(status_code=400, detail="Request must include 'input' or 'prompt'")
def normalize_openai_inputs(request: OpenAIEmbeddingRequest) -> list[str]:
return request.input if isinstance(request.input, list) else [request.input]
def maybe_truncate(vector: np.ndarray, dimensions: int | None) -> np.ndarray:
if dimensions is None or dimensions <= 0 or dimensions >= vector.shape[0]:
return vector
truncated = vector[:dimensions]
norm = np.linalg.norm(truncated)
if norm > 0:
truncated = truncated / norm
return truncated
def validate_model_name(model_name: str) -> None:
if model_name not in MODEL_ALIASES:
raise HTTPException(status_code=404, detail=f"Model '{model_name}' not found")
def estimate_prompt_eval_count(texts: list[str], model: SentenceTransformer) -> int:
tokenizer = getattr(model, "tokenizer", None)
if tokenizer is None:
return sum(max(1, len(text.split())) for text in texts)
return sum(len(tokenizer.encode(text, add_special_tokens=True)) for text in texts)
@app.get("/", response_class=HTMLResponse)
def root() -> str:
return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{APP_TITLE}</title>
<style>
body {{ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; margin: 32px; line-height: 1.45; }}
code {{ background: #f4f4f4; padding: 2px 6px; border-radius: 4px; }}
</style>
</head>
<body>
<h1>Ollama-Compatible Code Embeddings</h1>
<p>Model: <code>{MODEL_ID}</code></p>
<p>Served name: <code>{MODEL_NAME}</code></p>
<ul>
<li><code>GET /api/version</code></li>
<li><code>GET /api/tags</code></li>
<li><code>POST /api/embed</code></li>
<li><code>POST /api/embeddings</code></li>
<li><code>POST /embed</code></li>
</ul>
</body>
</html>"""
@app.get("/health")
def health() -> dict[str, float]:
return {"unix": time.time()}
@app.get("/api/version")
def api_version() -> dict[str, str]:
return {"version": SERVER_VERSION}
@app.get("/api/tags")
def api_tags() -> dict[str, Any]:
return {"models": [model_card(name) for name in MODEL_ALIASES]}
@app.get("/api/ps")
def api_ps() -> dict[str, Any]:
get_model()
now = time.time()
return {
"models": [
{
"name": MODEL_ID,
"model": MODEL_ID,
"size": 0,
"digest": MODEL_ID,
"details": model_card(MODEL_ID)["details"],
"expires_at": None,
"size_vram": 0,
}
],
"timestamp": now,
}
@app.post("/api/show")
def api_show(request: EmbedRequest) -> dict[str, Any]:
validate_model_name(request.model)
return {
"license": "cc-by-nc-4.0",
"modelfile": f"FROM {MODEL_ID}",
"parameters": "embedding-only",
"template": "",
"details": model_card(MODEL_ID)["details"],
"model_info": {
"general.architecture": "sentence-transformer",
"general.name": MODEL_ID,
"embedding.length": MODEL_DIMENSIONS,
},
}
@app.get("/v1/models")
def v1_models() -> dict[str, Any]:
now = int(time.time())
return {
"object": "list",
"data": [
{"id": model_name, "object": "model", "created": now, "owned_by": "chmielvu"}
for model_name in MODEL_ALIASES
],
}
def embed_impl(request: EmbedRequest) -> dict[str, Any]:
validate_model_name(request.model)
texts = normalize_inputs(request)
model = get_model()
started = time.perf_counter_ns()
vectors = np.asarray(model.encode(texts, convert_to_numpy=True))
total_duration = time.perf_counter_ns() - started
payload = [maybe_truncate(vector, request.dimensions).astype(np.float32).tolist() for vector in vectors]
return {
"model": request.model,
"embeddings": payload,
"total_duration": total_duration,
"load_duration": _load_duration_ns,
"prompt_eval_count": estimate_prompt_eval_count(texts, model),
}
@app.post("/api/embed")
@app.post("/embed")
def api_embed(request: EmbedRequest) -> dict[str, Any]:
return embed_impl(request)
@app.post("/api/embeddings")
def api_embeddings(request: EmbedRequest) -> dict[str, Any]:
result = embed_impl(request)
first = result["embeddings"][0] if result["embeddings"] else []
return {
"embedding": first,
"model": result["model"],
"total_duration": result["total_duration"],
"load_duration": result["load_duration"],
"prompt_eval_count": result["prompt_eval_count"],
}
@app.post("/v1/embeddings")
def v1_embeddings(request: OpenAIEmbeddingRequest) -> dict[str, Any]:
validate_model_name(request.model)
texts = normalize_openai_inputs(request)
model = get_model()
started = time.perf_counter_ns()
vectors = np.asarray(model.encode(texts, convert_to_numpy=True))
total_duration = time.perf_counter_ns() - started
data = []
for idx, vector in enumerate(vectors):
vector = maybe_truncate(vector, request.dimensions).astype(np.float32)
embedding: list[float] | str
if request.encoding_format == "base64":
embedding = base64.b64encode(vector.tobytes()).decode("ascii")
else:
embedding = vector.tolist()
data.append({"object": "embedding", "index": idx, "embedding": embedding})
prompt_tokens = estimate_prompt_eval_count(texts, model)
return {
"object": "list",
"model": request.model,
"data": data,
"usage": {
"prompt_tokens": prompt_tokens,
"total_tokens": prompt_tokens,
},
"load_duration": _load_duration_ns,
"total_duration": total_duration,
}
|