HanifAlgamar commited on
Commit
985c159
·
1 Parent(s): 3c2366b

Initial deploy of FastAPI app with TensorFlow model

Browse files
Files changed (4) hide show
  1. Dockerfile +17 -0
  2. main.py +83 -0
  3. models/model.h5 +3 -0
  4. requirements.txt +4 -0
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gunakan base image Python yang sesuai. TensorFlow sering membutuhkan versi Python tertentu.
2
+ FROM python:3.9-slim-buster
3
+
4
+ # Set direktori kerja di dalam container
5
+ WORKDIR /app
6
+
7
+ # Salin file requirements.txt dan install dependensi
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ # Salin seluruh isi proyek Anda ke dalam container
12
+ # Ini akan menyalin main.py dan folder models/ beserta isinya
13
+ COPY . .
14
+
15
+ # Komando untuk menjalankan aplikasi Uvicorn Anda
16
+ # Penting: Hugging Face Spaces menggunakan port 7860 secara default
17
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
main.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ from typing import List
4
+ from io import BytesIO
5
+ from PIL import Image
6
+ import numpy as np
7
+ import tensorflow as tf
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+
10
+ # Inisialisasi aplikasi FastAPI
11
+ app = FastAPI()
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["https://trash-scan-fe.vercel.app/"], # Gantilah dengan URL frontend Anda
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ # Muat model yang sudah dilatih sebelumnya
21
+ MODEL_PATH = "models/model.h5" # Ganti dengan path model Anda
22
+ try:
23
+ model = tf.keras.models.load_model(MODEL_PATH)
24
+ except Exception as e:
25
+ raise RuntimeError(f"Gagal memuat model: {e}")
26
+
27
+ # Label kelas (sesuaikan dengan model Anda)
28
+ CLASS_NAMES = ["battery", "biological", "clothes", "metal", "plastic"] # Ganti dengan label model Anda
29
+
30
+
31
+ def read_imagefile(file: bytes) -> Image.Image:
32
+ """Membaca file gambar dari bytes"""
33
+ try:
34
+ image = Image.open(BytesIO(file)).convert("RGB")
35
+ return image
36
+ except Exception as e:
37
+ raise HTTPException(status_code=400, detail=f"Gagal membaca file gambar: {e}")
38
+
39
+
40
+ def preprocess_image(image: Image.Image, target_size: tuple) -> np.ndarray:
41
+ """Preproses gambar sesuai dengan kebutuhan model"""
42
+ image = image.resize(target_size)
43
+ image_array = np.array(image) / 255.0 # Normalisasi
44
+ image_array = np.expand_dims(image_array, axis=0) # Tambahkan batch dimension
45
+ return image_array
46
+
47
+
48
+ @app.post("/predict")
49
+ async def predict_image(file: UploadFile = File(...)):
50
+ """Endpoint untuk prediksi gambar"""
51
+ # Tambahkan log awal untuk debugging
52
+ print(f"File diterima: {file.filename}, Content-Type: {file.content_type}")
53
+
54
+ # Validasi tipe file
55
+ if not file.content_type.startswith("image"):
56
+ raise HTTPException(status_code=400, detail="File yang diunggah bukan gambar")
57
+
58
+ # Baca dan preproses gambar
59
+ try:
60
+ image = read_imagefile(await file.read())
61
+ image_array = preprocess_image(image, target_size=(224, 224)) # Sesuaikan ukuran dengan model Anda
62
+ except Exception as e:
63
+ raise HTTPException(status_code=500, detail=f"Gagal memproses gambar: {e}")
64
+
65
+ # Lakukan prediksi menggunakan model
66
+ try:
67
+ predictions = model.predict(image_array)
68
+ predicted_class = CLASS_NAMES[np.argmax(predictions)]
69
+ confidence = float(np.max(predictions))
70
+ except Exception as e:
71
+ raise HTTPException(status_code=500, detail=f"Gagal melakukan prediksi: {e}")
72
+
73
+ # Kembalikan hasil prediksi
74
+ return JSONResponse(content={
75
+ "predicted_class": predicted_class,
76
+ "confidence": confidence,
77
+ "filename": file.filename # Tambahkan informasi nama file untuk debugging
78
+ })
79
+
80
+
81
+ # Jalankan server
82
+ # .venv\Scripts\activate # Aktifkan virtual environment
83
+ # Gunakan `uvicorn main:app --reload` untuk menjalankan API
models/model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:340f4cd407a37259fb0cf21b66a8fc51744287de6193da76ccc058904c3c5d55
3
+ size 9475672
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ tensorflow
4
+ Pillow