Model_batu / main.py
ChelsY12's picture
Upload 4 files
7bab9e5 verified
Raw History Blame Contribute Delete
3.75 kB
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import numpy as np
from PIL import Image
import io
import os
try:
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
TF_AVAILABLE = True
print("TensorFlow berhasil diimport")
print("TensorFlow Version:", tf.__version__)
except Exception as e:
TF_AVAILABLE = False
print("TensorFlow Import Error:", e)
app = FastAPI(
title="Rock Detection API",
version="1.0"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # sementara untuk testing
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
MODEL_PATH = "model_cnn.h5"
# 7 CLASS SESUAI MODEL CNN
CLASS_NAMES = [
"Quartzite",
"Marble",
"Coal",
"Sandstone",
"Limestone",
"Basalt",
"Granite"
]
# KATEGORI BATU
ROCK_INFO = {
"Quartzite": "Metamorphic",
"Marble": "Metamorphic",
"Coal": "Sedimentary",
"Sandstone": "Sedimentary",
"Limestone": "Sedimentary",
"Basalt": "Igneous",
"Granite": "Igneous"
}
TARGET_SIZE = (224, 224)
model = None
@app.get("/")
def root():
return {
"message": "Rock Detection API Aktif"
}
@app.on_event("startup")
async def load_ml_model():
global model
if not TF_AVAILABLE:
print("WARNING: TensorFlow tidak tersedia")
return
if not os.path.exists(MODEL_PATH):
print(f"ERROR: File {MODEL_PATH} tidak ditemukan")
return
try:
model = load_model(MODEL_PATH)
print(f"\nModel {MODEL_PATH} berhasil dimuat!")
print("Input Shape :", model.input_shape)
print("Output Shape:", model.output_shape)
model.summary()
except Exception as e:
print("ERROR LOAD MODEL:", e)
def preprocess_image(image_bytes: bytes):
try:
img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
img = img.resize(TARGET_SIZE)
img_array = img_to_array(img)
img_array = img_array / 255.0
img_array = np.expand_dims(img_array, axis=0)
return img_array
except Exception as e:
raise ValueError(f"Error preprocessing image: {e}")
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
if not file.content_type.startswith("image/"):
raise HTTPException(
status_code=400,
detail="File harus berupa gambar"
)
if model is None:
raise HTTPException(
status_code=500,
detail="Model CNN belum dimuat"
)
try:
contents = await file.read()
processed_image = preprocess_image(contents)
print("\nProcessed Image Shape:")
print(processed_image.shape)
predictions = model.predict(processed_image)
print("\nPredictions:")
print(predictions)
print("\nPrediction Shape:")
print(predictions.shape)
class_idx = np.argmax(predictions[0])
confidence = float(predictions[0][class_idx])
predicted_class = CLASS_NAMES[class_idx]
rock_category = ROCK_INFO[predicted_class]
return {
"rock_type": predicted_class,
"rock_category": rock_category,
"confidence": round(confidence, 4),
"message": "Prediksi berhasil"
}
except Exception as e:
print("PREDICT ERROR:", e)
raise HTTPException(
status_code=500,
detail=str(e)
)
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="0.0.0.0",
port=7860,
reload=True
)