Spaces:
Runtime error
Runtime error
Update app.py (#1)
Browse files- Update app.py (2ef87e7f2d4f3cc07fabc8e6ed293644140e8eeb)
Co-authored-by: Daffa Dians Ramadhan <Xaviant@users.noreply.huggingface.co>
3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051063 unmodified linesfrom PIL import Imageimport ioimport sysimport gradio as grfrom tensorflow.keras.applications.resnet50 import preprocess_input# =========================# 1. FastAPI Init# =========================app = FastAPI(title="Ashoka Buried Penis Classifier API")# =========================# 2. Load Model# =========================print("Loading model...")try:model = tf.keras.models.load_model("cnn_kfold_best_model.h5")print("Model loaded successfully")except Exception as e:print("Failed to load model:", e)sys.exit(1)class_names = ["Normal", "Buried"]# =========================# 3. Preprocessing# =========================def prepare_image(image: Image.Image):image = image.convert("RGB")image = image.resize((224, 224))img_array = np.array(image)img_array = np.expand_dims(img_array, axis=0)img_array = preprocess_input(img_array)return img_array# =========================# 4. Prediction Logic# =========================def predict_image(image):if image is None:return "No image uploaded", 0.0, 0.0processed = prepare_image(image)prediction = model.predict(processed)[0][0]prob_buried = float(prediction * 100)prob_normal = float((1 - prediction) * 100)label = "Buried Penis" if prediction > 0.5 else "Normal"return label, round(prob_normal, 2), round(prob_buried, 2)# =========================# 5. FastAPI Endpoint# =========================@app.post("/predict")async def api_predict(file: UploadFile = File(...)):image_bytes = await file.read()image = Image.open(io.BytesIO(image_bytes))label, normal, buried = predict_image(image)return {"class": label,"probabilities": {"normal": normal,"buried": buried}}# =========================# 6. Gradio UI# =========================with gr.Blocks() as demo:gr.Markdown("""# Ashoka Hipospadia Classifier API - ResNet50**Medical screening tool for Buried Penis**⚠️ This tool is **NOT a diagnostic device**.Results must be interpreted by **qualified medical professionals**.""")with gr.Row():image_input = gr.Image(type="pil",label="Upload / Drag & Drop Medical Image")classify_btn = gr.Button("Analyze Image")result_label = gr.Textbox(label="Prediction Result")prob_normal = gr.Number(label="Normal Probability (%)")prob_buried = gr.Number(label="Buried Probability (%)")classify_btn.click(fn=predict_image,inputs=image_input,outputs=[result_label, prob_normal, prob_buried])# =========================# 7. Mount Gradio to FastAPI# =========================app = gr.mount_gradio_app(app, demo, path="/")3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111123 unmodified linesfrom PIL import Imageimport ioimport sysfrom tensorflow.keras.applications.densenet import preprocess_input# 1. Inisialisasi Aplikasiapp = FastAPI(title="Ashoka Hipospadia Classifier API")# 2. Load Modelprint("Sedang memuat model...")try:model = tf.keras.models.load_model('cnn_kfold_best_model_v2.h5')print("Model berhasil dimuat!")except Exception as e:print(f"Error memuat model: {e}")sys.exit(1) # Matikan server jika model gagal load# Label kelas: 0 = normal, 1 = buriedclass_names = ['normal', 'buried']# 3. Fungsi Preprocessingdef prepare_image(image_bytes):"""Preprocessing gambar untuk model DenseNet- Konversi ke RGB (3 channel)- Resize ke 224x224- Preprocessing DenseNet"""try:img = Image.open(io.BytesIO(image_bytes))# Paksa ubah ke RGB agar PNG transparan tidak errorimg = img.convert("RGB")# Resize ke ukuran input model (224x224 untuk ResNet50)img = img.resize((224, 224))# Convert ke numpy arrayimg_array = np.array(img)# Tambah batch dimensionimg_array = np.expand_dims(img_array, axis=0)# Preprocessing ResNet50 (HARUS sama dengan training!)img_array = preprocess_input(img_array)return img_arrayexcept Exception as e:print(f"Error saat memproses gambar: {e}")return None# 4. Endpoint Prediksi@app.post("/predict")async def predict(file: UploadFile = File(...)):"""Endpoint untuk prediksi gambarInput: File gambar (JPG, PNG, BMP)Output: JSON dengan class dan confidence"""try:# Baca file gambarimage_bytes = await file.read()# Proses gambarprocessed_image = prepare_image(image_bytes)if processed_image is None:raise HTTPException(status_code=400, detail="File bukan gambar yang valid")# Prediksiprediction = model.predict(processed_image)pred_value = float(prediction[0][0])# Hitung probabilitas# Model output: 0 = normal, 1 = buriedprob_normal = (1 - pred_value) * 100prob_buried = pred_value * 100# Tentukan kelas berdasarkan threshold 0.5top_class_idx = 1 if pred_value > 0.5 else 0# Hasil dalam format JSONresult = {"class": class_names[top_class_idx],"confidence": float(max(prob_normal, prob_buried)),"probabilities": {"normal": float(prob_normal),"buried": float(prob_buried)}}return resultexcept Exception as e:# Cetak error ke logprint(f"CRITICAL ERROR: {e}")raise HTTPException(status_code=500, detail=str(e))# 5. Endpoint Home@app.get("/")def home():"""Endpoint root untuk testing API"""return {"message": "Ashoka Hipospadia Classifier API Online! 🚀\n","model": "DenseNet Binary Classification\n","classes": class_names}# API siap digunakan dengan uvicorn# Jalankan dengan: uvicorn app:app --host 0.0.0.0 --port 7860
app.py+97-91