Spaces:
Sleeping
Sleeping
Update main.py
Browse files11 unmodified lines1213141516171818 unmodified lines373839404142434445464748495051524 unmodified lines575859606162631 unmodified line656667686970711 unmodified line7374757677787980818283844 unmodified lines899091929394959697989910010110210310410510611 unmodified linesapp = FastAPI(title="MedGuard API")# --- CORS CONFIGURATION ---# Allow everything to prevent connection issuesapp.add_middleware(CORSMiddleware,allow_origins=["*"],18 unmodified linesprint("✅ Model Loaded Successfully!")except Exception as e:print(f"❌ Error loading local model: {e}")# Fallback to base model if custom model is missingMODEL_NAME = "csebuetnlp/banglabert"tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=3)# --- DATA MODELS ---class QueryRequest(BaseModel):genre: str = "" # New Fieldprompt: str = "" # New Fieldtext: str # This represents the AI Responseclass PredictionResponse(BaseModel):label: str4 unmodified linesLABELS = ["Highly Relevant", "Partially Relevant", "Not Relevant"]def predict_proba_lime(texts):# LIME passes a list of strings. We tokenize them directly.inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=128).to(DEVICE)with torch.no_grad():outputs = model(**inputs)1 unmodified line@app.get("/")def health_check():return {"status": "active", "model": "MedGuard v2.0 (Structured Input)"}@app.post("/predict", response_model=PredictionResponse)def predict(request: QueryRequest):1 unmodified lineraise HTTPException(status_code=503, detail="Model not loaded")try:# 1. CONSTRUCT INPUT# Combine the 3 fields into one context string for the modelparts = [part for part in [request.genre, request.prompt, request.text] if part]full_input = " ".join(parts)print(f"📥 Analyzing: {full_input[:50]}...")# 2. PREDICTinputs = tokenizer(full_input, return_tensors="pt", truncation=True, max_length=128).to(DEVICE)4 unmodified linespred_idx = np.argmax(probs)# 3. EXPLAIN (LIME)# Custom splitter for Bangla to keep words intactexplainer = LimeTextExplainer(class_names=LABELS,split_expression=lambda x: x.split())# Explain the FULL input so we see if Genre/Prompt influenced the decisionexp = explainer.explain_instance(full_input,predict_proba_lime,num_features=6,num_samples=40, # Low sample count for faster CPU inferencelabels=[pred_idx])lime_features = exp.as_list(label=pred_idx)11 unmodified lines12131415161718 unmodified lines363738394041424344454647484950514 unmodified lines5657585960611 unmodified line636465666768691 unmodified line71727374757677787980818283848586878889904 unmodified lines959697989910010110210310410510610710810911011 unmodified linesapp = FastAPI(title="MedGuard API")# --- CORS CONFIGURATION ---app.add_middleware(CORSMiddleware,allow_origins=["*"],18 unmodified linesprint("✅ Model Loaded Successfully!")except Exception as e:print(f"❌ Error loading local model: {e}")# FallbackMODEL_NAME = "csebuetnlp/banglabert"tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=3)# --- DATA MODELS ---class QueryRequest(BaseModel):genre: str = ""prompt: str = ""text: strclass PredictionResponse(BaseModel):label: str4 unmodified linesLABELS = ["Highly Relevant", "Partially Relevant", "Not Relevant"]def predict_proba_lime(texts):inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=128).to(DEVICE)with torch.no_grad():outputs = model(**inputs)1 unmodified line@app.get("/")def health_check():return {"status": "active", "model": "MedGuard v2.0"}@app.post("/predict", response_model=PredictionResponse)def predict(request: QueryRequest):1 unmodified lineraise HTTPException(status_code=503, detail="Model not loaded")try:# 1. CONSTRUCT INPUT (CRITICAL FIX)# If trained on combined columns, we need to replicate that structure.# We'll use a separator that BERT understands or just spaces if unsure.# Format: "Genre: ... Prompt: ... Response: ..." helps context.# Option A: Simple Concatenation (Most likely what you trained on)# full_input = f"{request.genre} {request.prompt} {request.text}"# Option B: Contextual Concatenation (Better for robustness if model allows)# Using [SEP] token is standard for BERT-like models to separate segmentssep = tokenizer.sep_token if tokenizer.sep_token else " "full_input = f"{request.genre} {sep} {request.prompt} {sep} {request.text}"print(f"📥 Analyzing: {full_input[:100]}...")# 2. PREDICTinputs = tokenizer(full_input, return_tensors="pt", truncation=True, max_length=128).to(DEVICE)4 unmodified linespred_idx = np.argmax(probs)# 3. EXPLAIN (LIME)explainer = LimeTextExplainer(class_names=LABELS,split_expression=lambda x: x.split())exp = explainer.explain_instance(full_input,predict_proba_lime,num_features=6,num_samples=40,labels=[pred_idx])lime_features = exp.as_list(label=pred_idx)
main.py+19-15