Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,11 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import numpy as np
|
| 4 |
import tensorflow as tf
|
| 5 |
from fastapi import FastAPI
|
| 6 |
from pydantic import BaseModel
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
|
| 9 |
-
# Optimasi RAM server HF
|
| 10 |
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 11 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 12 |
|
|
@@ -19,80 +18,43 @@ app.add_middleware(
|
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
| 22 |
-
clf_model = None
|
| 23 |
-
|
| 24 |
-
# Schema request dari Space A
|
| 25 |
class ItemRequest(BaseModel):
|
| 26 |
items_text: str
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
# =========================================================
|
| 31 |
-
def build_manual_clf_model():
|
| 32 |
-
inputs = tf.keras.Input(shape=(1,), dtype=tf.string, name='input_layer')
|
| 33 |
-
|
| 34 |
-
x = tf.keras.layers.TextVectorization(
|
| 35 |
-
max_tokens=5000,
|
| 36 |
-
output_sequence_length=50,
|
| 37 |
-
name='text_vectorization'
|
| 38 |
-
)(inputs)
|
| 39 |
-
|
| 40 |
-
x = tf.keras.layers.Embedding(input_dim=5000, output_dim=64, name='embedding')(x)
|
| 41 |
-
x = tf.keras.layers.GlobalAveragePooling1D(name='global_average_pooling1d')(x)
|
| 42 |
-
x = tf.keras.layers.Dense(64, activation='relu', name='dense')(x)
|
| 43 |
-
x = tf.keras.layers.Dropout(0.2, name='dropout')(x)
|
| 44 |
-
|
| 45 |
-
outputs = tf.keras.layers.Dense(7, activation='softmax', name='dense_1')(x)
|
| 46 |
-
|
| 47 |
-
return tf.keras.Model(inputs=inputs, outputs=outputs, name='functional')
|
| 48 |
|
| 49 |
-
def
|
| 50 |
-
global
|
| 51 |
-
if
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
clf_model.load_weights("model_strukly.keras")
|
| 57 |
-
|
| 58 |
-
# 3. Suntikkan kamus TextVectorization langsung dari dalam file .keras
|
| 59 |
-
print("Mengekstrak kamus TextVectorization...")
|
| 60 |
-
tv_layer = clf_model.get_layer('text_vectorization')
|
| 61 |
-
try:
|
| 62 |
-
with zipfile.ZipFile("model_strukly.keras", 'r') as z:
|
| 63 |
-
# Cari file txt di folder assets
|
| 64 |
-
vocab_files = [n for n in z.namelist() if 'assets/' in n and n.endswith('.txt')]
|
| 65 |
-
if vocab_files:
|
| 66 |
-
with z.open(vocab_files[0]) as f:
|
| 67 |
-
vocab_list = f.read().decode('utf-8').splitlines()
|
| 68 |
-
tv_layer.set_vocabulary(vocab_list)
|
| 69 |
-
print(f"Kamus berhasil disuntikkan dari: {vocab_files[0]}")
|
| 70 |
-
except Exception as e:
|
| 71 |
-
print(f"Gagal menyuntikkan kamus: {e}")
|
| 72 |
-
|
| 73 |
-
return clf_model
|
| 74 |
|
| 75 |
@app.post("/classify/")
|
| 76 |
def classify_items(request: ItemRequest):
|
| 77 |
try:
|
| 78 |
raw_items = request.items_text
|
| 79 |
|
| 80 |
-
# Jika Space A mengirim string kosong
|
| 81 |
if not raw_items.strip():
|
| 82 |
-
return {"success": True, "
|
| 83 |
|
| 84 |
-
|
| 85 |
-
input_data = np.array([raw_items])
|
| 86 |
|
| 87 |
-
|
| 88 |
-
hasil_prediksi =
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
|
| 93 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
except Exception as e:
|
| 96 |
import traceback
|
| 97 |
-
print(f"Error AI Klasifikasi
|
| 98 |
-
return {"success": False, "error": str(e), "
|
|
|
|
| 1 |
import os
|
| 2 |
+
import pickle
|
| 3 |
import numpy as np
|
| 4 |
import tensorflow as tf
|
| 5 |
from fastapi import FastAPI
|
| 6 |
from pydantic import BaseModel
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
|
|
|
|
| 9 |
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 10 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 11 |
|
|
|
|
| 18 |
allow_headers=["*"],
|
| 19 |
)
|
| 20 |
|
|
|
|
|
|
|
|
|
|
| 21 |
class ItemRequest(BaseModel):
|
| 22 |
items_text: str
|
| 23 |
|
| 24 |
+
model = None
|
| 25 |
+
encoder = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
def get_model():
|
| 28 |
+
global model, encoder
|
| 29 |
+
if model is None:
|
| 30 |
+
model = tf.keras.models.load_model('model_strukly.keras')
|
| 31 |
+
with open('penerjemah_kategori.pkl', 'rb') as file:
|
| 32 |
+
encoder = pickle.load(file)
|
| 33 |
+
return model, encoder
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
@app.post("/classify/")
|
| 36 |
def classify_items(request: ItemRequest):
|
| 37 |
try:
|
| 38 |
raw_items = request.items_text
|
| 39 |
|
|
|
|
| 40 |
if not raw_items.strip():
|
| 41 |
+
return {"success": True, "category_id": None, "category_name": "Tidak Terdeteksi"}
|
| 42 |
|
| 43 |
+
m, e = get_model()
|
|
|
|
| 44 |
|
| 45 |
+
input_data = tf.constant([raw_items], dtype=tf.string)
|
| 46 |
+
hasil_prediksi = m.predict(input_data, verbose=0)
|
| 47 |
|
| 48 |
+
category_id = int(np.argmax(hasil_prediksi[0]))
|
| 49 |
+
category_name = e.inverse_transform([category_id])[0]
|
| 50 |
|
| 51 |
+
return {
|
| 52 |
+
"success": True,
|
| 53 |
+
"class_id": category_id,
|
| 54 |
+
"class_name": category_name
|
| 55 |
+
}
|
| 56 |
|
| 57 |
except Exception as e:
|
| 58 |
import traceback
|
| 59 |
+
print(f"Error AI Klasifikasi: {traceback.format_exc()}")
|
| 60 |
+
return {"success": False, "error": str(e), "category_id": None, "category_name": None}
|