Gaykar commited on
Commit
c7e8477
·
1 Parent(s): cf19b9d

created floder structure

Browse files
Brain_Meningioma_Tumor.jpg DELETED
Binary file (15.8 kB)
 
Dockerfile CHANGED
@@ -1,22 +1,32 @@
1
  FROM python:3.12-slim
2
 
 
3
  WORKDIR /code
4
 
 
5
  COPY requirements.txt .
 
 
6
  RUN pip install --no-cache-dir --upgrade -r requirements.txt
7
 
 
8
  RUN useradd -m -u 1000 user
 
 
9
  USER user
10
 
 
11
  ENV HOME=/home/user \
12
  PATH=/home/user/.local/bin:$PATH
13
 
 
14
  WORKDIR $HOME/app
 
 
15
  COPY --chown=user . $HOME/app
16
 
17
- # Expose the mandatory Hugging Face port
18
  EXPOSE 7860
19
 
20
- # 1. Start a fake web server on port 7860 to pass the HF health check
21
- # 2. Run the pure Celery worker and beat (beat is required for the periodic heartbeat)
22
- CMD python3 -m http.server 7860 & celery -A main.celery_app worker --beat --loglevel=info
 
1
  FROM python:3.12-slim
2
 
3
+ # Set the working directory to /code
4
  WORKDIR /code
5
 
6
+ # Copy the requirements.txt file into the container
7
  COPY requirements.txt .
8
+
9
+ # Install the dependencies
10
  RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
 
12
+ # Set up a new user named "user" with user ID 1000
13
  RUN useradd -m -u 1000 user
14
+
15
+ # Switch to the "user" user
16
  USER user
17
 
18
+ # Set home to the user's home directory
19
  ENV HOME=/home/user \
20
  PATH=/home/user/.local/bin:$PATH
21
 
22
+ # Set the working directory to the user's home directory
23
  WORKDIR $HOME/app
24
+
25
+ # Copy the current directory contents into the container at $HOME/app
26
  COPY --chown=user . $HOME/app
27
 
28
+ # Expose the port FastAPI will run on
29
  EXPOSE 7860
30
 
31
+ # Start the FastAPI app on port 7860 (HF Spaces default)
32
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
 
TumorClassificationModel/model_file.pth DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8563e8da61ff7f3bf9d590172b96842c472eaa0b7a2186b9dc283558c1263fa8
3
- size 16359003
 
 
 
 
{TumorClassificationModel → app/TumorClassificationModel}/.gitkeep RENAMED
File without changes
{cnn_pipeline → app/cnn_pipeline}/__init__.py RENAMED
File without changes
{cnn_pipeline → app/cnn_pipeline}/pipeline.py RENAMED
@@ -1,46 +1,46 @@
1
- import io
2
- import torch
3
- import torch.nn as nn
4
- from PIL import Image
5
- from torchvision import models, transforms
6
-
7
- CLASS_NAMES = ['glioma', 'meningioma', 'no tumor', 'pituitary']
8
- CHECKPOINT = "TumorClassificationModel/model_file.pth"
9
-
10
-
11
- def load_cnn_model(checkpoint=CHECKPOINT, num_classes=len(CLASS_NAMES)):
12
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
13
- model = models.efficientnet_b0(weights=None)
14
- model.classifier = nn.Sequential(
15
- nn.Dropout(p=0.005),
16
- nn.Linear(model.classifier[1].in_features, num_classes),
17
- )
18
- model.load_state_dict(torch.load(checkpoint, map_location=device))
19
- return model.to(device).eval() # inference mode
20
-
21
-
22
- class CNNPipeline:
23
- def __init__(self, model, class_names=CLASS_NAMES, size=224):
24
- self.model = model
25
- self.device = next(model.parameters()).device
26
- self.class_names = class_names
27
- self.preprocess = transforms.Compose([
28
- transforms.Resize((size, size)),
29
- transforms.ToTensor(),
30
- transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
31
- ])
32
-
33
- def classify(self, image_bytes: bytes) -> dict:
34
- image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
35
- x = self.preprocess(image).unsqueeze(0).to(self.device) # [1,3,H,W]
36
-
37
- with torch.no_grad():
38
- probs = torch.softmax(self.model(x), dim=1)
39
- conf, idx = torch.max(probs, dim=1)
40
-
41
- tumor_type = self.class_names[int(idx)]
42
- return {
43
- "has_tumor": tumor_type.lower() != "no tumor",
44
- "tumor_type": tumor_type,
45
- "confidence": float(conf) * 100,
46
  }
 
1
+ import io
2
+ import torch
3
+ import torch.nn as nn
4
+ from PIL import Image
5
+ from torchvision import models, transforms
6
+
7
+ CLASS_NAMES = ['glioma', 'meningioma', 'no tumor', 'pituitary']
8
+ CHECKPOINT = "TumorClassificationModel/model_file.pth"
9
+
10
+
11
+ def load_cnn_model(checkpoint=CHECKPOINT, num_classes=len(CLASS_NAMES)):
12
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
13
+ model = models.efficientnet_b0(weights=None)
14
+ model.classifier = nn.Sequential(
15
+ nn.Dropout(p=0.005),
16
+ nn.Linear(model.classifier[1].in_features, num_classes),
17
+ )
18
+ model.load_state_dict(torch.load(checkpoint, map_location=device))
19
+ return model.to(device).eval() # inference mode
20
+
21
+
22
+ class CNNPipeline:
23
+ def __init__(self, model, class_names=CLASS_NAMES, size=224):
24
+ self.model = model
25
+ self.device = next(model.parameters()).device
26
+ self.class_names = class_names
27
+ self.preprocess = transforms.Compose([
28
+ transforms.Resize((size, size)),
29
+ transforms.ToTensor(),
30
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
31
+ ])
32
+
33
+ def classify(self, image_bytes: bytes) -> dict:
34
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
35
+ x = self.preprocess(image).unsqueeze(0).to(self.device) # [1,3,H,W]
36
+
37
+ with torch.no_grad():
38
+ probs = torch.softmax(self.model(x), dim=1)
39
+ conf, idx = torch.max(probs, dim=1)
40
+
41
+ tumor_type = self.class_names[int(idx)]
42
+ return {
43
+ "has_tumor": tumor_type.lower() != "no tumor",
44
+ "tumor_type": tumor_type,
45
+ "confidence": float(conf) * 100,
46
  }
app/core/__init__.py ADDED
File without changes
app/core/config.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Optional
4
+ from pydantic_settings import BaseSettings, SettingsConfigDict
5
+
6
+
7
+ BASE_DIR = Path(__file__).resolve().parent.parent.parent
8
+
9
+ class Settings(BaseSettings):
10
+ # --- Project Metadata ---
11
+ PROJECT_NAME: str = "Brain Tumor CNN Service"
12
+
13
+ # S3 compatible storage.
14
+ AWS_ENDPOINT_URL_S3:str
15
+ AWS_ACCESS_KEY_ID:str
16
+ AWS_SECRET_ACCESS_KEY:str
17
+ AWS_REGION:str
18
+ NEON_BUCKET:str
19
+
20
+ # --- Database Configuration ---
21
+ # Automatically falls back to local if not provided (useful for AWS RDS later)
22
+ DATABASE_URL: str
23
+
24
+ LANGGRAPH_DB_URL:str
25
+ # --- File Paths (Dynamic for Local/Cloud compatibility) ---
26
+
27
+ model_config = SettingsConfigDict(
28
+ env_file=str(BASE_DIR / ".env"),
29
+ env_file_encoding="utf-8",
30
+ extra="ignore" # Ignores extra variables in .env that aren't defined here
31
+ )
32
+
33
+ # Create a singleton instance to be used across the app
34
+ settings = Settings()
35
+
36
+
app/core/s3.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import aioboto3
3
+ from botocore.config import Config
4
+ from app.core.config import settings
5
+
6
+ cfg = {
7
+ "endpoint": settings.AWS_ENDPOINT_URL_S3,
8
+ "bucket": settings.NEON_BUCKET,
9
+ "region": settings.AWS_REGION,
10
+ "folder": "mri_scan",
11
+ "expires_in": 600,
12
+ }
13
+
14
+ session = aioboto3.Session(
15
+ aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
16
+ aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
17
+ )
18
+
19
+ def s3_client():
20
+ return session.client("s3",endpoint_url=cfg["endpoint"],region_name=cfg["region"],config=Config(signature_version="s3v4"))
21
+
22
+
23
+ def user_prefix(user_id: str) -> str:
24
+ return f"{user_id}/{cfg['folder']}/"
25
+
26
+
27
+ def owns_key(user_id: str, file_key: str) -> bool:
28
+ return file_key.startswith(user_prefix(user_id)) and ".." not in file_key
29
+
30
+
31
+ async def presigned_download_url(user_id: str, file_key: str) -> dict:
32
+ if not owns_key(user_id, file_key):
33
+ raise PermissionError("file_key does not belong to this user")
34
+ async with s3_client() as s3:
35
+ url = await s3.generate_presigned_url(
36
+ "get_object",
37
+ Params={"Bucket": cfg["bucket"], "Key": file_key},
38
+ ExpiresIn=cfg["expires_in"],
39
+ )
40
+ return {"download_url": url}
41
+
42
+ async def delete_scan(user_id: str, file_key: str) -> None:
43
+ if not owns_key(user_id, file_key):
44
+ raise PermissionError("file_key does not belong to this user")
45
+ async with s3_client() as s3:
46
+ await s3.delete_object(Bucket=cfg["bucket"], Key=file_key)
47
+
48
+
49
+
50
+
app/main.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from concurrent.futures import ThreadPoolExecutor
3
+ from contextlib import asynccontextmanager
4
+ from typing import Annotated
5
+ import torch
6
+ from fastapi import Depends, FastAPI, File, UploadFile
7
+ from app.cnn_pipeline.pipeline import CNNPipeline, load_cnn_model
8
+
9
+ ml_models = {}
10
+ executor = ThreadPoolExecutor(max_workers=2)
11
+
12
+
13
+ @asynccontextmanager
14
+ async def lifespan(app: FastAPI):
15
+
16
+ torch.set_num_threads(1)
17
+ ml_models["cnn_model"] = load_cnn_model()
18
+ ml_models["pipeline"] = CNNPipeline(ml_models["cnn_model"])
19
+
20
+ yield # the app serves requests here
21
+
22
+ # This code will run when the app is shuting down
23
+ executor.shutdown(wait=True)
24
+ ml_models.clear()
25
+
26
+
27
+ app = FastAPI(title="Brain Tumor CNN Service", lifespan=lifespan)
28
+
29
+
30
+ def get_pipeline() -> CNNPipeline:
31
+ return ml_models["pipeline"]
32
+
33
+
34
+ PipelineDep = Annotated[CNNPipeline, Depends(get_pipeline)]
35
+
36
+
37
+
38
+ # The classify endpoint is defined as an asynchronous function that takes a PipelineDep dependency and an uploaded file. It reads the image bytes from the uploaded file, then uses asyncio's event loop to run the classify method of the CNNPipeline in a separate thread using the ThreadPoolExecutor. The result of the classification is returned as a JSON response.
39
+ @app.post("/classify")
40
+ async def classify(pipeline: PipelineDep, file: UploadFile = File(...)):
41
+
42
+ # IO task
43
+ image_bytes = await file.read()
44
+ loop = asyncio.get_running_loop()
45
+ result = await loop.run_in_executor(executor, pipeline.classify, image_bytes)
46
+ return result
main.py DELETED
@@ -1,104 +0,0 @@
1
- import os
2
- import logging
3
- from pathlib import Path
4
- from celery import Celery
5
- from celery.signals import worker_process_init
6
- import torch
7
-
8
- # Import your custom modules exactly as structured in your repo image
9
- from cnn_pipeline.pipeline import CNNPipeline, load_cnn_model
10
-
11
- # -------------------------------------------------------------
12
- # 1. LOGGING & PATH DEFINITIONS
13
- # -------------------------------------------------------------
14
- logging.basicConfig(level=logging.INFO)
15
- logger = logging.getLogger(__name__)
16
-
17
- BASE_DIR = Path(__file__).resolve().parent
18
- DEFAULT_IMAGE_NAME = "Brain_Meningioma_Tumor.jpg"
19
-
20
- # -------------------------------------------------------------
21
- # 2. CELERY CORE INITIALIZATION
22
- # -------------------------------------------------------------
23
- celery_app = Celery(
24
- "tasks",
25
- broker="memory://",
26
- backend="cache+memory://"
27
- )
28
-
29
- # Global dictionary placeholder inside the worker container process space
30
- ml_models = {}
31
-
32
- # -------------------------------------------------------------
33
- # 3. WORKER LIFESPAN INITIALIZATION (Simulating FastAPI's Lifespan)
34
- # This signal runs exactly once when each worker child process starts up.
35
- # -------------------------------------------------------------
36
- @worker_process_init.connect
37
- def init_worker_models(**kwargs):
38
- logger.info("Initializing worker process: Tuning CPU execution and loading CNN weights...")
39
-
40
- # Restrict thread allocation exactly as done in your original setup
41
- torch.set_num_threads(1)
42
-
43
- try:
44
- # Load models globally into memory relative to this worker pipeline process
45
- cnn_model = load_cnn_model()
46
- ml_models["pipeline"] = CNNPipeline(cnn_model)
47
- logger.info("--- CNN pipeline successfully cached inside Celery worker context ---")
48
- except Exception as e:
49
- logger.error(f"Failed to load the model architecture into the worker environment: {e}")
50
-
51
- # -------------------------------------------------------------
52
- # 4. CELERY TASK TASK DEFINITION
53
- # -------------------------------------------------------------
54
- @celery_app.task(name="main.classify_tumor_task")
55
- def classify_tumor_task(image_name: str = DEFAULT_IMAGE_NAME):
56
- """
57
- Celery task replacing the async FastAPI endpoint.
58
- It reads raw bytes from the target repository image file and feeds
59
- it straight to the pre-loaded CNN pipeline model.
60
- """
61
- target_path = BASE_DIR / image_name
62
- logger.info(f"--- [TASK RECEIVED] Target File Processing: {target_path.name} ---")
63
-
64
- # Safety checks
65
- if "pipeline" not in ml_models:
66
- error_msg = "Model pipeline failed to initialize or is not fully loaded."
67
- logger.error(error_msg)
68
- return {"status": "FAILED", "error": error_msg}
69
-
70
- if not target_path.exists():
71
- error_msg = f"The requested image resource cannot be found: {target_path}"
72
- logger.error(error_msg)
73
- return {"status": "FAILED", "error": error_msg}
74
-
75
- try:
76
- # 1. Core I/O Operation: Mirroring FastAPI's 'await file.read()'
77
- with open(target_path, "rb") as image_file:
78
- image_bytes = image_file.read()
79
-
80
- # 2. Inference Execution: Celery executes tasks on dedicated background threads
81
- # naturally, eliminating the need to explicitly call loop.run_in_executor
82
- pipeline = ml_models["pipeline"]
83
- logger.info("Executing CNN tensor classification pipeline...")
84
- result = pipeline.classify(image_bytes)
85
-
86
- logger.info(f"--- [TASK SUCCESSFUL] Classification Result: {result} ---")
87
- return {
88
- "status": "SUCCESS",
89
- "image_processed": target_path.name,
90
- "classification_output": result
91
- }
92
-
93
- except Exception as e:
94
- logger.exception("An exception intercepted during CNN prediction step execution.")
95
- return {"status": "ERROR", "error": str(e)}
96
-
97
- # -------------------------------------------------------------
98
- # 5. SELF-TEST TRIGGER AUTOMATION
99
- # -------------------------------------------------------------
100
- @celery_app.on_after_configure.connect
101
- def trigger_automated_validation_run(sender, **kwargs):
102
- logger.info(f"Scheduling test run for local file asset: '{DEFAULT_IMAGE_NAME}'...")
103
- # Queue up a single background task tracking execution inside worker console logs
104
- classify_tumor_task.apply_async(args=[DEFAULT_IMAGE_NAME], countdown=3.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -7,4 +7,6 @@ pandas==2.3.3
7
  pillow==12.0.0
8
  python-multipart==0.0.21
9
  uvicorn==0.40.0
 
10
  celery
 
 
7
  pillow==12.0.0
8
  python-multipart==0.0.21
9
  uvicorn==0.40.0
10
+ pydantic_settings
11
  celery
12
+ aioboto3