fcastrovilli commited on
Commit
6284a4a
·
1 Parent(s): 29b2c47

feat: add bearer token to the api and fix the docs

Browse files
Files changed (2) hide show
  1. README.md +24 -3
  2. main.py +25 -3
README.md CHANGED
@@ -47,16 +47,37 @@ Build and run the container:
47
 
48
  ```bash
49
  docker build -t imagebind-api .
50
- docker run -p 8000:8000 imagebind-api
51
  ```
52
 
53
  ## API Endpoints
54
 
55
- The API will be available at `http://localhost:8000` with the following endpoints:
56
 
57
  - POST `/compute_embeddings`: Generate embeddings for images, audio files, and text
58
  - POST `/compute_similarities`: Compute similarities between embeddings
59
 
60
- For detailed API documentation, visit `http://localhost:8000/docs`
61
 
62
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  ```bash
49
  docker build -t imagebind-api .
50
+ docker run -p 7860:7860 imagebind-api
51
  ```
52
 
53
  ## API Endpoints
54
 
55
+ The API will be available at `http://localhost:7860` with the following endpoints:
56
 
57
  - POST `/compute_embeddings`: Generate embeddings for images, audio files, and text
58
  - POST `/compute_similarities`: Compute similarities between embeddings
59
 
60
+ For detailed API documentation, visit `http://localhost:7860/docs`
61
 
62
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
63
+
64
+ ## API Authentication
65
+
66
+ The API uses Bearer token authentication. You need to include an authorization header with your API token in all requests:
67
+
68
+ ```bash
69
+ # Set your API token as an environment variable
70
+ export API_TOKEN="your-api-token-here"
71
+
72
+ # Example curl request with authentication
73
+ curl -X POST "http://localhost:7860/compute_embeddings" \
74
+ -H "Authorization: Bearer ${API_TOKEN}" \
75
+ -H "Content-Type: multipart/form-data" \
76
+ -F "texts=example text"
77
+ ```
78
+
79
+ When running the Docker container, you can set the API token as an environment variable:
80
+
81
+ ```bash
82
+ docker run -p 7860:7860 -e API_TOKEN="your-api-token-here" imagebind-api
83
+ ```
main.py CHANGED
@@ -10,9 +10,25 @@ import tempfile
10
  from pydantic import BaseModel
11
  import uvicorn
12
  import numpy as np
 
 
13
 
14
  app = FastAPI()
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def convert_audio_to_wav(audio_path: str) -> str:
17
  """Convert MP3 to WAV if necessary."""
18
  if audio_path.lower().endswith('.mp3'):
@@ -108,6 +124,7 @@ class SimilarityResponse(BaseModel):
108
 
109
  @app.post("/compute_embeddings", response_model=EmbeddingResponse)
110
  async def generate_embeddings(
 
111
  texts: str | None = Form(None),
112
  images: List[UploadFile] | None = File(default=None),
113
  audio_files: List[UploadFile] | None = File(default=None)
@@ -184,13 +201,18 @@ async def generate_embeddings(
184
  pass
185
 
186
  @app.post("/compute_similarities", response_model=SimilarityResponse)
187
- async def compute_similarities(embeddings: Dict[str, List[List[float]]]):
 
 
 
188
  """Compute similarities from provided embeddings."""
189
  similarities = embedding_manager.compute_similarities(embeddings)
190
  return SimilarityResponse(similarities=similarities)
191
 
192
  @app.get("/health")
193
- async def health_check():
 
 
194
  """Basic healthcheck endpoint that returns the status of the service."""
195
  return {
196
  "status": "healthy",
@@ -198,4 +220,4 @@ async def health_check():
198
  }
199
 
200
  if __name__ == "__main__":
201
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
10
  from pydantic import BaseModel
11
  import uvicorn
12
  import numpy as np
13
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
14
+ from fastapi import Depends, HTTPException, status
15
 
16
  app = FastAPI()
17
 
18
+ # Add these lines after the app initialization
19
+ security = HTTPBearer()
20
+ API_TOKEN = os.getenv("API_TOKEN", "your-default-token-here") # Set a default token or use environment variable
21
+
22
+ # Add this function for token verification
23
+ async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
24
+ if credentials.credentials != API_TOKEN:
25
+ raise HTTPException(
26
+ status_code=status.HTTP_401_UNAUTHORIZED,
27
+ detail="Invalid authentication token",
28
+ headers={"WWW-Authenticate": "Bearer"},
29
+ )
30
+ return credentials.credentials
31
+
32
  def convert_audio_to_wav(audio_path: str) -> str:
33
  """Convert MP3 to WAV if necessary."""
34
  if audio_path.lower().endswith('.mp3'):
 
124
 
125
  @app.post("/compute_embeddings", response_model=EmbeddingResponse)
126
  async def generate_embeddings(
127
+ credentials: HTTPAuthorizationCredentials = Depends(verify_token),
128
  texts: str | None = Form(None),
129
  images: List[UploadFile] | None = File(default=None),
130
  audio_files: List[UploadFile] | None = File(default=None)
 
201
  pass
202
 
203
  @app.post("/compute_similarities", response_model=SimilarityResponse)
204
+ async def compute_similarities(
205
+ embeddings: Dict[str, List[List[float]]],
206
+ credentials: HTTPAuthorizationCredentials = Depends(verify_token)
207
+ ):
208
  """Compute similarities from provided embeddings."""
209
  similarities = embedding_manager.compute_similarities(embeddings)
210
  return SimilarityResponse(similarities=similarities)
211
 
212
  @app.get("/health")
213
+ async def health_check(
214
+ credentials: HTTPAuthorizationCredentials = Depends(verify_token)
215
+ ):
216
  """Basic healthcheck endpoint that returns the status of the service."""
217
  return {
218
  "status": "healthy",
 
220
  }
221
 
222
  if __name__ == "__main__":
223
+ uvicorn.run(app, host="0.0.0.0", port=7860)