Update app.py
Browse files
app.py
CHANGED
|
@@ -1,57 +1,43 @@
|
|
| 1 |
-
import
|
| 2 |
-
from fastapi import
|
| 3 |
-
import uvicorn
|
| 4 |
from sentence_transformers import SentenceTransformer
|
| 5 |
-
|
| 6 |
-
from typing import Optional
|
| 7 |
-
|
| 8 |
-
# Initialize FastAPI
|
| 9 |
-
app = FastAPI(title="Sentence Transformer API")
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
print(f"Model loading failed: {str(e)}")
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
|
| 25 |
|
| 26 |
@app.get("/")
|
| 27 |
-
def
|
| 28 |
-
"""Required health check endpoint"""
|
| 29 |
return {
|
| 30 |
-
"
|
| 31 |
-
"
|
|
|
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
@app.post("/embed")
|
| 35 |
-
async def embed_text(
|
| 36 |
-
|
| 37 |
-
return {"error": "Model still loading"}, 503
|
| 38 |
-
|
| 39 |
-
# Convert text to list if single string
|
| 40 |
-
input_text = [text] if isinstance(text, str) else text
|
| 41 |
-
|
| 42 |
-
embeddings = model.encode(input_text)
|
| 43 |
-
|
| 44 |
return {
|
| 45 |
-
"
|
| 46 |
-
"embedding": embeddings.tolist(),
|
| 47 |
-
"dimension": len(embeddings[0]) if isinstance(embeddings, list) else len(embeddings)
|
| 48 |
}
|
| 49 |
|
| 50 |
if __name__ == "__main__":
|
| 51 |
-
port = int(os.environ.get("PORT", 7860))
|
| 52 |
uvicorn.run(
|
| 53 |
-
|
| 54 |
host="0.0.0.0",
|
| 55 |
-
port=
|
| 56 |
-
reload=False
|
| 57 |
)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 3 |
from sentence_transformers import SentenceTransformer
|
| 4 |
+
import uvicorn
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
# Initialize with root_path (MANDATORY FOR SPACES)
|
| 7 |
+
app = FastAPI(root_path="/proxy") # 👈 THIS IS CRITICAL
|
| 8 |
|
| 9 |
+
# CORS (required for Spaces)
|
| 10 |
+
app.add_middleware(
|
| 11 |
+
CORSMiddleware,
|
| 12 |
+
allow_origins=["*"],
|
| 13 |
+
allow_methods=["*"],
|
| 14 |
+
allow_headers=["*"],
|
| 15 |
+
)
|
|
|
|
| 16 |
|
| 17 |
+
# Load model (simplified)
|
| 18 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 19 |
|
| 20 |
@app.get("/")
|
| 21 |
+
def home():
|
|
|
|
| 22 |
return {
|
| 23 |
+
"message": "API is working!",
|
| 24 |
+
"endpoints": {
|
| 25 |
+
"embed": "POST /embed",
|
| 26 |
+
"docs": "/docs"
|
| 27 |
+
}
|
| 28 |
}
|
| 29 |
|
| 30 |
@app.post("/embed")
|
| 31 |
+
async def embed_text(request: Request):
|
| 32 |
+
data = await request.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
return {
|
| 34 |
+
"embedding": model.encode(data['text']).tolist()
|
|
|
|
|
|
|
| 35 |
}
|
| 36 |
|
| 37 |
if __name__ == "__main__":
|
|
|
|
| 38 |
uvicorn.run(
|
| 39 |
+
app,
|
| 40 |
host="0.0.0.0",
|
| 41 |
+
port=7860,
|
| 42 |
+
reload=False
|
| 43 |
)
|