liesdillen's picture
Rename interface.py to app.py
04c1b88 verified
raw
history blame
3.91 kB
import numpy as np
import pandas as pd
import gradio as gr
import plotly.graph_objs as go
from plotly.subplots import make_subplots
import datetime
# Function to load data from a text file into a numpy array of the right format
def load_data(filename):
with open(filename, 'r') as file:
data = [int(line.strip()) for line in file]
data = np.array(data, dtype=int)
data[data == -100] = -1
return data.reshape((-1, 1))
def process_csv(file):
if file is None:
gr.Warning("No file uploaded")
# Load the data
acc_data = np.load(file)
predicted_labels = load_data('003_1_R.txt')
# Append the new columns
complete_array = np.hstack((acc_data, predicted_labels))
# Define the time axis
duration = 33.333333 # milliseconds
num_samples = complete_array.shape[0]
time_axis = np.arange(0, num_samples * duration, duration)
# Convert time axis to datetime objects
start_time = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
time_axis_datetime = [start_time + datetime.timedelta(milliseconds=int(t)) for t in time_axis]
# Convert datetime objects to formatted strings
time_axis_labels = [t.strftime('%H:%M:%S.%f')[:-3] for t in time_axis_datetime]
# Calculate the total number of predicted functional and non-functional activity
total_predicted_functional = np.sum(complete_array[:, 3] != 0)
total_predicted_non_functional = np.sum(complete_array[:, 3] == 0)
# Calculate percentages
predicted_functional_percentage = (total_predicted_functional / len(complete_array)) * 100
predicted_non_functional_percentage = (total_predicted_non_functional / len(complete_array)) * 100
# Formulate return string
return_string = f"Percentage of predicted functional activity: {predicted_functional_percentage:.2f}%\nPercentage of predicted non-functional activity: {predicted_non_functional_percentage:.2f}%"
# Create subplots
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.6, 0.4], specs=[[{"type": "scatter"}], [{"type": "scatter"}]])
# Add traces to the subplots
fig.add_trace(go.Scatter(x=time_axis_labels, y=complete_array[:, 0], mode='lines', name='Acc X', line=dict(width=0.75)), row=1, col=1)
fig.add_trace(go.Scatter(x=time_axis_labels, y=complete_array[:, 1], mode='lines', name='Acc Y', line=dict(width=0.75)), row=1, col=1)
fig.add_trace(go.Scatter(x=time_axis_labels, y=complete_array[:, 2], mode='lines', name='Acc Z', line=dict(width=0.75)), row=1, col=1)
fig.add_trace(go.Scatter(x=time_axis_labels, y=complete_array[:, 3], mode='lines', name='Predicted labels', line=dict(width=1)), row=2, col=1)
# Update layout
fig.update_layout(
title='Accelerometer Data with Annotated Labels',
xaxis=dict(title='Time (milliseconds)'),
yaxis=dict(title='Accelerometer Data'),
yaxis2=dict(title='Predicted'),
showlegend=True,
height=600
)
return return_string, fig
with gr.Blocks(theme=gr.themes.Base()) as demo:
gr.Markdown(
"""
# Functional Upper Limb Activity Recognition Model
Upload your csv file containing accelerometer data to obtain a prediction on the amount of functional activity of the upper limbs.
""")
with gr.Row(equal_height=True):
with gr.Column():
input_file = gr.File(label="Upload CSV file")
with gr.Row():
submit_btn = gr.Button("Submit", variant='primary')
clear_btn = gr.ClearButton(input_file, variant='secondary')
output_text = gr.Textbox(label="Prediction statistics")
output_plot = gr.Plot(label="CSV Plot")
submit_btn.click(fn=process_csv, inputs=input_file, outputs=[output_text, output_plot])
clear_btn.click(fn=lambda: input_file.reinit())
demo.launch()