Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import joblib
|
| 6 |
+
import requests
|
| 7 |
+
import os
|
| 8 |
+
import tensorflow as tf # Required for TFLite interpreter
|
| 9 |
+
|
| 10 |
+
# URLs for hosted files
|
| 11 |
+
tflite_model_url = "https://drive.google.com/uc?id=1j5JU2xD2iwi5STzjH2gKILAbekiKWBkp&export=download"
|
| 12 |
+
scaler_url = "https://drive.google.com/uc?id=1Qu2ogpNw8MqPbstNpcEbO0oRDQ56qX5X&export=download"
|
| 13 |
+
label_encoder_url = "https://drive.google.com/uc?id=1qYi5agK5vDKc-k6UcaRt7yL9AFJ3O_7-&export=download"
|
| 14 |
+
|
| 15 |
+
# Local file paths
|
| 16 |
+
tflite_model_path = "motion_classification_model.tflite"
|
| 17 |
+
scaler_path = "scaler.pkl"
|
| 18 |
+
label_encoder_path = "label_encoder.pkl"
|
| 19 |
+
|
| 20 |
+
# Function to download files if they don't exist locally
|
| 21 |
+
def download_file(url, local_path):
|
| 22 |
+
if not os.path.exists(local_path):
|
| 23 |
+
print(f"Downloading {local_path} from {url}...")
|
| 24 |
+
response = requests.get(url)
|
| 25 |
+
with open(local_path, 'wb') as file:
|
| 26 |
+
file.write(response.content)
|
| 27 |
+
print(f"Downloaded {local_path}")
|
| 28 |
+
|
| 29 |
+
# Download required files
|
| 30 |
+
download_file(tflite_model_url, tflite_model_path)
|
| 31 |
+
download_file(scaler_url, scaler_path)
|
| 32 |
+
download_file(label_encoder_url, label_encoder_path)
|
| 33 |
+
|
| 34 |
+
# Load the scaler and label encoder
|
| 35 |
+
scaler = joblib.load(scaler_path)
|
| 36 |
+
label_encoder = joblib.load(label_encoder_path)
|
| 37 |
+
|
| 38 |
+
# Initialize the TFLite interpreter
|
| 39 |
+
interpreter = tf.lite.Interpreter(model_path=tflite_model_path)
|
| 40 |
+
interpreter.allocate_tensors()
|
| 41 |
+
|
| 42 |
+
# Get input and output tensor details
|
| 43 |
+
input_details = interpreter.get_input_details()
|
| 44 |
+
output_details = interpreter.get_output_details()
|
| 45 |
+
|
| 46 |
+
# Feature Columns
|
| 47 |
+
feature_columns = ['AccX', 'AccY', 'AccZ', 'GyroX', 'GyroY', 'GyroZ']
|
| 48 |
+
sequence_length = 50
|
| 49 |
+
|
| 50 |
+
# Initialize Flask App
|
| 51 |
+
app = Flask(__name__)
|
| 52 |
+
CORS(app)
|
| 53 |
+
|
| 54 |
+
# Define a route for the prediction function
|
| 55 |
+
@app.route('/predict', methods=['POST'])
|
| 56 |
+
def predict_behavior():
|
| 57 |
+
try:
|
| 58 |
+
# Get the data from the request
|
| 59 |
+
data = request.json
|
| 60 |
+
|
| 61 |
+
# Convert the data to a DataFrame
|
| 62 |
+
df = pd.DataFrame(data)
|
| 63 |
+
|
| 64 |
+
# Validate required columns
|
| 65 |
+
if not all(col in df.columns for col in feature_columns):
|
| 66 |
+
return jsonify({'error': 'Missing columns'}), 400
|
| 67 |
+
|
| 68 |
+
# Scale the data
|
| 69 |
+
df[feature_columns] = scaler.transform(df[feature_columns])
|
| 70 |
+
|
| 71 |
+
# Create sequences
|
| 72 |
+
sequences = []
|
| 73 |
+
if len(df) >= sequence_length:
|
| 74 |
+
# If enough data for full sequences
|
| 75 |
+
for i in range(len(df) - sequence_length + 1):
|
| 76 |
+
seq = df.iloc[i:i+sequence_length][feature_columns].values
|
| 77 |
+
sequences.append(seq)
|
| 78 |
+
else:
|
| 79 |
+
# Pad the data if it's smaller than the sequence length
|
| 80 |
+
padded_data = np.pad(
|
| 81 |
+
df[feature_columns].values,
|
| 82 |
+
((sequence_length - len(df), 0), (0, 0)), # Pad missing rows
|
| 83 |
+
mode='constant',
|
| 84 |
+
constant_values=0
|
| 85 |
+
)
|
| 86 |
+
sequences.append(padded_data)
|
| 87 |
+
|
| 88 |
+
# Convert to NumPy array
|
| 89 |
+
X_input = np.array(sequences, dtype=np.float32)
|
| 90 |
+
|
| 91 |
+
# Make predictions using TFLite model
|
| 92 |
+
predictions = []
|
| 93 |
+
for seq in X_input:
|
| 94 |
+
# Prepare the input tensor
|
| 95 |
+
interpreter.set_tensor(input_details[0]['index'], [seq])
|
| 96 |
+
interpreter.invoke()
|
| 97 |
+
|
| 98 |
+
# Get the output tensor
|
| 99 |
+
output_data = interpreter.get_tensor(output_details[0]['index'])
|
| 100 |
+
predictions.append(output_data)
|
| 101 |
+
|
| 102 |
+
# Get predicted classes
|
| 103 |
+
predicted_classes = np.argmax(predictions, axis=2).flatten()
|
| 104 |
+
|
| 105 |
+
# Convert integers to class labels
|
| 106 |
+
class_labels = label_encoder.inverse_transform(predicted_classes)
|
| 107 |
+
|
| 108 |
+
# Calculate class frequencies
|
| 109 |
+
unique_classes, counts = np.unique(class_labels, return_counts=True)
|
| 110 |
+
max_count = np.max(counts)
|
| 111 |
+
most_frequent_classes = unique_classes[counts == max_count]
|
| 112 |
+
|
| 113 |
+
# Select the first class in case of ties
|
| 114 |
+
most_frequent_class = most_frequent_classes[0] # Select the first class alphabetically
|
| 115 |
+
|
| 116 |
+
# Return the predicted class labels and the most frequent class
|
| 117 |
+
return jsonify({
|
| 118 |
+
"predicted_classes": list(class_labels), # Full list of predictions
|
| 119 |
+
"most_frequent_class": most_frequent_class
|
| 120 |
+
})
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return jsonify({'error': str(e)}), 500
|
| 124 |
+
|
| 125 |
+
if __name__ == '__main__':
|
| 126 |
+
app.run(host="0.0.0.0", port=7860)
|