Spaces:
Sleeping
Sleeping
Create app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""KG Embedding Server β FastAPI on HuggingFace SpacesΩΨ΄ΨͺΨΊΩ ΩΩ REST APIΨ ΩΨΩ
Ω Ψ§ΩΩ
ΩΨ―ΩΩ Ω
Ψ±Ψ© ΩΨ§ΨΨ―Ψ© Ψ¨Ψ³"""
from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom typing import Optionalimport mathimport reimport contextlibfrom io import StringIO
app = FastAPI(title="KG Embedding Server")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ# GLOBALS β Ψ§ΩΩ
ΩΨ―ΩΩ Ψ¨ΩΨͺΨΩ
Ω Ω
Ψ±Ψ© ΩΨ§ΨΨ―Ψ© ΨΉΩΨ― startup# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ_model = None_use_st = False
@app.on_event("startup")def load_model(): global _model, _use_st try: from sentence_transformers import SentenceTransformer with contextlib.redirect_stdout(StringIO()), contextlib.redirect_stderr(StringIO()): _model = SentenceTransformer("all-MiniLM-L6-v2") _use_st = True print("[Server] sentence-transformers loaded β") except Exception as e: print(f"[Server] ST unavailable: {e}") _use_st = False
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ# REQUEST / RESPONSE MODELS# ββββββββββββββββββββββββββββββββββββββββββββββββββββββclass EmbedRequest(BaseModel): texts: list[str]
class EmbedResponse(BaseModel): embeddings: list[list[float]] model: str = "all-MiniLM-L6-v2"
class SimilarityRequest(BaseModel): query: str candidates: list[str] # Ψ§ΩΩΨ΅ΩΨ΅ Ψ§ΩΩΩ ΩΩΩΩΨ³ ΨΉΩΩΩΨ§
class SimilarityResponse(BaseModel): scores: list[float] # cosine similarity ΩΩΩ candidate
class HealthResponse(BaseModel): status: str model_loaded: bool
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ# ENDPOINTS# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/health", response_model=HealthResponse)def health(): return {"status": "ok", "model_loaded": _use_st}
@app.post("/embed", response_model=EmbedResponse)def embed(req: EmbedRequest): if not _use_st or _model is None: raise HTTPException(503, "Model not loaded") if not req.texts: return EmbedResponse(embeddings=[]) with contextlib.redirect_stdout(StringIO()), contextlib.redirect_stderr(StringIO()): vecs = _model.encode(req.texts, show_progress_bar=False) return EmbedResponse(embeddings=[v.tolist() for v in vecs])
@app.post("/similarity", response_model=SimilarityResponse)def similarity(req: SimilarityRequest): """Query + candidates β cosine scores (Ψ§ΩΨ£Ψ³Ψ±ΨΉ ΩΩ ΨΉΨ§ΩΨ² ΨͺΨ±ΨͺΨ¨ ΩΨͺΨ§ΩΨ¬)""" if not _use_st or _model is None: raise HTTPException(503, "Model not loaded") texts = [req.query] + req.candidates with contextlib.redirect_stdout(StringIO()), contextlib.redirect_stderr(StringIO()): vecs = _model.encode(texts, show_progress_bar=False) qvec = vecs[0] scores = [_cosine(qvec, v) for v in vecs[1:]] return SimilarityResponse(scores=scores)
def _cosine(a, b) -> float: dot = sum(x * y for x, y in zip(a, b)) na = math.sqrt(sum(x * x for x in a)) or 1e-9 nb = math.sqrt(sum(x * x for x in b)) or 1e-9 return dot / (na * nb)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PING β ΩΩ
ΩΨΉ Ψ§ΩΩ Space Ω
Ω Ψ§ΩΩΩΩ
(Ψ§ΨΉΩ
Ω cron job ΩΨ¨ΨΉΨͺΩ ΩΩ 4 Ψ―ΩΨ§ΩΩ)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.get("/ping")def ping(): return {"pong": True}app.pyAdded+97