| import gradio_client.utils as _cu |
|
|
| |
| _orig_parse = _cu._json_schema_to_python_type |
| def _safe_parse(schema, defs=None): |
| if not isinstance(schema, dict): |
| return "any" |
| return _orig_parse(schema, defs) |
| _cu._json_schema_to_python_type = _safe_parse |
|
|
| import gradio as gr |
| import numpy as np |
| import os |
| from PIL import Image |
|
|
| EMOTIONS = ["Angry", "Disgust", "Fear", "Happy", "Neutral", "Sad", "Surprised"] |
|
|
| model = None |
|
|
| def load_model(): |
| global model |
| try: |
| |
| import tf_keras |
| from tf_keras.models import model_from_json |
|
|
| if not os.path.exists("model.json") or not os.path.exists("best.h5"): |
| print("⚠️ model.json or best.h5 not found.") |
| return |
|
|
| with open("model.json", "r") as f: |
| model_json = f.read() |
|
|
| model = model_from_json(model_json) |
| model.load_weights("best.h5") |
| print("✅ Model loaded successfully.") |
| except Exception as e: |
| print(f"Model not loaded: {e}") |
|
|
| load_model() |
|
|
| def predict(image): |
| if model is None: |
| return "⚠️ Model could not be loaded.", {} |
| if image is None: |
| return "⚠️ Please upload an image first.", {} |
|
|
| image = image.convert("L").resize((48, 48)) |
| arr = np.array(image, dtype=np.float32) / 255.0 |
| arr = arr.reshape(1, 48, 48, 1) |
|
|
| preds = model.predict(arr, verbose=0)[0] |
| scores = {e: round(float(p), 4) for e, p in zip(EMOTIONS, preds)} |
| top = max(scores, key=scores.get) |
| return f"{top} ({scores[top]:.0%} confidence)", scores |
|
|
| demo = gr.Interface( |
| fn=predict, |
| inputs=gr.Image(type="pil", label="📷 Upload face image"), |
| outputs=[ |
| gr.Textbox(label="Prediction"), |
| gr.JSON(label="Confidence scores"), |
| ], |
| title="🙂 Facial Expression Recognition", |
| description="**CNN · 7 emotion classes · TensorFlow/Keras**\n\nUpload a face image to predict the emotion.", |
| flagging_mode="never", |
| ) |
|
|
| demo.launch() |
|
|