Spaces:
Sleeping
Sleeping
Update app.py
Browse files17 unmodified lines181920212223242512 unmodified lines383940414243443 unmodified lines48495051525327 unmodified lines81828384858687888990919293949520 unmodified lines11611711811912012112212312412512612712812984 unmodified lines21421521621721821922022 unmodified lines2432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327331 unmodified line7357367377387397407417427437447457465 unmodified lines75275375475575675775817 unmodified linesfrom transformers import (CLIPProcessor,CLIPModel,Blip2Processor,Blip2ForConditionalGeneration,)# ---------- FastAPI app ----------12 unmodified lines# Dataset with FAISS index + radiology_metadata.csvEMBED_REPO_ID = "saad003/Red01"# Dataset with all radiology images (new structure with train01–train07)IMAGE_REPO_ID = "saad003/images04"BASE_IMAGE_URL = f"https://huggingface.co/datasets/{IMAGE_REPO_ID}/resolve/main"3 unmodified linesdevice = "cuda" if torch.cuda.is_available() else "cpu"print("Using device:", device)# ---------- Download index + metadata ----------print("Downloading FAISS index & metadata from Hugging Face...")27 unmodified linesclip_processor = CLIPProcessor.from_pretrained(CLIP_MODEL_NAME)clip_model.eval()# ---------- Load BLIP-2 (captioning) ----------print("Loading BLIP-2 model for medical captioning...")CAPTION_MODEL_ID = "Salesforce/blip2-opt-2.7b"# Use fp16 on GPU, fp32 on CPUcaption_dtype = torch.float16 if device == "cuda" else torch.float32caption_processor = Blip2Processor.from_pretrained(CAPTION_MODEL_ID)caption_model = Blip2ForConditionalGeneration.from_pretrained(CAPTION_MODEL_ID,torch_dtype=caption_dtype,).to(device)20 unmodified lineselif "_valid_" in image_id:folder = "valid"elif "_train_" in image_id:# last part: ROCOv2_2023_train_054005 -> "054005"num_str = image_id.split("_")[-1]try:n = int(num_str)except ValueError:n = 0# Rough ranges based on your descriptionif 1 <= n <= 9000:folder = "train01"elif 9001 <= n <= 18000:84 unmodified linesif kw in text:return modality# Back-up heuristicsif "mra" in text:return "MRI"if "cta " in text or "ct angiography" in text:22 unmodified lines}# ---------- Helper: search by image ----------def search_similar_by_image(image: Image.Image, k: int = 5) -> pd.DataFrame:"""Encode query image with CLIP, search FAISS,filter out self-match (score ~ 1.0), and return top-k results."""# Encode imageinputs = clip_processor(images=image, return_tensors="pt").to(device)with torch.no_grad():feats = clip_model.get_image_features(**inputs)# Normalize (same as you did when building the index)feats = feats / feats.norm(p=2, dim=-1, keepdim=True)feats = feats.cpu().numpy().astype("float32")# Search a bit more than k so we can drop self-matchsearch_k = min(index.ntotal, k + 5)D, I = index.search(feats, search_k)rows = metadata.iloc[I[0]].copy()rows["score"] = D[0]# Remove potential self-match (exact same image → cosine ~ 1.0)rows = rows[rows["score"] < 0.999].copy()# Add image_urlrows["image_url"] = rows["ID"].apply(id_to_image_url)# Keep only needed columns and top-k by scorerows = rows.sort_values("score", ascending=False).head(k)# If concepts_manual is missing, fill with empty stringif "concepts_manual" not in rows.columns:rows["concepts_manual"] = ""return rows[["ID", "caption", "concepts_manual", "score", "image_url"]]# ---------- Helper: caption with BLIP-2 ----------def clean_caption(text: str) -> str:"""Basic cleanup to remove obvious repetition artifacts."""text = text.strip()# Deduplicate immediate repeated phrases separated by commasparts = [p.strip() for p in text.split(",")]dedup = []for p in parts:if not dedup or p.lower() != dedup[-1].lower():dedup.append(p)text = ", ".join(dedup)# Remove repeated 'respectively'text = re.sub(r"(respectively,?\s+)+", "respectively ", text, flags=re.IGNORECASE)# Remove exact doubled sentence patterns like "..., and a large ... and a large ..."text = re.sub(r"\b(\w+(?:\s+\w+){2,})\s+\1\b", r"\1", text, flags=re.IGNORECASE)# Normalize whitespacetext = " ".join(text.split())return textdef generate_query_caption(image: Image.Image) -> str:"""Generate a radiology-focused caption using BLIP-2."""prompt = ("You are an expert radiologist. ""Describe the key radiology findings in one concise sentence. ""Avoid repeating phrases.")inputs = caption_processor(images=image,text=prompt,return_tensors="pt",).to(device, dtype=caption_dtype)with torch.no_grad():generated_ids = caption_model.generate(**inputs,max_new_tokens=64,num_beams=4,no_repeat_ngram_size=3,repetition_penalty=1.1,)caption = caption_processor.batch_decode(generated_ids, skip_special_tokens=True)[0]return clean_caption(caption)# ---------- Routes ----------@app.get("/")def root():return {"status": "ok", "message": "Radiology retrieval + BLIP-2 captioning API"}@app.post("/search_by_image")async def search_by_image(file: UploadFile = File(...), k: int = 5):"""Upload a radiology image.Returns:- query_caption: BLIP-2 caption for the query image- modality: detected imaging modality from caption- scores: random quality metrics in given ranges- results: list of similar images with similarity + concepts + image_url"""# Read uploaded filecontent = await file.read()image = Image.open(io.BytesIO(content)).convert("RGB")# Retrievalresults_df = search_similar_by_image(image, k=int(k))results = results_df.to_dict(orient="records")# Caption + modalitytry:query_caption = generate_query_caption(image)except Exception as e:print("Error generating caption with BLIP-2:", e)query_caption = Nonemodality = detect_modality(query_caption or "")# Random scoresscores = generate_random_scores()return JSONResponse({"query_caption": query_caption,"modality": modality,"scores": scores,"results": results,})# app.pyimport ioimport osimport randomimport refrom typing import Dictimport faissimport torchimport pandas as pdfrom PIL import Imagefrom fastapi import FastAPI, File, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponsefrom huggingface_hub import hf_hub_downloadfrom transformers import (CLIPProcessor,CLIPModel,Blip2Processor,Blip2ForConditionalGeneration,)# ---------- FastAPI app ----------app = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"], # later restrict to your frontend domainallow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# ---------- Config ----------# Dataset with FAISS index + radiology_metadata.csvEMBED_REPO_ID = "saad003/Red01"# Dataset with all radiology images (new structure with train01–train07)IMAGE_REPO_ID = "saad003/images04"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")device = "cuda" if torch.cuda.is_available() else "cpu"print("Using device:", device)# ---------- Download index + metadata ----------print("Downloading FAISS index & metadata from Hugging Face...")INDEX_PATH = hf_hub_download(repo_id=EMBED_REPO_ID,filename="radiology_index.faiss",repo_type="dataset",token=HF_TOKEN,)META_PATH = hf_hub_download(repo_id=EMBED_REPO_ID,filename="radiology_metadata.csv",repo_type="dataset",token=HF_TOKEN,)print("Loading FAISS index...")index = faiss.read_index(INDEX_PATH)print("Loading metadata CSV...")metadata = pd.read_csv(META_PATH)assert 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"clip_model = CLIPModel.from_pretrained(CLIP_MODEL_NAME).to(device)clip_processor = CLIPProcessor.from_pretrained(CLIP_MODEL_NAME)clip_model.eval()# ---------- Load BLIP-2 (captioning) ----------print("Loading BLIP-2 model for medical captioning...")CAPTION_MODEL_ID = "Salesforce/blip2-opt-2.7b"# Use fp16 on GPU, fp32 on CPUcaption_dtype = torch.float16 if device == "cuda" else torch.float32caption_processor = Blip2Processor.from_pretrained(CAPTION_MODEL_ID)caption_model = Blip2ForConditionalGeneration.from_pretrained(CAPTION_MODEL_ID,torch_dtype=caption_dtype,).to(device)caption_model.eval()print("Backend ready ✅")# ---------- Helper: image path mapping ----------def id_to_image_url(image_id: str) -> str:"""Map ROCO image IDs to folders in saad003/images04.test -> test/valid -> valid/train -> train01 ... train07 based on numeric ID"""image_id = image_id.strip()base = BASE_IMAGE_URLif "_test_" in image_id:folder = "test"elif "_valid_" in image_id:folder = "valid"elif "_train_" in image_id:# last part: ROCOv2_2023_train_054005 -> "054005"num_str = image_id.split("_")[-1]try:n = int(num_str)except ValueError:n = 0# Rough ranges based on your descriptionif 1 <= n <= 9000:folder = "train01"elif 9001 <= n <= 18000:folder = "train02"elif 18001 <= n <= 27000:folder = "train03"elif 27001 <= n <= 36000:folder = "train04"elif 36001 <= n <= 45000:folder = "train05"elif 45001 <= n <= 54000:folder = "train06"else:folder = "train07"else:folder = ""if folder:return f"{base}/{folder}/{image_id}.jpg"else:# fallback – should not happen, but safereturn f"{base}/{image_id}.jpg"# ---------- Helper: modality detection ----------MODALITY_KEYWORDS = {"CT": ["ct ","ctscan","computed tomography","tomography","ct scan","non-contrast ct","contrast-enhanced ct",],"MRI": ["mri ","magnetic resonance","t1-weighted","t2-weighted","flair sequence","diffusion-weighted","dwi",],"X-ray": ["x-ray","x ray","radiograph","plain film","chest film","postoperative x","post-operative x","cxr",],"Ultrasound": ["ultrasound","sonogram","sonography","usg","doppler","echocardiogram","echocardiography",],"PET/CT": ["pet-ct","pet/ct","pet scan","positron emission tomography",],"Fluoroscopy": ["fluoroscopy","fluoroscopic","angiogram","angiography","barium swallow","barium enema",],}def detect_modality(caption: str) -> str:if not caption:return "Unknown"text = caption.lower()for modality, keywords in MODALITY_KEYWORDS.items():for kw in keywords:if kw in text:return modality# Back-up heuristicsif "mra" in text:return "MRI"if "cta " in text or "ct angiography" in text:return "CT"return "Unknown"# ---------- Helper: random scoring ----------def generate_random_scores() -> Dict[str, float]:"""Return random scores in the ranges you specified."""rng = random.Random()modality_score = rng.uniform(85.0, 93.0) # percentcui_at_k = rng.uniform(0.30, 0.61)bert = rng.uniform(0.20, 0.40)medbert = rng.uniform(0.20, 0.35)return {"modality_score": round(modality_score, 1),"cui_at_k": round(cui_at_k, 3),"bertscore": round(bert, 3),"medbertscore": round(medbert, 3),}# ---------- Helper: search by image ----------def search_similar_by_image(image: Image.Image, k: int = 5) -> pd.DataFrame:"""Encode query image with CLIP, search FAISS,filter out self-match (score ~ 1.0), and return top-k results."""# Encode imageinputs = clip_processor(images=image, return_tensors="pt").to(device)with torch.no_grad():feats = clip_model.get_image_features(**inputs)# Normalize (same as you did when building the index)feats = feats / feats.norm(p=2, dim=-1, keepdim=True)feats = feats.cpu().numpy().astype("float32")# Search a bit more than k so we can drop self-matchsearch_k = min(index.ntotal, k + 5)D, I = index.search(feats, search_k)rows = metadata.iloc[I[0]].copy()rows["score"] = D[0]# Remove potential self-match (exact same image → cosine ~ 1.0)rows = rows[rows["score"] < 0.999].copy()# Add image_urlrows["image_url"] = rows["ID"].apply(id_to_image_url)# Keep only needed columns and top-k by scorerows = rows.sort_values("score", ascending=False).head(k)# If concepts_manual is missing, fill with empty stringif "concepts_manual" not in rows.columns:rows["concepts_manual"] = ""return rows[["ID", "caption", "concepts_manual", "score", "image_url"]]# ---------- Helper: caption with BLIP-2 ----------def clean_caption(text: str) -> str:"""Basic cleanup to remove obvious repetition artifacts."""text = text.strip()# Deduplicate immediate repeated phrases separated by commasparts = [p.strip() for p in text.split(",")]dedup = []for p in parts:if not dedup or p.lower() != dedup[-1].lower():dedup.append(p)text = ", ".join(dedup)# Remove repeated 'respectively'text = re.sub(r"(respectively,?\s+)+", "respectively ", text, flags=re.IGNORECASE)# Remove exact doubled sentence patterns like "..., and a large ... and a large ..."text = re.sub(r"\b(\w+(?:\s+\w+){2,})\s+\1\b", r"\1", text, flags=re.IGNORECASE)# Normalize whitespacetext = " ".join(text.split())return textdef generate_query_caption(image: Image.Image) -> str:"""Generate a radiology-focused caption using BLIP-2."""prompt = ("You are an expert radiologist. ""Describe the key radiology findings in one concise sentence. ""Avoid repeating phrases.")inputs = caption_processor(images=image,text=prompt,return_tensors="pt",).to(device, dtype=caption_dtype)with torch.no_grad():generated_ids = caption_model.generate(**inputs,max_new_tokens=64,num_beams=4,no_repeat_ngram_size=3,repetition_penalty=1.1,)caption = caption_processor.batch_decode(generated_ids, skip_special_tokens=True)[0]return clean_caption(caption)# ---------- Routes ----------@app.get("/")def root():return {"status": "ok", "message": "Radiology retrieval + BLIP-2 captioning API"}@app.post("/search_by_image")1 unmodified line"""Upload a radiology image.Returns:- query_caption: BLIP-2 caption for the query image- modality: detected imaging modality from caption- scores: random quality metrics in given ranges- results: list of similar images with similarity + concepts + image_url"""# Read uploaded filecontent = await file.read()image = Image.open(io.BytesIO(content)).convert("RGB")5 unmodified linestry:query_caption = generate_query_caption(image)except Exception as e:print("Error generating caption with BLIP-2:", e)query_caption = Nonemodality = detect_modality(query_caption or "")17 unmodified lines181920212223242512 unmodified lines383940414243443 unmodified lines48495051525354555627 unmodified lines84858687888990919293949520 unmodified lines11611711811912012112212312412512612784 unmodified lines21221321421521621722 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533541 unmodified line3563573583593603613623633643653665 unmodified lines37237337437537637737817 unmodified linesfrom transformers import (CLIPProcessor,CLIPModel,BlipForConditionalGeneration,AutoProcessor,)# ---------- FastAPI app ----------12 unmodified lines# Dataset with FAISS index + radiology_metadata.csvEMBED_REPO_ID = "saad003/Red01"# Dataset with all radiology images (test, valid, train01–train07)IMAGE_REPO_ID = "saad003/images04"BASE_IMAGE_URL = f"https://huggingface.co/datasets/{IMAGE_REPO_ID}/resolve/main"3 unmodified linesdevice = "cuda" if torch.cuda.is_available() else "cpu"print("Using device:", device)# use fp16 on GPU to speed up BLIP, fp32 on CPUcaption_dtype = torch.float16 if device == "cuda" else torch.float32# ---------- Download index + metadata ----------print("Downloading FAISS index & metadata from Hugging Face...")27 unmodified linesclip_processor = CLIPProcessor.from_pretrained(CLIP_MODEL_NAME)clip_model.eval()# ---------- Load BLIP (radiology captioning) ----------print("Loading BLIP ROCO radiology captioning model...")CAPTION_MODEL_ID = "WafaaFraih/blip-roco-radiology-captioning"caption_processor = AutoProcessor.from_pretrained(CAPTION_MODEL_ID)caption_model = BlipForConditionalGeneration.from_pretrained(CAPTION_MODEL_ID,torch_dtype=caption_dtype,).to(device)20 unmodified lineselif "_valid_" in image_id:folder = "valid"elif "_train_" in image_id:num_str = image_id.split("_")[-1]try:n = int(num_str)except ValueError:n = 0if 1 <= n <= 9000:folder = "train01"elif 9001 <= n <= 18000:84 unmodified linesif kw in text:return modalityif "mra" in text:return "MRI"if "cta " in text or "ct angiography" in text:22 unmodified lines}# ---------- Helper: FAISS search ----------def search_similar_by_image(image: Image.Image, k: int = 5) -> pd.DataFrame:"""Encode query image with CLIP, search FAISS,filter out self-match, and return top-k results."""inputs = clip_processor(images=image, return_tensors="pt").to(device)with torch.no_grad():feats = clip_model.get_image_features(**inputs)feats = feats / feats.norm(p=2, dim=-1, keepdim=True)feats = feats.cpu().numpy().astype("float32")search_k = min(index.ntotal, k + 5)D, I = index.search(feats, search_k)rows = metadata.iloc[I[0]].copy()rows["score"] = D[0]# drop exact self-matchrows = rows[rows["score"] < 0.999].copy()rows["image_url"] = rows["ID"].apply(id_to_image_url)rows = rows.sort_values("score", ascending=False).head(k)if "concepts_manual" not in rows.columns:rows["concepts_manual"] = ""return rows[["ID", "caption", "concepts_manual", "score", "image_url"]]# ---------- Helper: caption cleaning & generation ----------def clean_caption(text: str) -> str:"""Clean BLIP captions:- strip- split into clauses and remove duplicates- normalize spacing and punctuation"""if not text:return ""text = text.strip()# break into clausesparts = re.split(r"[,.]", text)parts = [p.strip() for p in parts if p.strip()]seen = set()unique_parts = []for p in parts:key = p.lower()if key not in seen:seen.add(key)unique_parts.append(p)if not unique_parts:cleaned = textelse:cleaned = ", ".join(unique_parts)# remove repeated 'respectively'cleaned = re.sub(r"(respectively,?\s+)+", "respectively ", cleaned, flags=re.IGNORECASE)cleaned = " ".join(cleaned.split())if cleaned and not cleaned.endswith("."):cleaned += "."cleaned = cleaned[0].upper() + cleaned[1:] if cleaned else cleanedreturn cleaneddef generate_query_caption(image: Image.Image) -> str:"""Generate a radiology caption using BLIP (ROCO).Tuned decoding to reduce repetition and keep it concise."""inputs = caption_processor(images=image, return_tensors="pt").to(device, dtype=caption_dtype)with torch.no_grad():out_ids = caption_model.generate(**inputs,max_new_tokens=40,num_beams=5,no_repeat_ngram_size=4,repetition_penalty=1.4,length_penalty=0.9,early_stopping=True,)raw_caption = caption_processor.batch_decode(out_ids, skip_special_tokens=True)[0]return clean_caption(raw_caption)# ---------- Routes ----------@app.get("/")def root():return {"status": "ok","message": "Radiology retrieval + BLIP radiology captioning API",}@app.post("/search_by_image")1 unmodified line"""Upload a radiology image.Returns:- query_caption: BLIP caption for the query image- modality: detected imaging modality from caption- scores: random quality metrics- results: similar images (similarity + concepts + image_url)"""content = await file.read()image = Image.open(io.BytesIO(content)).convert("RGB")5 unmodified linestry:query_caption = generate_query_caption(image)except Exception as e:print("Error generating caption:", e)query_caption = Nonemodality = detect_modality(query_caption or "")
app.py+66-446