Spaces:
Sleeping
Sleeping
update app.py with circle
Browse files
app.py
CHANGED
@@ -4,43 +4,43 @@ import librosa
|
|
4 |
import librosa.display
|
5 |
import numpy as np
|
6 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
7 |
|
8 |
# Load the pre-trained model
|
9 |
model = tf.keras.models.load_model("model.h5")
|
10 |
|
11 |
# Function to process audio, predict, and generate results
|
12 |
-
def process_audio(audio_file):
|
13 |
try:
|
14 |
# Load the audio file
|
15 |
y, sr = librosa.load(audio_file, sr=16000)
|
16 |
-
|
17 |
# Detect segments (e.g., using energy or silence)
|
18 |
intervals = librosa.effects.split(y, top_db=20)
|
19 |
-
|
20 |
results = []
|
21 |
-
|
22 |
plt.figure(figsize=(10, 4))
|
23 |
librosa.display.waveshow(y, sr=sr, alpha=0.5)
|
24 |
-
|
25 |
# Process each segment
|
26 |
for i, (start, end) in enumerate(intervals):
|
27 |
segment = y[start:end]
|
28 |
duration = (end - start) / sr
|
29 |
-
|
30 |
# Compute the amplitude (mean absolute value)
|
31 |
amplitude = np.mean(np.abs(segment))
|
32 |
-
|
33 |
# Extract MFCC features
|
34 |
mfcc = librosa.feature.mfcc(y=segment, sr=sr, n_mfcc=13)
|
35 |
mfcc = np.mean(mfcc, axis=1).reshape(1, -1)
|
36 |
-
|
37 |
-
# Predict inhale or exhale
|
38 |
prediction = model.predict(mfcc)
|
39 |
-
|
40 |
-
|
41 |
-
# Assign label based on amplitude
|
42 |
-
label = "Inhale" if amplitude > 0.05 else "Exhale" # Threshold for exhale
|
43 |
-
|
44 |
# Append results
|
45 |
results.append({
|
46 |
"Segment": i + 1,
|
@@ -48,41 +48,113 @@ def process_audio(audio_file):
|
|
48 |
"Duration (s)": round(duration, 2),
|
49 |
"Amplitude": round(amplitude, 4)
|
50 |
})
|
51 |
-
|
52 |
-
# Highlight segment on waveform
|
53 |
plt.axvspan(start / sr, end / sr, color='red' if label == "Inhale" else 'blue', alpha=0.3)
|
54 |
-
|
55 |
# Save the waveform with highlighted segments
|
56 |
plt.title("Audio Waveform with Inhale/Exhale Segments")
|
57 |
plt.xlabel("Time (s)")
|
58 |
plt.ylabel("Amplitude")
|
59 |
plt.savefig("waveform_highlighted.png")
|
60 |
plt.close()
|
61 |
-
|
62 |
# Format results as a table
|
63 |
result_table = "Segment\tType\tDuration (s)\tAmplitude\n" + "\n".join(
|
64 |
f"{row['Segment']}\t{row['Type']}\t{row['Duration (s)']}\t{row['Amplitude']}" for row in results
|
65 |
)
|
66 |
-
|
67 |
return result_table, "waveform_highlighted.png"
|
68 |
-
|
69 |
except Exception as e:
|
70 |
return f"Error: {str(e)}", None
|
71 |
|
72 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
with gr.Blocks() as demo:
|
74 |
gr.Markdown("### Breathe Training Application")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
with gr.Row():
|
76 |
-
|
|
|
77 |
result_output = gr.Textbox(label="Prediction Results (Table)")
|
78 |
waveform_output = gr.Image(label="Waveform with Highlighted Segments")
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
fn=process_audio,
|
83 |
-
inputs=[
|
84 |
-
outputs=[result_output, waveform_output]
|
85 |
)
|
86 |
|
87 |
# Run the Gradio app
|
88 |
-
demo.launch()
|
|
|
4 |
import librosa.display
|
5 |
import numpy as np
|
6 |
import matplotlib.pyplot as plt
|
7 |
+
import sounddevice as sd
|
8 |
+
import soundfile as sf
|
9 |
+
import threading
|
10 |
|
11 |
# Load the pre-trained model
|
12 |
model = tf.keras.models.load_model("model.h5")
|
13 |
|
14 |
# Function to process audio, predict, and generate results
|
15 |
+
def process_audio(audio_file, breath_in_time, breath_out_time):
|
16 |
try:
|
17 |
# Load the audio file
|
18 |
y, sr = librosa.load(audio_file, sr=16000)
|
19 |
+
|
20 |
# Detect segments (e.g., using energy or silence)
|
21 |
intervals = librosa.effects.split(y, top_db=20)
|
22 |
+
|
23 |
results = []
|
24 |
+
|
25 |
plt.figure(figsize=(10, 4))
|
26 |
librosa.display.waveshow(y, sr=sr, alpha=0.5)
|
27 |
+
|
28 |
# Process each segment
|
29 |
for i, (start, end) in enumerate(intervals):
|
30 |
segment = y[start:end]
|
31 |
duration = (end - start) / sr
|
32 |
+
|
33 |
# Compute the amplitude (mean absolute value)
|
34 |
amplitude = np.mean(np.abs(segment))
|
35 |
+
|
36 |
# Extract MFCC features
|
37 |
mfcc = librosa.feature.mfcc(y=segment, sr=sr, n_mfcc=13)
|
38 |
mfcc = np.mean(mfcc, axis=1).reshape(1, -1)
|
39 |
+
|
40 |
+
# Predict inhale or exhale
|
41 |
prediction = model.predict(mfcc)
|
42 |
+
label = "Inhale" if np.argmax(prediction) == 0 else "Exhale"
|
43 |
+
|
|
|
|
|
|
|
44 |
# Append results
|
45 |
results.append({
|
46 |
"Segment": i + 1,
|
|
|
48 |
"Duration (s)": round(duration, 2),
|
49 |
"Amplitude": round(amplitude, 4)
|
50 |
})
|
51 |
+
|
52 |
+
# Highlight segment on waveform
|
53 |
plt.axvspan(start / sr, end / sr, color='red' if label == "Inhale" else 'blue', alpha=0.3)
|
54 |
+
|
55 |
# Save the waveform with highlighted segments
|
56 |
plt.title("Audio Waveform with Inhale/Exhale Segments")
|
57 |
plt.xlabel("Time (s)")
|
58 |
plt.ylabel("Amplitude")
|
59 |
plt.savefig("waveform_highlighted.png")
|
60 |
plt.close()
|
61 |
+
|
62 |
# Format results as a table
|
63 |
result_table = "Segment\tType\tDuration (s)\tAmplitude\n" + "\n".join(
|
64 |
f"{row['Segment']}\t{row['Type']}\t{row['Duration (s)']}\t{row['Amplitude']}" for row in results
|
65 |
)
|
66 |
+
|
67 |
return result_table, "waveform_highlighted.png"
|
68 |
+
|
69 |
except Exception as e:
|
70 |
return f"Error: {str(e)}", None
|
71 |
|
72 |
+
# Function to record audio for a specified duration
|
73 |
+
def record_audio(duration):
|
74 |
+
try:
|
75 |
+
audio_file = "recorded_audio.wav"
|
76 |
+
print(f"Recording for {duration} seconds...")
|
77 |
+
recording = sd.rec(int(duration * 16000), samplerate=16000, channels=1, dtype='float32')
|
78 |
+
sd.wait()
|
79 |
+
sf.write(audio_file, recording, 16000)
|
80 |
+
print("Recording complete!")
|
81 |
+
return audio_file
|
82 |
+
except Exception as e:
|
83 |
+
return f"Error: {str(e)}"
|
84 |
+
|
85 |
+
# Gradio Interface
|
86 |
with gr.Blocks() as demo:
|
87 |
gr.Markdown("### Breathe Training Application")
|
88 |
+
|
89 |
+
# Breath cycle configuration
|
90 |
+
with gr.Row():
|
91 |
+
breath_in_time = gr.Number(label="Breathe In Time (seconds)", value=3, interactive=True)
|
92 |
+
breath_out_time = gr.Number(label="Breathe Out Time (seconds)", value=3, interactive=True)
|
93 |
+
|
94 |
+
# Circle Animation using Custom HTML and CSS
|
95 |
+
gr.HTML("""
|
96 |
+
<div style="text-align: center;">
|
97 |
+
<div id="circle" style="
|
98 |
+
width: 100px;
|
99 |
+
height: 100px;
|
100 |
+
border-radius: 50%;
|
101 |
+
background-color: lightblue;
|
102 |
+
margin: 20px auto;
|
103 |
+
animation: breathe 6s infinite;">
|
104 |
+
</div>
|
105 |
+
<p id="instruction" style="font-size: 20px; font-weight: bold;">Breathe In...</p>
|
106 |
+
</div>
|
107 |
+
<style>
|
108 |
+
@keyframes breathe {
|
109 |
+
0% { transform: scale(1); }
|
110 |
+
50% { transform: scale(1.5); }
|
111 |
+
100% { transform: scale(1); }
|
112 |
+
}
|
113 |
+
</style>
|
114 |
+
<script>
|
115 |
+
const instruction = document.getElementById("instruction");
|
116 |
+
let breatheInTime = 3; // Default value for inhale
|
117 |
+
let breatheOutTime = 3; // Default value for exhale
|
118 |
+
|
119 |
+
function updateBreathingCycle(inTime, outTime) {
|
120 |
+
breatheInTime = inTime;
|
121 |
+
breatheOutTime = outTime;
|
122 |
+
const totalTime = inTime + outTime;
|
123 |
+
const keyframes = `
|
124 |
+
@keyframes breathe {
|
125 |
+
0% { transform: scale(1); }
|
126 |
+
${Math.round((inTime / totalTime) * 100)}% { transform: scale(1.5); }
|
127 |
+
100% { transform: scale(1); }
|
128 |
+
}
|
129 |
+
`;
|
130 |
+
const styleSheet = document.styleSheets[0];
|
131 |
+
styleSheet.insertRule(keyframes, styleSheet.cssRules.length);
|
132 |
+
|
133 |
+
let isInhaling = true;
|
134 |
+
setInterval(() => {
|
135 |
+
instruction.textContent = isInhaling ? "Breathe In..." : "Breathe Out...";
|
136 |
+
isInhaling = !isInhaling;
|
137 |
+
}, inTime * 1000);
|
138 |
+
}
|
139 |
+
|
140 |
+
// Default breathing cycle
|
141 |
+
updateBreathingCycle(breatheInTime, breatheOutTime);
|
142 |
+
</script>
|
143 |
+
""")
|
144 |
+
|
145 |
+
# File upload and analysis
|
146 |
with gr.Row():
|
147 |
+
record_button = gr.Button("Start Recording")
|
148 |
+
audio_input = gr.Audio(type="filepath", label="Upload Audio (optional)")
|
149 |
result_output = gr.Textbox(label="Prediction Results (Table)")
|
150 |
waveform_output = gr.Image(label="Waveform with Highlighted Segments")
|
151 |
+
|
152 |
+
# Handle recording and analysis
|
153 |
+
record_button.click(
|
154 |
+
fn=lambda breath_in, breath_out: process_audio(record_audio(breath_in + breath_out), breath_in, breath_out),
|
155 |
+
inputs=[breath_in_time, breath_out_time],
|
156 |
+
outputs=[result_output, waveform_output],
|
157 |
)
|
158 |
|
159 |
# Run the Gradio app
|
160 |
+
demo.launch()
|