Spaces:
Sleeping
Sleeping
Update app.py
Browse files17 unmodified lines181920212223242526273 unmodified lines313233343536373839404119 unmodified lines6162636465666768697015 unmodified lines868788899091929394959697987 unmodified lines10610710810911011111211311411511611711811912012112212312411 unmodified lines1361371381391401415 unmodified lines14714814915015115215315410 unmodified lines16516616716816917017117217317 unmodified lines# ---------- FastAPI app ----------app = FastAPI()# CORS so your React app can call this APIapp.add_middleware(CORSMiddleware,allow_origins=["*"], # later you can restrict to your frontend domainallow_credentials=True,allow_methods=["*"],allow_headers=["*"],3 unmodified lines# Dataset with FAISS index + radiology_metadata.csvEMBED_REPO_ID = "saad003/Red01"# Dataset with all radiology images you uploadedIMAGE_REPO_ID = "saad003/images02"BASE_IMAGE_URL = f"https://huggingface.co/datasets/{IMAGE_REPO_ID}/resolve/main"# Optional: token if Red01 is privateHF_TOKEN = os.environ.get("HF_TOKEN")# ---------- Download index + metadata ----------19 unmodified linesprint("Loading metadata CSV...")metadata = pd.read_csv(META_PATH)# Make sure the index and metadata have same lengthassert index.ntotal == len(metadata), "Index size and metadata rows mismatch!"# ---------- Load CLIP (retrieval) ----------print("Loading PubMedCLIP model for retrieval...")CLIP_MODEL_NAME = "flaviagiammarino/pubmed-clip-vit-base-patch32"15 unmodified linesprint("Backend ready ✅")# ---------- Helper: build image URL ----------def id_to_image_url(image_id: str) -> str:"""Build a public URL to the image in saad003/images02.Assumes filenames are exactly f\"{image_id}.jpg\"."""return f"{BASE_IMAGE_URL}/{image_id}.jpg"# ---------- Helper: search by image ----------7 unmodified lineswith torch.no_grad():feats = clip_model.get_image_features(**inputs)# Normalize (very important, matches how you created the index)feats = feats / feats.norm(p=2, dim=-1, keepdim=True)feats = feats.cpu().numpy().astype("float32")# Search in FAISSD, I = index.search(feats, k) # D: distances/similarity, I: indices# Get metadata rows for top-k indicesrows = metadata.iloc[I[0]].copy()rows["score"] = D[0]# Add image_url for each resultrows["image_url"] = rows["ID"].apply(id_to_image_url)return rows[["ID", "split", "caption", "concepts_manual", "score", "image_url"]]11 unmodified linesreturn caption.strip()# ---------- Routes ----------@app.get("/")5 unmodified linesasync def search_by_image(file: UploadFile = File(...), k: int = 5):"""Upload a radiology image.Returns:- query_caption: generated caption for the query image- results: list of similar images with their captions, concepts, score, image_url"""content = await file.read()10 unmodified linesprint("Error generating caption:", e)query_caption = Nonereturn JSONResponse({"query_caption": query_caption,"results": results,})17 unmodified lines181920212223242526273 unmodified lines313233343536373839404119 unmodified lines616263646566676869707115 unmodified lines878889909192939495969798991001011021031041051061071081091101111121131141151161171181197 unmodified lines12712812913013113213313413513613713813914014114214314414511 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941955 unmodified lines20120220320420520620720820921010 unmodified lines22122222322422522622722822923023123223317 unmodified lines# ---------- FastAPI app ----------app = FastAPI()# Allow your React app to call this APIapp.add_middleware(CORSMiddleware,allow_origins=["*"], # You can later restrict to your domainallow_credentials=True,allow_methods=["*"],allow_headers=["*"],3 unmodified lines# Dataset with FAISS index + radiology_metadata.csvEMBED_REPO_ID = "saad003/Red01"# Dataset with all radiology images (you uploaded here)IMAGE_REPO_ID = "saad003/images02"BASE_IMAGE_URL = f"https://huggingface.co/datasets/{IMAGE_REPO_ID}/resolve/main"# Optional: token if Red01 is private (set HF_TOKEN secret in Space)HF_TOKEN = os.environ.get("HF_TOKEN")# ---------- Download index + metadata ----------19 unmodified linesprint("Loading metadata CSV...")metadata = pd.read_csv(META_PATH)# Sanity checkassert index.ntotal == len(metadata), "Index size and metadata rows mismatch!"# ---------- Load CLIP (retrieval) ----------# IMPORTANT: must match the model you used to build the index.print("Loading PubMedCLIP model for retrieval...")CLIP_MODEL_NAME = "flaviagiammarino/pubmed-clip-vit-base-patch32"15 unmodified linesprint("Backend ready ✅")# ---------- Helper: build image URL from img_path ----------def img_path_to_image_url(img_path: str) -> str:"""Use the original img_path from Kaggle and map it to your HF dataset.Example img_path in CSV:/kaggle/input/radiology/8333645/train_images/train/ROCOv2_2023_train_000001.jpgIf you uploaded folders train_images/..., test_images/..., valid_images/... intosaad003/images02, the relative path after '8333645/' is what we want.So URL becomes:https://huggingface.co/datasets/saad003/images02/resolve/main/train_images/train/ROCOv2_2023_train_000001.jpg"""if not isinstance(img_path, str):return None# Try to cut everything up to the Kaggle dataset rootmarker = "8333645/"if marker in img_path:rel = img_path.split(marker, 1)[1]else:# Fallback: just take the filenamerel = os.path.basename(img_path)rel = rel.lstrip("/") # safetyreturn f"{BASE_IMAGE_URL}/{rel}"# ---------- Helper: search by image ----------7 unmodified lineswith torch.no_grad():feats = clip_model.get_image_features(**inputs)# Normalize (very important, must match index construction)feats = feats / feats.norm(p=2, dim=-1, keepdim=True)feats = feats.cpu().numpy().astype("float32")# Search FAISSD, I = index.search(feats, k) # D: distances/similarity, I: indices# Get metadata rows for top-k indicesrows = metadata.iloc[I[0]].copy()rows["score"] = D[0]# Add image_url using original img_path columnrows["image_url"] = rows["img_path"].apply(img_path_to_image_url)return rows[["ID", "split", "caption", "concepts_manual", "score", "image_url"]]11 unmodified linesreturn caption.strip()# ---------- Helper: infer modality from caption ----------def infer_modality_from_caption(caption: str) -> str:"""Simple heuristic to map a caption to imaging modality."""if not caption:return "Unknown"text = caption.lower()# CTif any(word in text for word in ["ct scan", "computed tomography", "ct of", "ct image", "ct of the"]):return "CT"# MRIif any(word in text for word in ["mri", "magnetic resonance"]):return "MRI"# X-ray / radiographif any(word in text for word in ["x-ray", "x ray", "radiograph", "chest xray", "chest x-ray"]):return "X-ray"# Ultrasoundif any(word in text for word in ["ultrasound", "sonography", "sonogram"]):return "Ultrasound"# PET / PET-CTif any(word in text for word in ["pet-ct", "pet ct", "pet scan", "positron emission tomography"]):return "PET/CT"return "Unknown"# ---------- Routes ----------@app.get("/")5 unmodified linesasync def search_by_image(file: UploadFile = File(...), k: int = 5):"""Upload a radiology image.Returns:- query_caption: generated caption for the query image (BLIP)- modality: inferred imaging modality from the caption- results: list of similar images with their captions, concepts, score, image_url"""content = await file.read()10 unmodified linesprint("Error generating caption:", e)query_caption = None# 3) Infer modalitymodality = infer_modality_from_caption(query_caption or "")return JSONResponse({"query_caption": query_caption,"modality": modality,"results": results,})
app.py+75-15