|
import tensorflow as tf
|
|
|
|
from huggingface_hub import hf_hub_download
|
|
from PIL import Image, ImageOps
|
|
import numpy as np
|
|
import os
|
|
|
|
def load_model_from_hf(model_id, model_filename="model.keras"):
|
|
"""
|
|
Hugging Face Hub์์ Keras ๋ชจ๋ธ ํ์ผ์ ๋ค์ด๋ก๋ํ ํ,
|
|
๋ก์ปฌ์ ์ ์ฅ๋ ํ์ผ์ ์ด์ฉํด ๋ชจ๋ธ์ ๋ถ๋ฌ์ต๋๋ค.
|
|
"""
|
|
try:
|
|
print(f"Downloading model '{model_id}' from Hugging Face Hub...")
|
|
|
|
|
|
model_path = hf_hub_download(repo_id=model_id, filename=model_filename)
|
|
print(f"Model downloaded to: {model_path}")
|
|
|
|
|
|
print("Loading model from local file...")
|
|
model = tf.keras.models.load_model(model_path)
|
|
print("Model loaded successfully!")
|
|
return model
|
|
|
|
except Exception as e:
|
|
print(f"Error loading model: {e}")
|
|
print("Please check if the model ID and filename are correct on Hugging Face Hub.")
|
|
return None
|
|
|
|
def preprocess_image(image_path):
|
|
"""
|
|
์ฌ์ฉ์ ์ด๋ฏธ์ง๋ฅผ MNIST ๋ฐ์ดํฐ์
ํ์์ ๋ง๊ฒ ์ ์ฒ๋ฆฌํฉ๋๋ค.
|
|
"""
|
|
try:
|
|
|
|
img = Image.open(image_path)
|
|
|
|
|
|
img = img.convert('L')
|
|
|
|
|
|
if np.mean(np.array(img)) > 128:
|
|
img = ImageOps.invert(img)
|
|
|
|
|
|
img = img.resize((28, 28), Image.Resampling.LANCZOS)
|
|
|
|
|
|
img_array = np.array(img).astype('float32') / 255.0
|
|
|
|
|
|
processed_img = np.expand_dims(img_array, axis=0)
|
|
processed_img = np.expand_dims(processed_img, axis=-1)
|
|
|
|
return processed_img
|
|
except FileNotFoundError:
|
|
print(f"Error: The file '{image_path}' was not found.")
|
|
return None
|
|
except Exception as e:
|
|
print(f"Error processing image: {e}")
|
|
return None
|
|
|
|
def main():
|
|
|
|
model_id = "OneclickAI/CNN_test_Model"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model = load_model_from_hf(model_id, model_filename="my_keras_model.keras")
|
|
|
|
if model is None:
|
|
return
|
|
|
|
|
|
while True:
|
|
user_input = input("\nPlease enter the path to your image (or type 'exit' to quit): ")
|
|
|
|
if user_input.lower() == 'exit':
|
|
break
|
|
|
|
if not os.path.exists(user_input):
|
|
print(f"File not found at '{user_input}'. Please check the path and try again.")
|
|
continue
|
|
|
|
|
|
processed_image = preprocess_image(user_input)
|
|
|
|
if processed_image is not None:
|
|
|
|
predictions = model.predict(processed_image)
|
|
|
|
|
|
predicted_digit = np.argmax(predictions[0])
|
|
confidence = np.max(predictions[0]) * 100
|
|
|
|
print("\n--- Prediction Result ---")
|
|
print(f"Predicted Digit: {predicted_digit}")
|
|
print(f"Confidence: {confidence:.2f}%")
|
|
print("-------------------------")
|
|
|
|
if __name__ == "__main__":
|
|
main() |