Spaces:
Sleeping
Sleeping
Update main.py
Browse files11 unmodified lines1213141515161718 unmodified lines36373840394041424344454748494647484950514 unmodified lines565758605960611 unmodified line63646568666768691 unmodified line717273767778797475767778798081828384858681878889904 unmodified lines9596979298991001011029810310410510610310710810911011 unmodified linesapp = FastAPI(title="MedGuard API")
# --- CORS CONFIGURATION ---# Allow everything to prevent connection issuesapp.add_middleware( CORSMiddleware, allow_origins=["*"], 18 unmodified lines print("✅ Model Loaded Successfully!")except Exception as e: print(f"❌ Error loading local model: {e}") # Fallback to base model if custom model is missing # Fallback MODEL_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 Field prompt: str = "" # New Field text: str # This represents the AI Response genre: str = "" prompt: str = "" text: str
class 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)"} return {"status": "active", "model": "MedGuard v2.0"}
@app.post("/predict", response_model=PredictionResponse)def predict(request: QueryRequest):1 unmodified line raise HTTPException(status_code=503, detail="Model not loaded") try: # 1. CONSTRUCT INPUT # Combine the 3 fields into one context string for the model parts = [part for part in [request.genre, request.prompt, request.text] if part] full_input = " ".join(parts) # 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 segments sep = tokenizer.sep_token if tokenizer.sep_token else " " full_input = f"{request.genre} {sep} {request.prompt} {sep} {request.text}" print(f"📥 Analyzing: {full_input[:50]}...") print(f"📥 Analyzing: {full_input[:100]}...")
# 2. PREDICT inputs = tokenizer(full_input, return_tensors="pt", truncation=True, max_length=128).to(DEVICE)4 unmodified lines pred_idx = np.argmax(probs) # 3. EXPLAIN (LIME) # Custom splitter for Bangla to keep words intact explainer = LimeTextExplainer( class_names=LABELS, split_expression=lambda x: x.split() ) # Explain the FULL input so we see if Genre/Prompt influenced the decision exp = explainer.explain_instance( full_input, predict_proba_lime, num_features=6, num_samples=40, # Low sample count for faster CPU inference num_samples=40, labels=[pred_idx] ) lime_features = exp.as_list(label=pred_idx) main.py+19-15