brendon-ai commited on
Commit
73bfd5b
·
verified ·
1 Parent(s): b908fcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -15
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import FastAPI, HTTPException, status
2
  from pydantic import BaseModel, ValidationError
3
  from transformers import AutoTokenizer, AutoModelForMaskedLM
4
  import torch
@@ -14,6 +14,10 @@ app = FastAPI(
14
  version="1.0.0"
15
  )
16
 
 
 
 
 
17
  # Load model globally to avoid reloading on each request
18
  # This block runs once when the FastAPI application starts.
19
  try:
@@ -24,29 +28,26 @@ try:
24
  logger.info("Model loaded successfully.")
25
  except Exception as e:
26
  logger.exception("Failed to load model or tokenizer during startup!")
27
- # Depending on the deployment, you might want to raise an exception here
28
- # to prevent the app from starting if the model can't be loaded.
29
- # For now, we'll let it potentially start and fail on prediction.
30
  raise RuntimeError(f"Could not load model: {e}")
31
 
32
  class InferenceRequest(BaseModel):
33
  """
34
- Request model for the /predict endpoint.
35
  Expects a single string field 'text' containing the sentence with [MASK] tokens.
36
  """
37
  text: str
38
 
39
  class PredictionResult(BaseModel):
40
  """
41
- Response model for individual predictions from the /predict endpoint.
42
  """
43
  sequence: str # The full sequence with the predicted token filled in
44
  score: float # Confidence score of the prediction
45
  token: int # The ID of the predicted token
46
  token_str: str # The string representation of the predicted token
47
 
48
- @app.post(
49
- "/predict",
50
  response_model=list[PredictionResult],
51
  summary="Predicts masked tokens in a given text",
52
  description="Accepts a text string with '[MASK]' tokens and returns top 5 predictions for each masked position."
@@ -74,7 +75,7 @@ async def predict_masked_lm(request: InferenceRequest):
74
  masked_token_indices = torch.where(inputs["input_ids"] == masked_token_id)[1]
75
 
76
  if not masked_token_indices.numel():
77
- logger.warning("No [MASK] token found in the input text.")
78
  raise HTTPException(
79
  status_code=status.HTTP_400_BAD_REQUEST,
80
  detail="Input text must contain at least one '[MASK]' token."
@@ -129,22 +130,32 @@ async def predict_masked_lm(request: InferenceRequest):
129
  detail=f"An internal server error occurred: {e}"
130
  )
131
 
132
- @app.get(
133
- "/",
134
  summary="Health Check",
135
  description="Returns a simple message indicating the API is running."
136
  )
137
- async def root():
138
  """
139
  Provides a basic health check endpoint for the API.
140
  """
141
  logger.info("Health check endpoint accessed.")
142
  return {"message": "NeuroBERT-Tiny API is running!"}
143
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  # This block is for running the app directly, typically used for local development.
145
  # In a Docker container, Uvicorn (or Gunicorn) is usually invoked via the CMD in Dockerfile.
146
  if __name__ == "__main__":
147
  import uvicorn
148
- # The 'reload=True' is great for local development for auto-reloading changes.
149
- # For production in a Docker container, it's typically omitted for performance.
150
- uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
 
1
+ from fastapi import FastAPI, HTTPException, status, APIRouter, Request
2
  from pydantic import BaseModel, ValidationError
3
  from transformers import AutoTokenizer, AutoModelForMaskedLM
4
  import torch
 
14
  version="1.0.0"
15
  )
16
 
17
+ # Create an API Router to manage endpoints.
18
+ # This approach can sometimes help with routing issues in proxied environments.
19
+ api_router = APIRouter()
20
+
21
  # Load model globally to avoid reloading on each request
22
  # This block runs once when the FastAPI application starts.
23
  try:
 
28
  logger.info("Model loaded successfully.")
29
  except Exception as e:
30
  logger.exception("Failed to load model or tokenizer during startup!")
 
 
 
31
  raise RuntimeError(f"Could not load model: {e}")
32
 
33
  class InferenceRequest(BaseModel):
34
  """
35
+ Request model for the main prediction endpoint.
36
  Expects a single string field 'text' containing the sentence with [MASK] tokens.
37
  """
38
  text: str
39
 
40
  class PredictionResult(BaseModel):
41
  """
42
+ Response model for individual predictions from the API.
43
  """
44
  sequence: str # The full sequence with the predicted token filled in
45
  score: float # Confidence score of the prediction
46
  token: int # The ID of the predicted token
47
  token_str: str # The string representation of the predicted token
48
 
49
+ @api_router.post(
50
+ "/", # Changed from "/predict" to "/" to funnel all POST requests to the root
51
  response_model=list[PredictionResult],
52
  summary="Predicts masked tokens in a given text",
53
  description="Accepts a text string with '[MASK]' tokens and returns top 5 predictions for each masked position."
 
75
  masked_token_indices = torch.where(inputs["input_ids"] == masked_token_id)[1]
76
 
77
  if not masked_token_indices.numel():
78
+ logger.warning("No [MASK] token found in the input text. Returning 400 Bad Request.")
79
  raise HTTPException(
80
  status_code=status.HTTP_400_BAD_REQUEST,
81
  detail="Input text must contain at least one '[MASK]' token."
 
130
  detail=f"An internal server error occurred: {e}"
131
  )
132
 
133
+ @api_router.get(
134
+ "/health", # Health check moved to /health
135
  summary="Health Check",
136
  description="Returns a simple message indicating the API is running."
137
  )
138
+ async def health_check():
139
  """
140
  Provides a basic health check endpoint for the API.
141
  """
142
  logger.info("Health check endpoint accessed.")
143
  return {"message": "NeuroBERT-Tiny API is running!"}
144
 
145
+ # Include the API router in the main FastAPI application
146
+ app.include_router(api_router)
147
+
148
+ # Optional: Add a catch-all route for any unhandled paths.
149
+ # This can help log when requests are hitting the app but to an unknown path.
150
+ # This should now catch anything not / or /health
151
+ @app.api_route("/{path_name:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
152
+ async def catch_all(request: Request, path_name: str):
153
+ logger.warning(f"Unhandled route accessed: {request.method} {path_name}")
154
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found")
155
+
156
+
157
  # This block is for running the app directly, typically used for local development.
158
  # In a Docker container, Uvicorn (or Gunicorn) is usually invoked via the CMD in Dockerfile.
159
  if __name__ == "__main__":
160
  import uvicorn
161
+ uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")