Spaces:
Sleeping
Sleeping
Download main.py from ChelsY12/Model_batu: direct link, hf CLI and curl.
- Browser
- Download file 3.75 kB
-
https://huggingface.co/spaces/ChelsY12/Model_batu/resolve/main/main.py
- Command line
-
hf download hf://spaces/ChelsY12/Model_batu/main.py
-
curl -L -o main.py https://huggingface.co/spaces/ChelsY12/Model_batu/resolve/main/main.py
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 | |
| def root(): | |
| return { | |
| "message": "Rock Detection API Aktif" | |
| } | |
| 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}") | |
| 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 | |
| ) |