Rithvickkr commited on
Commit
068b918
·
1 Parent(s): 15082e5

Add initial FastAPI application with Docker support and Redis caching

Browse files
Files changed (3) hide show
  1. Dockerfile +10 -0
  2. app.py +46 -0
  3. requirements.txt +5 -0
Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY . .
9
+
10
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from sentence_transformers import SentenceTransformer
4
+ import torch
5
+ import redis
6
+ import json
7
+ import hashlib
8
+ import os
9
+
10
+ app = FastAPI()
11
+ model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
12
+
13
+ # Redis connection using Hugging Face storage
14
+ REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
15
+ redis_client = redis.Redis(host=REDIS_HOST, port=6379, db=0, decode_responses=True)
16
+
17
+ class EmbedRequest(BaseModel):
18
+ text: str
19
+
20
+ def get_cache_key(text: str) -> str:
21
+ return f"embed:{hashlib.md5(text.encode()).hexdigest()}"
22
+
23
+ @app.get("/")
24
+ async def root():
25
+ return {"message": "Embedding API is running! Use /embed to generate embeddings."}
26
+
27
+ @app.post("/embed")
28
+ async def embed(request: EmbedRequest):
29
+ text = request.text.strip()
30
+ if not text:
31
+ raise HTTPException(status_code=400, detail="Text cannot be empty")
32
+
33
+ cache_key = get_cache_key(text)
34
+ cached_result = redis_client.get(cache_key)
35
+ if cached_result:
36
+ return json.loads(cached_result)
37
+
38
+ embedding = model.encode([text], convert_to_tensor=True).cpu().tolist()[0]
39
+ redis_client.setex(cache_key, 86400, json.dumps({"embedding": embedding}))
40
+
41
+ return {"embedding": embedding}
42
+
43
+ @app.get("/health")
44
+ async def health_check():
45
+ redis_status = "ok" if redis_client.ping() else "down"
46
+ return {"status": "ok", "gpu": torch.cuda.is_available(), "redis": redis_status}
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ torch
4
+ sentence-transformers
5
+ redis