CoolFace
Apppublic

Roshni231123/STS_API

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
inference_app.py92 linesDownload Raw Back to root
1# # inference_app.py
2# from fastapi import FastAPI
3# from pydantic import BaseModel
4# from sentence_transformers import SentenceTransformer, util
5
6# # ---------------------------------------------------------
7# # Initialize FastAPI app
8# # ---------------------------------------------------------
9# app = FastAPI(
10#     title="Semantic Textual Similarity API",
11#     description="Returns semantic similarity score between two text paragraphs (0–1 scale)",
12#     version="1.0"
13# )
14
15# # ---------------------------------------------------------
16# # Load pre-trained lightweight model (CPU friendly)
17# # ---------------------------------------------------------
18# model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
19
20# # ---------------------------------------------------------
21# # Define input request structure
22# # ---------------------------------------------------------
23# class TextPair(BaseModel):
24#     text1: str
25#     text2: str
26
27# # ---------------------------------------------------------
28# # Define route for similarity
29# # ---------------------------------------------------------
30# @app.post("/", tags=["Similarity"])
31# def get_similarity(data: TextPair):
32#     """
33#     Calculate semantic similarity between two texts
34#     """
35#     # Encode both sentences
36#     emb1 = model.encode(data.text1, convert_to_tensor=True)
37#     emb2 = model.encode(data.text2, convert_to_tensor=True)
38
39#     # Compute cosine similarity
40#     similarity = util.cos_sim(emb1, emb2).item()
41
42#     # Normalize similarity from [-1, 1] → [0, 1]
43#     normalized_score = (similarity + 1) / 2
44
45#     # Return rounded result
46#     return {"similarity score": round(normalized_score, 4)}
47
48# # ---------------------------------------------------------
49# # Root endpoint
50# # ---------------------------------------------------------
51# @app.get("/", tags=["Home"])
52# def home():
53#     return {"message": "Welcome to the Semantic Text Similarity API"}
54
55
56
57
58# inference_app.py
59from fastapi import FastAPI
60from pydantic import BaseModel
61from sentence_transformers import SentenceTransformer, util
62from fastapi.responses import HTMLResponse, JSONResponse
63
64app = FastAPI(title="Semantic Text Similarity API")
65
66# Load lightweight STS model (CPU-friendly)
67model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
68
69# Input data structure
70class TextPair(BaseModel):
71    text1: str
72    text2: str
73
74# Root endpoint: HTML page for browser users
75@app.get("/", response_class=HTMLResponse)
76def home():
77    return """
78    <h2>Semantic Text Similarity API</h2>
79    <p>Send POST requests with JSON to get similarity score between two texts.</p>
80    <p>Example POST JSON format:</p>
81    <pre>{"text1":"Hello","text2":"Hi"}</pre>
82    """
83
84# POST endpoint: Returns JSON similarity score
85@app.post("/", tags=["Similarity"])
86def get_similarity(data: TextPair):
87    emb1 = model.encode(data.text1, convert_to_tensor=True)
88    emb2 = model.encode(data.text2, convert_to_tensor=True)
89    similarity = util.cos_sim(emb1, emb2).item()
90    normalized_score = (similarity + 1) / 2
91    return JSONResponse(content={"similarity score": round(normalized_score, 4)})
92