nightfury commited on
Commit
f22bd8f
·
verified ·
1 Parent(s): cf0f019

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -0
app.py CHANGED
@@ -1,6 +1,201 @@
1
  import gradio as gr
2
  import numpy as np
3
  import io
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  from scipy.io import wavfile
5
  import speech_recognition as sr
6
  import soundfile as sf
@@ -188,6 +383,7 @@ with gr.Blocks(title="Morse Code Decoder & Generator") as demo:
188
 
189
  # Launch the app
190
  demo.launch()
 
191
 
192
  '''
193
  import gradio as gr
 
1
  import gradio as gr
2
  import numpy as np
3
  import io
4
+ import tempfile
5
+ import os
6
+ from scipy.io import wavfile
7
+ import speech_recognition as sr
8
+ import soundfile as sf
9
+
10
+ # Morse code dictionary (ITU standard)
11
+ MORSE_CODE_DICT = {
12
+ 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
13
+ 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
14
+ 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
15
+ 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
16
+ 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--',
17
+ '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..',
18
+ '9': '----.', '0': '-----', ' ': '/'
19
+ }
20
+ MORSE_TO_CHAR = {v: k for k, v in MORSE_CODE_DICT.items()}
21
+
22
+ # Morse code timing (in seconds)
23
+ DIT_DURATION = 0.1 # 100ms for dit
24
+ DAH_DURATION = 3 * DIT_DURATION # 300ms for dah
25
+ SPACE_DURATION = 7 * DIT_DURATION # 700ms for word space
26
+ CHAR_SPACE = DIT_DURATION # Space between characters
27
+ SAMPLE_RATE = 44100 # Standard audio sample rate
28
+
29
+ # Decode Morse from audio
30
+ def decode_morse_from_audio(audio_data):
31
+ if audio_data is None:
32
+ return "", ""
33
+ sample_rate, data = audio_data
34
+ if len(data.shape) > 1:
35
+ data = data.mean(axis=1)
36
+ data = data / np.max(np.abs(data))
37
+
38
+ threshold = 0.1
39
+ signal = data > threshold
40
+ morse_code, decoded_text = "", ""
41
+ i = 0
42
+
43
+ while i < len(signal) - int(SAMPLE_RATE * DIT_DURATION):
44
+ if signal[i]:
45
+ start = i
46
+ while i < len(signal) and signal[i]:
47
+ i += 1
48
+ duration = (i - start) / sample_rate
49
+ morse_code += "-" if duration >= DAH_DURATION else "."
50
+ else:
51
+ start = i
52
+ while i < len(signal) and not signal[i]:
53
+ i += 1
54
+ pause = (i - start) / sample_rate
55
+ if pause >= SPACE_DURATION and morse_code:
56
+ decoded_text += " "
57
+ morse_code = ""
58
+ elif pause >= DIT_DURATION and morse_code:
59
+ decoded_text += MORSE_TO_CHAR.get(morse_code, "?")
60
+ morse_code = ""
61
+ i += 1
62
+
63
+ if morse_code:
64
+ decoded_text += MORSE_TO_CHAR.get(morse_code, "?")
65
+ return morse_code, decoded_text.strip()
66
+
67
+ # Convert text to Morse code
68
+ def text_to_morse(text):
69
+ text = text.upper()
70
+ morse = " ".join(MORSE_CODE_DICT.get(char, "?") for char in text if char in MORSE_CODE_DICT)
71
+ return morse
72
+
73
+ # Generate Morse code audio and save to temporary file
74
+ def generate_morse_audio(morse):
75
+ audio = []
76
+ frequency = 750 # Hz for Morse tone
77
+
78
+ for symbol in morse.split():
79
+ if symbol == "/":
80
+ audio.extend([0] * int(SAMPLE_RATE * SPACE_DURATION))
81
+ else:
82
+ for char in symbol:
83
+ duration = DAH_DURATION if char == "-" else DIT_DURATION
84
+ t = np.linspace(0, duration, int(SAMPLE_RATE * duration), False)
85
+ tone = 0.5 * np.sin(2 * np.pi * frequency * t)
86
+ audio.extend(tone)
87
+ audio.extend([0] * int(SAMPLE_RATE * DIT_DURATION)) # Space between dits/dahs
88
+ audio.extend([0] * int(SAMPLE_RATE * CHAR_SPACE)) # Space between characters
89
+
90
+ audio = np.array(audio, dtype=np.float32)
91
+ # Save to a temporary file
92
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
93
+ sf.write(temp_file.name, audio, SAMPLE_RATE, format="wav")
94
+ temp_file_path = temp_file.name
95
+ return temp_file_path
96
+
97
+ # Speech to text
98
+ def speech_to_text(audio_path):
99
+ recognizer = sr.Recognizer()
100
+ with sr.AudioFile(audio_path) as source:
101
+ audio_data = recognizer.record(source)
102
+ try:
103
+ return recognizer.recognize_google(audio_data)
104
+ except sr.UnknownValueError:
105
+ return "Could not understand audio"
106
+ except sr.RequestError:
107
+ return "Speech recognition service unavailable"
108
+
109
+ # Highlight alphabet in UI
110
+ def generate_alphabet_html(decoded_text):
111
+ html = "<div style='font-family: monospace; font-size: 16px;'>"
112
+ for char in MORSE_CODE_DICT.keys():
113
+ color = "red" if char in decoded_text.upper() else "black"
114
+ html += f"<span style='color: {color}; margin: 5px;'>{char}: {MORSE_CODE_DICT[char]}</span>"
115
+ if char in "AEIMQUZ":
116
+ html += "<br>"
117
+ html += "</div>"
118
+ return html
119
+
120
+ # Combined processing function with cleanup
121
+ def process_input(text=None, speech=None, audio=None):
122
+ morse, decoded_text, audio_output = "", "", None
123
+
124
+ if text: # Text input
125
+ morse = text_to_morse(text)
126
+ decoded_text = text
127
+ audio_output = generate_morse_audio(morse)
128
+
129
+ elif speech: # Speech input
130
+ text = speech_to_text(speech)
131
+ morse = text_to_morse(text)
132
+ decoded_text = text
133
+ audio_output = generate_morse_audio(morse)
134
+
135
+ elif audio: # Live audio input
136
+ morse, decoded_text = decode_morse_from_audio(audio)
137
+
138
+ alphabet_html = generate_alphabet_html(decoded_text)
139
+ return morse, decoded_text, alphabet_html, audio_output
140
+
141
+ # Gradio UI with Blocks
142
+ with gr.Blocks(title="Morse Code Decoder & Generator") as demo:
143
+ gr.Markdown("# Morse Code Decoder & Generator")
144
+ gr.Markdown("Decode live Morse audio, or generate Morse from text/speech!")
145
+
146
+ with gr.Tab("Decode Live Audio"):
147
+ audio_input = gr.Audio(type="numpy", label="Live Audio Input (Use Microphone)", streaming=True)
148
+ with gr.Row():
149
+ with gr.Column():
150
+ morse_output = gr.Textbox(label="Detected Morse Code", interactive=False)
151
+ text_output = gr.Textbox(label="Decoded Text", interactive=False)
152
+ alphabet_display = gr.HTML(label="Morse Alphabet (Highlighted)")
153
+
154
+ audio_input.stream(
155
+ fn=process_input,
156
+ inputs=[audio_input],
157
+ outputs=[morse_output, text_output, alphabet_display, gr.Audio(visible=False)],
158
+ )
159
+
160
+ with gr.Tab("Generate from Text"):
161
+ text_input = gr.Textbox(label="Enter Text", placeholder="Type here...")
162
+ generate_btn = gr.Button("Generate Morse")
163
+ with gr.Row():
164
+ with gr.Column():
165
+ morse_gen_output = gr.Textbox(label="Morse Code", interactive=False)
166
+ text_gen_output = gr.Textbox(label="Original Text", interactive=False)
167
+ gen_alphabet_display = gr.HTML(label="Morse Alphabet (Highlighted)")
168
+ audio_playback = gr.Audio(label="Morse Audio Playback", interactive=False)
169
+
170
+ generate_btn.click(
171
+ fn=process_input,
172
+ inputs=[text_input],
173
+ outputs=[morse_gen_output, text_gen_output, gen_alphabet_display, audio_playback]
174
+ )
175
+
176
+ with gr.Tab("Generate from Speech"):
177
+ speech_input = gr.Audio(type="filepath", label="Speak Your Text (Record Audio)")
178
+ speech_btn = gr.Button("Convert Speech to Morse")
179
+ with gr.Row():
180
+ with gr.Column():
181
+ morse_speech_output = gr.Textbox(label="Morse Code", interactive=False)
182
+ text_speech_output = gr.Textbox(label="Transcribed Text", interactive=False)
183
+ speech_alphabet_display = gr.HTML(label="Morse Alphabet (Highlighted)")
184
+ speech_audio_playback = gr.Audio(label="Morse Audio Playback", interactive=False)
185
+
186
+ speech_btn.click(
187
+ fn=process_input,
188
+ inputs=[speech_input],
189
+ outputs=[morse_speech_output, text_speech_output, speech_alphabet_display, speech_audio_playback]
190
+ )
191
+
192
+ # Launch the app
193
+ demo.launch()
194
+
195
+ '''
196
+ import gradio as gr
197
+ import numpy as np
198
+ import io
199
  from scipy.io import wavfile
200
  import speech_recognition as sr
201
  import soundfile as sf
 
383
 
384
  # Launch the app
385
  demo.launch()
386
+ '''
387
 
388
  '''
389
  import gradio as gr