Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
|
@@ -51,40 +163,46 @@ sequence_length = 50
|
|
| 51 |
app = Flask(__name__)
|
| 52 |
CORS(app)
|
| 53 |
|
| 54 |
-
|
| 55 |
@app.route('/')
|
| 56 |
def home():
|
| 57 |
-
return "Welcome to driving behavior analysis"
|
| 58 |
|
| 59 |
-
# Define a route for the prediction function
|
| 60 |
@app.route('/predict', methods=['POST'])
|
| 61 |
def predict_behavior():
|
| 62 |
try:
|
| 63 |
-
# Get
|
| 64 |
data = request.json
|
| 65 |
-
|
| 66 |
-
# Convert the data to a DataFrame
|
| 67 |
df = pd.DataFrame(data)
|
| 68 |
|
| 69 |
# Validate required columns
|
| 70 |
if not all(col in df.columns for col in feature_columns):
|
| 71 |
-
return jsonify({'error': 'Missing columns'}), 400
|
| 72 |
|
| 73 |
# Scale the data
|
| 74 |
df[feature_columns] = scaler.transform(df[feature_columns])
|
| 75 |
|
| 76 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
sequences = []
|
| 78 |
if len(df) >= sequence_length:
|
| 79 |
-
# If enough data for full sequences
|
| 80 |
for i in range(len(df) - sequence_length + 1):
|
| 81 |
seq = df.iloc[i:i+sequence_length][feature_columns].values
|
| 82 |
sequences.append(seq)
|
| 83 |
else:
|
| 84 |
-
# Pad
|
| 85 |
padded_data = np.pad(
|
| 86 |
df[feature_columns].values,
|
| 87 |
-
((sequence_length - len(df), 0), (0, 0)),
|
| 88 |
mode='constant',
|
| 89 |
constant_values=0
|
| 90 |
)
|
|
@@ -93,35 +211,28 @@ def predict_behavior():
|
|
| 93 |
# Convert to NumPy array
|
| 94 |
X_input = np.array(sequences, dtype=np.float32)
|
| 95 |
|
| 96 |
-
#
|
| 97 |
predictions = []
|
| 98 |
for seq in X_input:
|
| 99 |
-
# Prepare the input tensor
|
| 100 |
interpreter.set_tensor(input_details[0]['index'], [seq])
|
| 101 |
interpreter.invoke()
|
| 102 |
-
|
| 103 |
-
# Get the output tensor
|
| 104 |
output_data = interpreter.get_tensor(output_details[0]['index'])
|
| 105 |
predictions.append(output_data)
|
| 106 |
|
| 107 |
# Get predicted classes
|
| 108 |
predicted_classes = np.argmax(predictions, axis=2).flatten()
|
| 109 |
-
|
| 110 |
-
# Convert integers to class labels
|
| 111 |
class_labels = label_encoder.inverse_transform(predicted_classes)
|
| 112 |
|
| 113 |
-
#
|
| 114 |
unique_classes, counts = np.unique(class_labels, return_counts=True)
|
| 115 |
-
|
| 116 |
-
most_frequent_classes = unique_classes[counts == max_count]
|
| 117 |
-
|
| 118 |
-
# Select the first class in case of ties
|
| 119 |
-
most_frequent_class = most_frequent_classes[0] # Select the first class alphabetically
|
| 120 |
|
| 121 |
-
# Return
|
| 122 |
return jsonify({
|
| 123 |
-
"predicted_classes": list(class_labels),
|
| 124 |
-
"most_frequent_class": most_frequent_class
|
|
|
|
|
|
|
| 125 |
})
|
| 126 |
|
| 127 |
except Exception as e:
|
|
|
|
| 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 |
+
|
| 55 |
+
# @app.route('/')
|
| 56 |
+
# def home():
|
| 57 |
+
# return "Welcome to driving behavior analysis"
|
| 58 |
+
|
| 59 |
+
# # Define a route for the prediction function
|
| 60 |
+
# @app.route('/predict', methods=['POST'])
|
| 61 |
+
# def predict_behavior():
|
| 62 |
+
# try:
|
| 63 |
+
# # Get the data from the request
|
| 64 |
+
# data = request.json
|
| 65 |
+
|
| 66 |
+
# # Convert the data to a DataFrame
|
| 67 |
+
# df = pd.DataFrame(data)
|
| 68 |
+
|
| 69 |
+
# # Validate required columns
|
| 70 |
+
# if not all(col in df.columns for col in feature_columns):
|
| 71 |
+
# return jsonify({'error': 'Missing columns'}), 400
|
| 72 |
+
|
| 73 |
+
# # Scale the data
|
| 74 |
+
# df[feature_columns] = scaler.transform(df[feature_columns])
|
| 75 |
+
|
| 76 |
+
# # Create sequences
|
| 77 |
+
# sequences = []
|
| 78 |
+
# if len(df) >= sequence_length:
|
| 79 |
+
# # If enough data for full sequences
|
| 80 |
+
# for i in range(len(df) - sequence_length + 1):
|
| 81 |
+
# seq = df.iloc[i:i+sequence_length][feature_columns].values
|
| 82 |
+
# sequences.append(seq)
|
| 83 |
+
# else:
|
| 84 |
+
# # Pad the data if it's smaller than the sequence length
|
| 85 |
+
# padded_data = np.pad(
|
| 86 |
+
# df[feature_columns].values,
|
| 87 |
+
# ((sequence_length - len(df), 0), (0, 0)), # Pad missing rows
|
| 88 |
+
# mode='constant',
|
| 89 |
+
# constant_values=0
|
| 90 |
+
# )
|
| 91 |
+
# sequences.append(padded_data)
|
| 92 |
+
|
| 93 |
+
# # Convert to NumPy array
|
| 94 |
+
# X_input = np.array(sequences, dtype=np.float32)
|
| 95 |
+
|
| 96 |
+
# # Make predictions using TFLite model
|
| 97 |
+
# predictions = []
|
| 98 |
+
# for seq in X_input:
|
| 99 |
+
# # Prepare the input tensor
|
| 100 |
+
# interpreter.set_tensor(input_details[0]['index'], [seq])
|
| 101 |
+
# interpreter.invoke()
|
| 102 |
+
|
| 103 |
+
# # Get the output tensor
|
| 104 |
+
# output_data = interpreter.get_tensor(output_details[0]['index'])
|
| 105 |
+
# predictions.append(output_data)
|
| 106 |
+
|
| 107 |
+
# # Get predicted classes
|
| 108 |
+
# predicted_classes = np.argmax(predictions, axis=2).flatten()
|
| 109 |
+
|
| 110 |
+
# # Convert integers to class labels
|
| 111 |
+
# class_labels = label_encoder.inverse_transform(predicted_classes)
|
| 112 |
+
|
| 113 |
+
# # Calculate class frequencies
|
| 114 |
+
# unique_classes, counts = np.unique(class_labels, return_counts=True)
|
| 115 |
+
# max_count = np.max(counts)
|
| 116 |
+
# most_frequent_classes = unique_classes[counts == max_count]
|
| 117 |
+
|
| 118 |
+
# # Select the first class in case of ties
|
| 119 |
+
# most_frequent_class = most_frequent_classes[0] # Select the first class alphabetically
|
| 120 |
+
|
| 121 |
+
# # Return the predicted class labels and the most frequent class
|
| 122 |
+
# return jsonify({
|
| 123 |
+
# "predicted_classes": list(class_labels), # Full list of predictions
|
| 124 |
+
# "most_frequent_class": most_frequent_class
|
| 125 |
+
# })
|
| 126 |
+
|
| 127 |
+
# except Exception as e:
|
| 128 |
+
# return jsonify({'error': str(e)}), 500
|
| 129 |
+
|
| 130 |
+
# if __name__ == '__main__':
|
| 131 |
+
# app.run(host="0.0.0.0", port=7860)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
from flask import Flask, request, jsonify
|
| 135 |
from flask_cors import CORS
|
| 136 |
import numpy as np
|
| 137 |
import pandas as pd
|
| 138 |
import joblib
|
|
|
|
|
|
|
| 139 |
import tensorflow as tf # Required for TFLite interpreter
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
# Local file paths
|
| 142 |
tflite_model_path = "motion_classification_model.tflite"
|
| 143 |
scaler_path = "scaler.pkl"
|
| 144 |
label_encoder_path = "label_encoder.pkl"
|
| 145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
# Load the scaler and label encoder
|
| 147 |
scaler = joblib.load(scaler_path)
|
| 148 |
label_encoder = joblib.load(label_encoder_path)
|
|
|
|
| 163 |
app = Flask(__name__)
|
| 164 |
CORS(app)
|
| 165 |
|
|
|
|
| 166 |
@app.route('/')
|
| 167 |
def home():
|
| 168 |
+
return "Welcome to driving behavior analysis API"
|
| 169 |
|
|
|
|
| 170 |
@app.route('/predict', methods=['POST'])
|
| 171 |
def predict_behavior():
|
| 172 |
try:
|
| 173 |
+
# Get data from the request
|
| 174 |
data = request.json
|
|
|
|
|
|
|
| 175 |
df = pd.DataFrame(data)
|
| 176 |
|
| 177 |
# Validate required columns
|
| 178 |
if not all(col in df.columns for col in feature_columns):
|
| 179 |
+
return jsonify({'error': 'Missing required sensor columns'}), 400
|
| 180 |
|
| 181 |
# Scale the data
|
| 182 |
df[feature_columns] = scaler.transform(df[feature_columns])
|
| 183 |
|
| 184 |
+
# Compute Jerk (Rate of Change of Acceleration)
|
| 185 |
+
df['JerkX'] = df['AccX'].diff().fillna(0)
|
| 186 |
+
df['JerkY'] = df['AccY'].diff().fillna(0)
|
| 187 |
+
df['JerkZ'] = df['AccZ'].diff().fillna(0)
|
| 188 |
+
|
| 189 |
+
# Identify Harsh Braking (Sudden drop in AccX)
|
| 190 |
+
harsh_braking_events = (df['JerkX'] < -3).sum() # Adjusted threshold from -5 to -3
|
| 191 |
+
|
| 192 |
+
# Identify Harsh Cornering (Sharp change in GyroZ)
|
| 193 |
+
harsh_cornering_events = (df['GyroZ'].diff().abs() > 1.5).sum() # Adjusted threshold from 30 to 1.5
|
| 194 |
+
|
| 195 |
+
# Create sequences for model input
|
| 196 |
sequences = []
|
| 197 |
if len(df) >= sequence_length:
|
|
|
|
| 198 |
for i in range(len(df) - sequence_length + 1):
|
| 199 |
seq = df.iloc[i:i+sequence_length][feature_columns].values
|
| 200 |
sequences.append(seq)
|
| 201 |
else:
|
| 202 |
+
# Pad if data is smaller than sequence length
|
| 203 |
padded_data = np.pad(
|
| 204 |
df[feature_columns].values,
|
| 205 |
+
((sequence_length - len(df), 0), (0, 0)),
|
| 206 |
mode='constant',
|
| 207 |
constant_values=0
|
| 208 |
)
|
|
|
|
| 211 |
# Convert to NumPy array
|
| 212 |
X_input = np.array(sequences, dtype=np.float32)
|
| 213 |
|
| 214 |
+
# Predict using TFLite model
|
| 215 |
predictions = []
|
| 216 |
for seq in X_input:
|
|
|
|
| 217 |
interpreter.set_tensor(input_details[0]['index'], [seq])
|
| 218 |
interpreter.invoke()
|
|
|
|
|
|
|
| 219 |
output_data = interpreter.get_tensor(output_details[0]['index'])
|
| 220 |
predictions.append(output_data)
|
| 221 |
|
| 222 |
# Get predicted classes
|
| 223 |
predicted_classes = np.argmax(predictions, axis=2).flatten()
|
|
|
|
|
|
|
| 224 |
class_labels = label_encoder.inverse_transform(predicted_classes)
|
| 225 |
|
| 226 |
+
# Find most frequent class
|
| 227 |
unique_classes, counts = np.unique(class_labels, return_counts=True)
|
| 228 |
+
most_frequent_class = unique_classes[np.argmax(counts)]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
+
# Return results
|
| 231 |
return jsonify({
|
| 232 |
+
"predicted_classes": list(class_labels),
|
| 233 |
+
"most_frequent_class": most_frequent_class,
|
| 234 |
+
"harsh_braking_count": int(harsh_braking_events),
|
| 235 |
+
"harsh_cornering_count": int(harsh_cornering_events)
|
| 236 |
})
|
| 237 |
|
| 238 |
except Exception as e:
|