Arpit-Bansal commited on
Commit
b009852
·
1 Parent(s): 3fc6785

Push Files

Browse files
Files changed (5) hide show
  1. .gitignore +3 -0
  2. __init__.py +2 -0
  3. embedding_generator.py +86 -0
  4. main.py +49 -0
  5. requirements.txt +4 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ venv/
2
+ .env
3
+ __pycache__/
__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ import sys
2
+ sys.path.append("..")
embedding_generator.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import login, from_pretrained_keras
2
+
3
+ import os
4
+ import glob
5
+ import time
6
+ import h5py
7
+ import numpy as np
8
+ # import pandas as pd
9
+ from PIL import Image
10
+ from tqdm import tqdm
11
+ import tensorflow as tf
12
+ from dotenv import load_dotenv
13
+
14
+ load_dotenv()
15
+
16
+ hf_token = os.getenv("HF_TOKEN")
17
+ if hf_token is None:
18
+ raise ValueError("Hugging Face token not found. Please set the HF_TOKEN environment variable.")
19
+ login(token=hf_token)
20
+
21
+ def load_model():
22
+ """Load PathFoundation model from Hugging Face"""
23
+ print("Loading PathFoundation model...")
24
+ model = from_pretrained_keras("google/path-foundation")
25
+ infer = model.signatures["serving_default"]
26
+ print("Model loaded!")
27
+ return infer
28
+
29
+ def load_model():
30
+ """Load PathFoundation model from Hugging Face"""
31
+ print("Loading PathFoundation model...")
32
+ import tensorflow as tf
33
+ import keras
34
+ from huggingface_hub import snapshot_download
35
+
36
+ # Download the model from HuggingFace
37
+ model_path = snapshot_download(repo_id="google/path-foundation")
38
+
39
+ # Load as TFSMLayer
40
+ model = keras.layers.TFSMLayer(
41
+ model_path,
42
+ call_endpoint='serving_default'
43
+ )
44
+ print("Model loaded!")
45
+ return model
46
+
47
+
48
+ def process_image(image_input, infer_function):
49
+ """Process a single image and get embedding
50
+
51
+ Args:
52
+ image_input: Either a file path (str) or image data (bytes/BytesIO/numpy array)
53
+ infer_function: The model inference function
54
+
55
+ Returns:
56
+ Embedding vector or None if processing fails
57
+ """
58
+ try:
59
+ # Handle different input types
60
+ if isinstance(image_input, str):
61
+ # It's a file path
62
+ img = Image.open(image_input).convert('RGB')
63
+ elif isinstance(image_input, bytes) or hasattr(image_input, 'read'):
64
+ # It's image data from frontend (bytes or BytesIO)
65
+ img = Image.open(image_input).convert('RGB')
66
+ elif isinstance(image_input, np.ndarray):
67
+ # It's already a numpy array
68
+ img = Image.fromarray(image_input.astype('uint8')).convert('RGB')
69
+ else:
70
+ raise ValueError(f"Unsupported image input type: {type(image_input)}")
71
+
72
+ # Resize to 224x224 if needed
73
+ if img.size != (224, 224):
74
+ img = img.resize((224, 224))
75
+ # Convert to tensor and normalize
76
+ tensor = tf.cast(tf.expand_dims(np.array(img), axis=0), tf.float32) / 255.0
77
+
78
+ # Get embedding
79
+ embeddings = infer_function(tf.constant(tensor))
80
+
81
+ embedding_vector = embeddings['output_0'].numpy().flatten()
82
+
83
+ return embedding_vector
84
+ except Exception as e:
85
+ print(f"Error processing image: {e}")
86
+ return None
main.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ import uvicorn
4
+ from typing import List
5
+ import os
6
+ import numpy as np
7
+ from PIL import Image
8
+ import io
9
+ from embedding_generator import load_model, process_image
10
+
11
+ app = FastAPI(title="Medical Image Embedding Generator")
12
+
13
+
14
+ global infer
15
+ infer = load_model()
16
+
17
+
18
+ @app.post("/embeddings")
19
+ async def generate_embeddings(file: UploadFile = File(...)):
20
+ """
21
+ Upload a medical image (JPEG, PNG, TIFF) and get embeddings
22
+ """
23
+ content_type = file.content_type
24
+ if not (content_type.startswith("image/") or
25
+ file.filename.endswith((".tif", ".tiff", ".jpg", ".jpeg", ".png", ".bmp"))):
26
+ raise HTTPException(status_code=400, detail="File must be an image (JPEG, PNG, BMP) or TIFF format")
27
+
28
+ try:
29
+ # Read the file content
30
+ embedding = process_image(file.file, infer)
31
+ if embedding is None:
32
+ raise HTTPException(status_code=500, detail="Error processing image")
33
+
34
+ return_content = {
35
+ "filename": file.filename,
36
+ "embedding": embedding.tolist(),
37
+ }
38
+
39
+ return JSONResponse(content=return_content)
40
+
41
+ except Exception as e:
42
+ raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
43
+
44
+ @app.get("/")
45
+ async def root():
46
+ return {"message": "Welcome to Medical Image Embedding Generator API. Use /embeddings endpoint to upload images."}
47
+
48
+ if __name__ == "__main__":
49
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ tf-nightly[and-cuda]
2
+ python-dotenv
3
+ pillow
4
+ huggingface-hub