Spaces:
Sleeping
Sleeping
| # -*- coding: utf-8 -*- | |
| """app.py | |
| Automatically generated by Colab. | |
| Original file is located at | |
| https://colab.research.google.com/drive/1J1hXUB5eoxFBDoclJh3sO2ehEIFKr3Pw | |
| """ | |
| import gradio as gr | |
| import tensorflow as tf | |
| import numpy as np | |
| from PIL import Image | |
| # ขนาดภาพที่ใช้ในโมเดล | |
| IMG_SIZE = (224, 224) | |
| # สร้าง Dictionary ที่เก็บชื่อโมเดลและ path ไฟล์ .h5 | |
| model_paths = { | |
| "Custom CNN": "Custom_CNN_model.h5", | |
| "VGG16": "VGG16_model.h5", | |
| "ResNet50": "ResNet50_model.h5" | |
| } | |
| # ฟังก์ชันเตรียมข้อมูลภาพ (และคืนภาพที่ resize แล้ว) | |
| def resize_image(image): | |
| image = image.resize(IMG_SIZE) # Resize เป็น 224x224 | |
| return image # คืนภาพเพื่อแสดงต่อ (ช่องเดียวกัน) | |
| # ฟังก์ชันทำนาย โดยใช้ภาพที่ resize แล้ว | |
| def predict_with_model(resized_image, model_name): | |
| # เตรียมภาพ | |
| image_array = np.array(resized_image) / 255.0 # Normalize | |
| image_array = np.expand_dims(image_array, axis=0) # เพิ่ม batch dimension | |
| # โหลดโมเดลที่เลือก | |
| model = tf.keras.models.load_model(model_paths[model_name]) | |
| # ทำนายผล | |
| prediction = model.predict(image_array)[0][0] # ได้ค่าความน่าจะเป็น | |
| class_name = "Stroke" if prediction > 0.5 else "Non-Stroke" | |
| confidence = round(float(prediction if prediction > 0.5 else 1 - prediction) * 100, 2) | |
| # คืนผลลัพธ์ | |
| result_text = f"\n\n🧠 Prediction Result\n---------------------------\nClass: {class_name}\nConfidence: {confidence}%" | |
| return result_text | |
| # สร้าง Gradio Interface แบบไม่มีช่องแยก | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 🧠 Stroke Face Classification App") | |
| gr.Markdown("Upload a face image. The image will be automatically resized to 224x224 and shown here. Then, select a model to classify.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| image_input = gr.Image(type="pil", label="🖼️ Upload & Auto Resize Face Image (224x224)") | |
| model_selector = gr.Dropdown(choices=["Custom CNN", "VGG16", "ResNet50"], label="📊 Select Model to Classify") | |
| predict_button = gr.Button("🚀 Predict Stroke") | |
| with gr.Column(): | |
| output_text = gr.Textbox(label="📝 Prediction Output", lines=5) | |
| # เมื่ออัปโหลดรูปแล้ว resize และแสดงแทนที่เดิมทันที | |
| image_input.upload(resize_image, inputs=image_input, outputs=image_input) | |
| # เมื่อกดปุ่ม Predict ใช้ภาพที่ resize แล้วไปทำนาย | |
| predict_button.click( | |
| predict_with_model, | |
| inputs=[image_input, model_selector], | |
| outputs=output_text | |
| ) | |
| # Run app | |
| if __name__ == "__main__": | |
| demo.launch() |