| | from fastapi import FastAPI, File, UploadFile |
| | from fastapi.responses import JSONResponse |
| | from PIL import Image |
| | import tensorflow as tf |
| | import numpy as np |
| | import requests |
| | import io |
| | import os |
| |
|
| | app = FastAPI() |
| |
|
| | MODEL_URL = "https://huggingface.co/faturbbx/htr/resolve/main/htr_crnn_final_model.keras" |
| | MODEL_PATH = "htr_crnn_final_model.keras" |
| |
|
| | def download_model(): |
| | if not os.path.exists(MODEL_PATH): |
| | print("📥 Downloading model...") |
| | r = requests.get(MODEL_URL) |
| | with open(MODEL_PATH, "wb") as f: |
| | f.write(r.content) |
| | print("✅ Model downloaded.") |
| |
|
| | download_model() |
| | model = tf.keras.models.load_model(MODEL_PATH) |
| |
|
| | def preprocess(img): |
| | img = img.convert('L').resize((256, 64)) |
| | img = np.array(img) / 255.0 |
| | img = np.transpose(img, (1, 0)) |
| | img = np.expand_dims(img, axis=(0, -1)) |
| | return img |
| |
|
| | def decode_prediction(pred): |
| | |
| | return "prediksi-hasil" |
| |
|
| | @app.post("/predict") |
| | async def predict(image: UploadFile = File(...)): |
| | contents = await image.read() |
| | img = Image.open(io.BytesIO(contents)) |
| | processed = preprocess(img) |
| | pred = model.predict(processed) |
| | result = decode_prediction(pred) |
| | return JSONResponse({"result": result}) |
| | |