Spaces:
Sleeping
Sleeping
Download app.py from khvlil69/anomaly-detection-api: direct link, hf CLI and curl.
- Browser
- Download file 2.43 kB
-
https://huggingface.co/spaces/khvlil69/anomaly-detection-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/khvlil69/anomaly-detection-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/khvlil69/anomaly-detection-api/resolve/main/app.py
2.43 kB
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| import cv2 | |
| import numpy as np | |
| import os | |
| os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Set to '3' to suppress all warnings | |
| import tensorflow as tf | |
| app = Flask(__name__) | |
| CORS(app) # Enable CORS for all routes | |
| # Build the same architecture as in anomaly_detection.md to avoid HDF5 load_model bug | |
| # (Sequential + Functional submodel causes Flatten to receive a list in legacy .h5 load) | |
| base_model = tf.keras.applications.EfficientNetV2B1( | |
| input_shape=(224, 224, 3), include_top=False, weights='imagenet' | |
| ) | |
| base_model.trainable = False | |
| model = tf.keras.Sequential([ | |
| base_model, | |
| tf.keras.layers.Flatten(), | |
| tf.keras.layers.Dropout(0.5), | |
| tf.keras.layers.Dense(2, activation='softmax'), | |
| ]) | |
| model.load_weights('anomaly-detection-model.h5') | |
| # Match training: def_front=0 (Anomaly), ok_front=1 (Normal) | |
| class_names = ['Anomaly', 'Normal'] | |
| def predict(): | |
| try: | |
| if 'image' not in request.files: | |
| return jsonify({'error': 'No image in request. Use form field "image".'}), 400 | |
| image_file = request.files['image'] | |
| if image_file.filename == '' or not image_file.filename: | |
| return jsonify({'error': 'No file selected.'}), 400 | |
| buf = image_file.read() | |
| if not buf: | |
| return jsonify({'error': 'Empty file.'}), 400 | |
| img = cv2.imdecode(np.frombuffer(buf, np.uint8), cv2.IMREAD_COLOR) | |
| if img is None: | |
| return jsonify({'error': 'Invalid image. Use JPEG, PNG or WebP.'}), 400 | |
| img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Model was trained with RGB | |
| img = cv2.resize(img, (224, 224)) | |
| img = np.expand_dims(img, axis=0) | |
| predictions = model.predict(img, verbose=0) | |
| predicted_class_index = int(np.argmax(predictions[0])) | |
| predicted_confidence = float(predictions[0][predicted_class_index]) | |
| if predicted_confidence >= 0.85: | |
| predicted_class = class_names[predicted_class_index] | |
| return jsonify({ | |
| 'predicted_class': predicted_class, | |
| 'confidence': round(predicted_confidence, 4), | |
| }) | |
| else: | |
| return jsonify({'message': 'Prediction is not clear.'}) | |
| except Exception as e: | |
| return jsonify({'error': str(e)}), 500 | |
| if __name__ == '__main__': | |
| app.run(debug=True, port=4000) | |