Spaces:
Sleeping
Sleeping
File size: 3,002 Bytes
d45cd98 780562d 13a34a0 780562d 13a34a0 4d15e01 13a34a0 780562d d45cd98 780562d d45cd98 780562d d45cd98 780562d d45cd98 c6d3dc0 d45cd98 13a34a0 d45cd98 780562d c23447b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | import re
import base64
from PIL import Image
from io import BytesIO
import numpy as np
from fastapi import FastAPI
from pydantic import BaseModel
from keras.models import load_model
from keras.utils import img_to_array
from tensorflow.keras.utils import load_img, img_to_array
import uvicorn
from keras.layers import BatchNormalization
# Memuat model Keras dengan menangani objek kustom
try:
model = load_model('modelMobileNetNew.h5', custom_objects={'BatchNormalization': BatchNormalization})
except Exception as e:
print(f"Error loading model: {e}")
app = FastAPI()
class ImageData(BaseModel):
message: str
def base64_to_pil(img_base64):
image_data = re.sub('data:image/.+;base64,', '', str(img_base64))
pil_image = Image.open(BytesIO(base64.b64decode(image_data)))
return pil_image
def model_predict(img, model):
img = img.resize((224, 224))
x = img_to_array(img)
x = x.reshape(-1, 224, 224, 3)
x = x.astype('float32')
x = x / 255.0
preds = model.predict(x)
return preds
target_names = ['australopithecus_aferensis',
'badak_bercula_satu',
'batu_lempung_krisikan',
'fauna_darat_semedo',
'fragmen_tengkorak',
'fragmen_tengkorak_parential',
'fragmen_tengkorak_sambung_macan',
'fragmen_tulang_fermur_bawah',
'gigi_buaya',
'gigi_gajah',
'gigi_hiu',
'homo_erectus_ngawi',
'homo_habilis',
'homo_sapiens_wajak',
'kapak_penetak',
'kapak_primbas']
display_names = ['Australopithecus Aferensis',
'Badak Bercula Satu',
'Batu Lempung Krisikan',
'Fauna Darat Semedo',
'Fragmen Tengkorak',
'Fragmen Tengkorak Parential',
'Fragmen Tengkorak Sambung_macan',
'Fragmen Tulang Fermur Bawah',
'Gigi Buaya',
'Gigi Gajah',
'Gigi Hiu',
'Homo Erectus Ngawi',
'Homo Habilis',
'Homo Sapiens Wajak',
'Kapak Penetak',
'Kapak Primbas']
label_mapping = dict(zip(target_names, display_names))
@app.get("/hello")
async def say_hello():
return "hello"
@app.post("/predict")
async def predict(image_data: ImageData):
try:
data = image_data.message
img = base64_to_pil(data)
pred = model_predict(img, model)
hasil_label = label_mapping[target_names[np.argmax(pred)]]
hasil_prob = "{:.2f}".format(100 * np.max(pred))
return {'message': 'Berhasil melakukan prediksi', 'nama': hasil_label, 'probability': hasil_prob}
except Exception as e:
print(f"EXCEPTION in Predict POST: {e}")
return {'message': str(e), 'nama': '', 'probability': ''}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)
|