Spaces:
Sleeping
Sleeping
rezvan98 commited on
Commit ·
ddbe9e9
0
Parent(s):
Medical image processing backend API
Browse filesFiles changed (5)
- .gitattributesAdded+35
- DockerfileAdded+29
- README.mdAdded+166
- app.pyAdded+242
- requirements.txtAdded+6
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829FROM python:3.10-slim
# Set working directoryWORKDIR /app
# Install system dependencies for OpenCVRUN apt-get update && apt-get install -y \ libglib2.0-0 \ libsm6 \ libxext6 \ libxrender1 \ libgomp1 \ libgl1 \ && rm -rf /var/lib/apt/lists/*
# Copy requirements fileCOPY requirements.txt .
# Install Python dependenciesRUN pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY app.py .
# Expose port 7860 (Hugging Face Spaces default)EXPOSE 7860
# Run the applicationCMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166---title: Medical Phase Simulator Backendemoji: 🏥colorFrom: bluecolorTo: purplesdk: dockerpinned: false---
# MedTech Image Processing Backend
FastAPI-based backend service for processing medical images with arterial and venous phase filters.
## Features
- **Arterial Phase Processing**: CLAHE-based contrast enhancement for improved visibility- **Venous Phase Processing**: Gaussian smoothing/blur for noise reduction- **RESTful API**: Simple POST endpoint for image processing- **CORS Enabled**: Works with frontend hosted on GitHub Pages- **Docker Ready**: Containerized for easy deployment on Hugging Face Spaces
## API Endpoints
### `POST /process`
Process a medical image with specified phase filter.
**Parameters:**- `image` (file): Medical image file (JPG/PNG)- `phase` (form): Processing phase - `"arterial"` or `"venous"`
**Response:**- Processed image as PNG
**Example using curl:**```bashcurl -X POST "http://localhost:7860/process" \ -F "image=@sample.jpg" \ -F "phase=arterial" \ --output processed.png```
### `GET /`
Health check and API information.
### `GET /health`
Detailed health check with library versions.
## Local Development
### Prerequisites- Python 3.10+- pip
### Setup
1. Install dependencies:```bashpip install -r requirements.txt```
2. Run the server:```bashpython app.py```
The API will be available at `http://localhost:7860`
### Using uvicorn directly:```bashuvicorn app:app --reload --port 7860```
## Docker Deployment
### Build locally:```bashdocker build -t medtech-backend .docker run -p 7860:7860 medtech-backend```
## Hugging Face Spaces Deployment
1. Create a new Space at [huggingface.co/spaces](https://huggingface.co/spaces)2. Select **Docker** as the SDK3. Clone the Space repository:```bashgit clone https://huggingface.co/spaces/YOUR-USERNAME/YOUR-SPACE-NAME```
4. Copy backend files:```bashcp app.py Dockerfile requirements.txt YOUR-SPACE-NAME/cd YOUR-SPACE-NAME```
5. Commit and push:```bashgit add .git commit -m "Initial commit"git push```
6. Your Space will automatically build and deploy at: `https://YOUR-USERNAME-YOUR-SPACE-NAME.hf.space`
## Image Processing Details
### Arterial Phase (Contrast Enhancement)- Uses CLAHE (Contrast Limited Adaptive Histogram Equalization)- Operates in LAB color space for better results- Parameters: `clipLimit=3.0`, `tileGridSize=(8,8)`
### Venous Phase (Gaussian Smoothing)- Applies Gaussian blur with 15x15 kernel- Reduces noise and smooths fine details- Simulates venous phase imaging characteristics
## Tech Stack
- **FastAPI**: Modern Python web framework- **OpenCV**: Image processing library- **NumPy**: Numerical computing- **Pillow**: Image I/O- **Uvicorn**: ASGI server
## Error Handling
The API includes comprehensive error handling:- Invalid file types → 400 Bad Request- Invalid phase parameter → 400 Bad Request- Processing errors → 500 Internal Server Error
## CORS Configuration
CORS is configured to accept requests from:- GitHub Pages (`*.github.io`)- Localhost (development)- All origins (can be restricted for production)
## Testing
Test the API with sample medical images:
```pythonimport requests
url = "http://localhost:7860/process"files = {"image": open("sample.jpg", "rb")}data = {"phase": "arterial"}
response = requests.post(url, files=files, data=data)
with open("output.png", "wb") as f: f.write(response.content)```
## License
This is a demonstration project for educational purposes only. Not intended for clinical use.
## Disclaimer
⚠️ **Important**: This application is for educational and demonstration purposes only. It should NOT be used for actual medical diagnosis or clinical decision-making. Always consult qualified healthcare professionals for medical imaging interpretation.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""MedTech Image Processing Backend APIProvides endpoints for processing medical images with arterial and venous phase filters"""
from fastapi import FastAPI, File, UploadFile, Form, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import Responseimport cv2import numpy as npfrom io import BytesIOfrom PIL import Imageimport logging
# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# Initialize FastAPI appapp = FastAPI( title="MedTech Image Processing API", description="Backend API for processing medical images", version="1.0.0")
# Configure CORS to allow requests from GitHub Pages and localhostapp.add_middleware( CORSMiddleware, allow_origins=[ "https://*.github.io", "http://localhost:*", "http://127.0.0.1:*", "*" # Allow all origins for development - restrict in production ], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
def increase_contrast(img: np.ndarray) -> np.ndarray: """ Apply CLAHE (Contrast Limited Adaptive Histogram Equalization) to enhance contrast Used for arterial phase processing
Args: img: Input image as numpy array (BGR format)
Returns: Enhanced image as numpy array """ try: # Convert to LAB color space for better contrast enhancement lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) l, a, b = cv2.split(lab)
# Apply CLAHE to L channel (lightness) clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8)) l_enhanced = clahe.apply(l)
# Merge channels back and convert to BGR enhanced_lab = cv2.merge([l_enhanced, a, b]) enhanced = cv2.cvtColor(enhanced_lab, cv2.COLOR_LAB2BGR)
logger.info("Contrast enhancement applied successfully") return enhanced except Exception as e: logger.error(f"Error in contrast enhancement: {str(e)}") raise
def apply_gaussian_blur(img: np.ndarray) -> np.ndarray: """ Apply Gaussian blur for smoothing Used for venous phase processing
Args: img: Input image as numpy array (BGR format)
Returns: Blurred image as numpy array """ try: # Apply Gaussian blur with 15x15 kernel blurred = cv2.GaussianBlur(img, (15, 15), 0) logger.info("Gaussian blur applied successfully") return blurred except Exception as e: logger.error(f"Error in Gaussian blur: {str(e)}") raise
def read_image_file(file_bytes: bytes) -> np.ndarray: """ Read image file bytes and convert to OpenCV format
Args: file_bytes: Raw image file bytes
Returns: Image as numpy array in BGR format """ try: # Convert bytes to PIL Image image = Image.open(BytesIO(file_bytes))
# Convert to RGB if needed if image.mode != 'RGB': image = image.convert('RGB')
# Convert PIL Image to numpy array img_array = np.array(image)
# Convert RGB to BGR for OpenCV img_bgr = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
logger.info(f"Image loaded successfully: shape={img_bgr.shape}") return img_bgr except Exception as e: logger.error(f"Error reading image file: {str(e)}") raise HTTPException(status_code=400, detail=f"Invalid image file: {str(e)}")
def encode_image(img: np.ndarray) -> bytes: """ Encode OpenCV image to PNG bytes
Args: img: Image as numpy array (BGR format)
Returns: PNG encoded bytes """ try: # Encode image to PNG format success, buffer = cv2.imencode('.png', img) if not success: raise Exception("Failed to encode image")
return buffer.tobytes() except Exception as e: logger.error(f"Error encoding image: {str(e)}") raise
@app.get("/")async def root(): """Health check endpoint""" return { "status": "online", "service": "MedTech Image Processing API", "version": "1.0.0", "endpoints": { "/process": "POST - Process medical images with arterial or venous phase filters" } }
@app.post("/process")async def process_image( image: UploadFile = File(..., description="Medical image file (JPG/PNG)"), phase: str = Form(..., description="Processing phase: 'arterial' or 'venous'")): """ Process medical image with selected phase filter
Args: image: Uploaded image file (JPG/PNG) phase: Processing phase - 'arterial' (contrast enhancement) or 'venous' (blur)
Returns: Processed image as PNG """ logger.info(f"Processing request received - Phase: {phase}")
# Validate phase parameter if phase not in ['arterial', 'venous']: raise HTTPException( status_code=400, detail="Invalid phase. Must be 'arterial' or 'venous'" )
# Validate file type if not image.content_type.startswith('image/'): raise HTTPException( status_code=400, detail="File must be an image (JPG/PNG)" )
try: # Read uploaded file file_bytes = await image.read() logger.info(f"File received: {image.filename}, size: {len(file_bytes)} bytes")
# Convert to OpenCV format img = read_image_file(file_bytes)
# Apply processing based on phase if phase == 'arterial': processed_img = increase_contrast(img) logger.info("Arterial phase processing completed") else: # venous processed_img = apply_gaussian_blur(img) logger.info("Venous phase processing completed")
# Encode processed image output_bytes = encode_image(processed_img)
# Return processed image return Response( content=output_bytes, media_type="image/png", headers={ "Content-Disposition": f"inline; filename=processed_{image.filename}", "X-Processing-Phase": phase } )
except HTTPException: raise except Exception as e: logger.error(f"Unexpected error processing image: {str(e)}") raise HTTPException( status_code=500, detail=f"Error processing image: {str(e)}" )
@app.get("/health")async def health_check(): """Detailed health check endpoint""" return { "status": "healthy", "opencv_version": cv2.__version__, "numpy_version": np.__version__ }
if __name__ == "__main__": import uvicorn # Run server on port 7860 (Hugging Face Spaces default) uvicorn.run(app, host="0.0.0.0", port=7860)123456fastapi==0.104.1uvicorn[standard]==0.24.0python-multipart==0.0.6opencv-python-headless==4.8.1.78numpy==1.26.2Pillow==10.1.0.gitattributesAdded+35
DockerfileAdded+29
README.mdAdded+166
app.pyAdded+242
requirements.txtAdded+6