Skip to content

Commit

Permalink
Working on HBR graph updation on sound change PART-1
Browse files Browse the repository at this point in the history
  • Loading branch information
Kumar-laxmi committed Feb 9, 2024
1 parent 418719a commit 67082a5
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 86 deletions.
Binary file modified app/DashApp/__pycache__/hbr_dash.cpython-311.pyc
Binary file not shown.
19 changes: 18 additions & 1 deletion app/DashApp/hbr_dash.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,31 @@
import pandas as pd
import time
import sqlite3
from django.http import JsonResponse, HttpResponse

sound_name = 'normal_heart'
sound_type = 'M'

def graphChange(request):
global sound_name, sound_type
if request.method == 'POST':
if 'normal_heart_sound_mitral_valve' in request.POST:
sound_name, sound_type = 'normal_heart', 'M'
print('Request to print the Normal Heart Sound')
elif 'split_first_heart_sound_mitral_valve' in request.POST:
sound_name, sound_type = 'split_first_heart', 'M'
print('Request to print Split fIRST Heart Sound')
return JsonResponse({'message': 'Success!'})
else:
return HttpResponse("Request method is not a POST")

# Create Dash app
app = DjangoDash('hbrDash')
con = sqlite3.connect("db.sqlite3")
cur = con.cursor()
df = pd.read_sql_query("SELECT * FROM app_heartaudio", con)

audio_path = df.loc[(df['sound_name'] == 'normal_heart') & (df['sound_type'] == 'T'), 'audio_file_path'].values[0]
audio_path = df.loc[(df['sound_name'] == sound_name) & (df['sound_type'] == sound_type), 'audio_file_path'].values[0]
audio = AudioSegment.from_file(audio_path)
audio_data = np.array(audio.get_array_of_samples())
audio_duration = len(audio_data) / audio.frame_rate
Expand Down
Binary file modified app/__pycache__/views.cpython-311.pyc
Binary file not shown.
13 changes: 13 additions & 0 deletions app/templates/elements/Scripts/soundPlay.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,19 @@
console.error('Error in POST request for ' + identifier + '_sound_mitral_valve' + ':', error);
}
});
$.ajax({
type: 'POST',
url: 'graphChange/',
data: {'csrfmiddlewaretoken': '{{ csrf_token }}', [identifier + '_sound_mitral_valve']: true},
success: function (response) {
// Handle success response
console.log('POST request successful for ' + identifier + '_sound_mitral_valve' + ':', response);
},
error: function (error) {
// Handle error response
console.error('Error in POST request for ' + identifier + '_sound_mitral_valve' + ':', error);
}
});
});
});
});
Expand Down
Binary file modified core/__pycache__/urls.cpython-311.pyc
Binary file not shown.
2 changes: 2 additions & 0 deletions core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from django.conf.urls.static import static

from app.views import *
from app.DashApp.hbr_dash import graphChange

urlpatterns = [
path('admin/', admin.site.urls),
Expand All @@ -32,6 +33,7 @@
path('tricuspidVolumeChange/', tricuspidVolumeChange),
path('erbVolumeChange/', erbVolumeChange),
path('django_plotly_dash/', include('django_plotly_dash.urls')),
path('graphChange/', graphChange),
]

if settings.DEBUG:
Expand Down
Binary file modified db.sqlite3
Binary file not shown.
129 changes: 44 additions & 85 deletions test.py
Original file line number Diff line number Diff line change
@@ -1,90 +1,49 @@
import datetime

import dash
from dash import Dash, dcc, html, Input, Output, callback
import plotly

# pip install pyorbital
from pyorbital.orbital import Orbital
satellite = Orbital('TERRA')

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
html.Div([
html.H4('TERRA Satellite Live Feed'),
html.Div(id='live-update-text'),
dcc.Graph(id='live-update-graph'),
dcc.Interval(
id='interval-component',
interval=1*1000, # in milliseconds
n_intervals=0
)
])
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import numpy as np

# Dummy data generation function
def generate_dummy_data(num_points=100):
np.random.seed(42)
x = np.linspace(0, 1, num_points)
y = np.random.rand(num_points)
df = pd.DataFrame({'X': x, 'Y': y})
return df

# Initial dummy data
initial_data = generate_dummy_data()

# Initialize the Dash app
app = dash.Dash(__name__)

# App layout
app.layout = html.Div([
html.H1("Dummy Data Plot"),

# Graph component for plotting
dcc.Graph(id='scatter-plot'),

# Button to refresh the plot
html.Button('Refresh Plot', id='refresh-button', n_clicks=0)
])

# Callback to update the plot on button click
@app.callback(
Output('scatter-plot', 'figure'),
[Input('refresh-button', 'n_clicks')]
)


@callback(Output('live-update-text', 'children'),
Input('interval-component', 'n_intervals'))
def update_metrics(n):
lon, lat, alt = satellite.get_lonlatalt(datetime.datetime.now())
style = {'padding': '5px', 'fontSize': '16px'}
return [
html.Span('Longitude: {0:.2f}'.format(lon), style=style),
html.Span('Latitude: {0:.2f}'.format(lat), style=style),
html.Span('Altitude: {0:0.2f}'.format(alt), style=style)
]


# Multiple components can update everytime interval gets fired.
@callback(Output('live-update-graph', 'figure'),
Input('interval-component', 'n_intervals'))
def update_graph_live(n):
satellite = Orbital('TERRA')
data = {
'time': [],
'Latitude': [],
'Longitude': [],
'Altitude': []
}

# Collect some data
for i in range(180):
time = datetime.datetime.now() - datetime.timedelta(seconds=i*20)
lon, lat, alt = satellite.get_lonlatalt(
time
)
data['Longitude'].append(lon)
data['Latitude'].append(lat)
data['Altitude'].append(alt)
data['time'].append(time)

# Create the graph with subplots
fig = plotly.tools.make_subplots(rows=2, cols=1, vertical_spacing=0.2)
fig['layout']['margin'] = {
'l': 30, 'r': 10, 'b': 30, 't': 10
}
fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'}

fig.append_trace({
'x': data['time'],
'y': data['Altitude'],
'name': 'Altitude',
'mode': 'lines+markers',
'type': 'scatter'
}, 1, 1)
fig.append_trace({
'x': data['Longitude'],
'y': data['Latitude'],
'text': data['time'],
'name': 'Longitude vs Latitude',
'mode': 'lines+markers',
'type': 'scatter'
}, 2, 1)

def update_plot(n_clicks):
# Generate new dummy data on button click
dummy_data = generate_dummy_data()

# Create a scatter plot using Plotly Express
fig = px.scatter(dummy_data, x='X', y='Y', title='Dummy Data Plot')

return fig


# Run the app
if __name__ == '__main__':
app.run(debug=True)
app.run_server(debug=True)

0 comments on commit 67082a5

Please sign in to comment.