Skip to content

Commit 8e0c85b

Browse files
authored
backend
1 parent 1158489 commit 8e0c85b

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed

flask_app.py

+111
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
2+
# A very simple Flask Hello World app for you to get started with...
3+
4+
from flask import Flask,request,render_template
5+
import json
6+
import heartpy as hp
7+
import matplotlib.pyplot as plt
8+
import hrvanalysis as hrv
9+
import io
10+
import base64
11+
import datetime
12+
import numpy as np
13+
import scipy
14+
import sys,os
15+
import csv
16+
import time
17+
18+
app = Flask(__name__)
19+
def plt_to_src():
20+
s = io.BytesIO()
21+
plt.savefig(s, format='png', bbox_inches="tight")
22+
plt.close()
23+
return base64.b64encode(s.getvalue()).decode("utf-8").replace("\n", "")
24+
25+
def pie_to_bar(normalized_ff_dist):
26+
plt.rcParams["figure.figsize"] = (8,8)
27+
plt.ylim(0, 10)
28+
plt.yticks([i/2 for i in range(0, 21,1)])
29+
plt.grid(linestyle='--', linewidth='0.5', color='black',)
30+
for i in range(0, 10):
31+
c=None
32+
a=0.2
33+
if(i<1):
34+
c="yellow"
35+
elif(i<5):
36+
c="green"
37+
else:
38+
c="red"
39+
if(2<=i<4 or i>=7):
40+
a=0.4
41+
plt.axhspan(i, i+1, facecolor=c, alpha=a)
42+
plt.bar(["V","P","K"],normalized_ff_dist,color=["yellow","red","blue"],edgecolor="black",width=0.5)
43+
for index, value in enumerate(["Vatt","Pitta","Kafa"]):
44+
plt.text(index-0.1, normalized_ff_dist[index]+0.1, str(round(normalized_ff_dist[index],3)),fontsize=15)
45+
plt.title("Vatt , Pitta , Kafa Scores ")
46+
plt.show()
47+
48+
def store(data,mt,sr,ff=None,err=None):
49+
fields=[str(data),str(mt),str(sr),str(ff),str(err),str(time.time())]
50+
f=open("data.csv","a+")
51+
f.write(';'.join(fields)+"\n")
52+
f.flush()
53+
f.close()
54+
55+
@app.route('/', methods = ['POST','GET'])
56+
def hello_world():
57+
if request.method == 'POST':
58+
hdata = request.form.get('hdata')
59+
dataplt=None
60+
pie=None
61+
bar=None
62+
sampling_rate=None
63+
measure_length=None
64+
normalized_ff_dist=None
65+
#return hdata
66+
try:
67+
hdata=json.loads(hdata)
68+
data=np.array(hdata['bright'])[120:]
69+
datetims=np.array(hdata['time'])[120:]
70+
measure_length=(datetims[-1]-datetims[0])/60000
71+
72+
data=scipy.signal.detrend(data)
73+
sampling_rate=hp.get_samplerate_mstimer(datetims)
74+
#smooth and scale
75+
data=hp.scale_data(data)
76+
data=hp.smooth_signal(data,sampling_rate,window_length=30,polyorder=3)
77+
78+
79+
plt.rcParams["figure.figsize"] = (10,5)
80+
plt.title("Heart Data - Raw ")
81+
plt.plot(range(0,len(data)),data)
82+
dataplt=plt_to_src()
83+
84+
working_data, measures = hp.process(data, sampling_rate,freq_method='fft',calc_freq=True)
85+
hp.plotter(working_data, measures,moving_average=True,show=False)
86+
peak_detection=plt_to_src()
87+
88+
ff_dist=hrv.get_frequency_domain_features(working_data["RR_list"],sampling_frequency=sampling_rate,method="lomb")
89+
normalized_ff_dist=[i/ff_dist["total_power"]*10 for i in [ff_dist["vlf"],ff_dist["lf"],ff_dist["hf"]]]
90+
plt.pie(normalized_ff_dist,labels=["Very low ","Low ","High"])
91+
plt.title("Frequency distribution ")
92+
plt.show()
93+
pie=plt_to_src()
94+
95+
pie_to_bar(normalized_ff_dist)
96+
97+
bar=plt_to_src()
98+
store(hdata,measure_length,sampling_rate,ff=normalized_ff_dist,err=None)
99+
except Exception as e :
100+
exc_type, exc_obj, exc_tb = sys.exc_info()
101+
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
102+
e=str(exc_type)+str( fname) + str(exc_tb.tb_lineno)
103+
104+
store(hdata,measure_length,sampling_rate,ff=normalized_ff_dist,err=str(e))
105+
106+
return render_template("main.html",dataplt = dataplt,error=str(e),sampling_rate=sampling_rate,measure_length=measure_length)
107+
108+
return render_template("main.html",dataplt=dataplt,peak_detection_graph = peak_detection,pie=pie,bar=bar,sampling_rate=sampling_rate,measure_length=measure_length)
109+
110+
return 'No data recieved!'
111+

0 commit comments

Comments
 (0)