import json import torch import os from PIL import Image from fastapi import FastAPI, UploadFile, File from transformers import AutoImageProcessor from dotenv import load_dotenv from langchain_groq import ChatGroq from langchain_core.prompts import ChatPromptTemplate from model import SwinClassifier app = FastAPI(title="Skin Disease Prediction and Medical Awareness API") DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") MODEL_PATH = "best_training_weights.pth" CLASSES_PATH = "classes.json" with open(CLASSES_PATH, "r") as f: classes = json.load(f) if isinstance(classes, dict): class_names = list(classes.values()) else: class_names = classes processor = AutoImageProcessor.from_pretrained( "microsoft/swin-tiny-patch4-window7-224" ) model = SwinClassifier(num_classes=len(class_names)) state_dict = torch.load(MODEL_PATH, map_location=DEVICE) load_dotenv() llm = ChatGroq( model="llama-3.1-8b-instant", temperature=0.4, groq_api_key=os.getenv("GROQ_API_KEY") ) medical_prompt = ChatPromptTemplate.from_template(""" You are a helpful medical awareness assistant. The ML model predicted the following skin disease/class: Disease/Class: {predicted_class} Confidence: {confidence}% Give the response in simple Hindi-English mixed language. Important rules: - Do not claim final diagnosis. - Clearly describe the predicted problem first. - Explain future impact if ignored. - Explain possible solution / next steps. - Give practical advice. - Recommend doctor/dermatologist consultation. - Keep response clear and structured. Response format: 1. Problem Description: Explain what this predicted condition may mean in simple language. 2. Future Impact: Explain what can happen if this condition is ignored or untreated. 3. Solution / Next Steps: Explain what the user should do next. 4. Advice: Give short practical lifestyle / care advice. 5. Disclaimer: Mention that this is AI-based prediction, not a final medical diagnosis. """) # if saved as checkpoint if "model_state_dict" in state_dict: state_dict = state_dict["model_state_dict"] model.load_state_dict(state_dict, strict=False) model.to(DEVICE) model.eval() @app.get("/") def home(): return { "message": "Skin Cancer ViT FastAPI Backend Running", "classes": class_names } @app.post("/predict") async def predict(file: UploadFile = File(...)): image = Image.open(file.file).convert("RGB") inputs = processor(images=image, return_tensors="pt") pixel_values = inputs["pixel_values"].to(DEVICE) with torch.no_grad(): outputs = model(pixel_values) probabilities = torch.softmax(outputs, dim=1)[0] predicted_index = torch.argmax(probabilities).item() predicted_class = class_names[predicted_index] confidence = round(probabilities[predicted_index].item() * 100, 2) chain = medical_prompt | llm llm_response = chain.invoke({ "predicted_class": predicted_class, "confidence": confidence }) try: llm_data = json.loads(llm_response.content) except: llm_data = llm_response.content return { "prediction": { "class": predicted_class, "confidence": confidence, "probabilities": { class_names[i]: round(probabilities[i].item() * 100, 2) for i in range(len(class_names)) } }, "analysis": llm_data }