Spaces:
Sleeping
Sleeping
Update app.py
Browse files20 unmodified lines212223242526273 unmodified lines31323334353637383940414219 unmodified lines62636465666718 unmodified lines86878889909192939495969798991001011021031 unmodified line10510610710810911011111211311411511611711811912012112212312412512612712812912 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516616712 unmodified lines1801811821831841851861871884 unmodified lines19319419519619719819920020120220 unmodified lines# Allow your React app to call this APIapp.add_middleware(CORSMiddleware,allow_origins=["*"], # you can later restrict thisallow_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 (flat, filenames only)# e.g. ROCOv2_2023_test_000001.jpg in the rootIMAGE_REPO_ID = "saad003/images"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)assert index.ntotal == len(metadata), "Index size and metadata rows mismatch!"# ---------- Load CLIP (retrieval) ----------18 unmodified linesprint("Backend ready ✅")# ---------- Helper: build image URL from img_path ----------def img_path_to_image_url(img_path: str) -> str:"""Your images dataset `saad003/images` has files directly in root:ROCOv2_2023_train_000001.jpgROCOv2_2023_valid_000001.jpgROCOv2_2023_test_000001.jpgso we only need the filename from img_path."""if not isinstance(img_path, str):return Nonefilename = os.path.basename(img_path)return f"{BASE_IMAGE_URL}/{filename}"1 unmodified linedef search_similar_by_image(image: Image.Image, k: int = 5) -> pd.DataFrame:"""Encode query image with CLIP, search FAISS, return top-k rowscontaining ID, split, caption, concepts, score, image_url."""inputs = clip_processor(images=image, return_tensors="pt").to(device)with torch.no_grad():feats = clip_model.get_image_features(**inputs)# Normalize (must match how index was created)feats = feats / feats.norm(p=2, dim=-1, keepdim=True)feats = feats.cpu().numpy().astype("float32")D, I = index.search(feats, k) # D: distances, I: indicesrows = metadata.iloc[I[0]].copy()rows["score"] = D[0]# build URL using only the filenamerows["image_url"] = rows["img_path"].apply(img_path_to_image_url)return rows[["ID", "split", "caption", "concepts_manual", "score", "image_url"]]# ---------- Helper: generate caption for query image ----------12 unmodified lines# ---------- Helper: infer modality from caption ----------def infer_modality_from_caption(caption: str) -> str:"""Simple heuristic to infer imaging modality based on caption text."""if not caption:return "Unknown"text = caption.lower()if any(word in text for word in ["ct scan", "ct of", "computed tomography"]):return "CT"if any(word in text for word in ["mri", "magnetic resonance"]):return "MRI"if any(word in text for word in ["x-ray", "x ray", "radiograph", "chest xray", "chest x-ray"]):return "X-ray"if any(word in text for word in ["ultrasound", "sonography", "sonogram"]):return "Ultrasound"if any(word in text for word in ["pet-ct", "pet ct", "pet scan", "positron emission tomography"]):return "PET/CT"return "Unknown"12 unmodified linesUpload a radiology image.Returns:- query_caption: generated caption for the query image- modality: inferred imaging modality from the caption- results: list of similar images with their concepts, scores, and image URLs"""content = await file.read()image = Image.open(io.BytesIO(content)).convert("RGB")4 unmodified lines# 2) Captioning for the query imagetry:query_caption = generate_query_caption(image)except Exception as e:print("Error generating caption:", e)query_caption = None# 3) Infer modalitymodality = infer_modality_from_caption(query_caption or "")20 unmodified lines212223242526273 unmodified lines31323334353637383940414219 unmodified lines62636465666768697071727318 unmodified lines92939495969798991001011021031041051061071 unmodified line10911011111211311411511611711811912012112212312412512612712812913013113213313413513612 unmodified lines14915015115215315415515615715815916016116216316416516616716816917017117217317412 unmodified lines1871881891901911921931941954 unmodified lines20020120220320420520620720820920 unmodified lines# Allow your React app to call this APIapp.add_middleware(CORSMiddleware,allow_origins=["*"], # you can restrict laterallow_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 (flat: ID + ".jpg" in root)# e.g. ROCOv2_2023_valid_000001.jpgIMAGE_REPO_ID = "saad003/images"BASE_IMAGE_URL = f"https://huggingface.co/datasets/{IMAGE_REPO_ID}/resolve/main"# Optional: token if Red01 is private (set HF_TOKEN secret on the Space)HF_TOKEN = os.environ.get("HF_TOKEN")# ---------- Download index + metadata ----------19 unmodified linesprint("Loading metadata CSV...")metadata = pd.read_csv(META_PATH)# We will only rely on: vec_index, ID, caption, concepts_manualrequired_cols = {"vec_index", "ID", "caption", "concepts_manual"}missing = required_cols - set(metadata.columns)if missing:raise ValueError(f"radiology_metadata.csv is missing columns: {missing}")assert index.ntotal == len(metadata), "Index size and metadata rows mismatch!"# ---------- Load CLIP (retrieval) ----------18 unmodified linesprint("Backend ready ✅")# ---------- Helper: build image URL from ID ----------def id_to_image_url(image_id: str) -> str:"""Your images dataset `saad003/images` has files like:ROCOv2_2023_valid_000001.jpgwhere filename = ID + ".jpg"."""if not isinstance(image_id, str):return Nonefilename = f"{image_id}.jpg"return f"{BASE_IMAGE_URL}/{filename}"1 unmodified linedef search_similar_by_image(image: Image.Image, k: int = 5) -> pd.DataFrame:"""Encode query image with CLIP, search FAISS, return top-k rowscontaining vec_index, ID, caption, concepts_manual, score, image_url."""# Encode imageinputs = clip_processor(images=image, return_tensors="pt").to(device)with torch.no_grad():feats = clip_model.get_image_features(**inputs)# Normalize (must match how index was built)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, I: indices# Get rows for top-k indicesrows = metadata.iloc[I[0]].copy()rows["score"] = D[0]# Build URL from ID onlyrows["image_url"] = rows["ID"].apply(id_to_image_url)return rows[["vec_index", "ID", "caption", "concepts_manual", "score", "image_url"]]# ---------- Helper: generate caption for query image ----------12 unmodified lines# ---------- Helper: infer modality from caption ----------def infer_modality_from_caption(caption: str) -> str:"""Simple heuristic to infer imaging modality (CT, MRI, X-ray, etc.)."""if not caption:return "Unknown"text = caption.lower()if any(w in text for w in ["ct scan", "ct of", "computed tomography"]):return "CT"if any(w in text for w in ["mri", "magnetic resonance"]):return "MRI"if any(w in text for w in ["x-ray", "x ray", "radiograph", "chest xray", "chest x-ray"]):return "X-ray"if any(w in text for w in ["ultrasound", "sonography", "sonogram"]):return "Ultrasound"if any(w in text for w in ["pet-ct", "pet ct", "pet scan", "positron emission tomography"]):return "PET/CT"return "Unknown"12 unmodified linesUpload 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 vec_index, ID, concepts_manual, score, image_url"""content = await file.read()image = Image.open(io.BytesIO(content)).convert("RGB")4 unmodified lines# 2) Captioning for the query imagetry:query_caption = generate_query_caption(image)except Exception as e:print("Error generating caption:", e)query_caption = None# 3) Infer modalitymodality = infer_modality_from_caption(query_caption or "")
app.py+35-28