Spaces:
Sleeping
Sleeping
File size: 12,855 Bytes
b068b7b df0a64d 87484df df0a64d 87484df df0a64d 87484df df0a64d 87484df df0a64d 87484df df0a64d 87484df df0a64d 87484df df0a64d 87484df df0a64d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
import gradio as gr
import numpy as np
import subprocess
import tempfile
import os
import json
from pathlib import Path
import base64
import wave
# Install ggwave if not already installed
try:
import ggwave
except ImportError:
subprocess.run(["pip", "install", "ggwave"], check=True)
import ggwave
class GGWaveTransceiver:
def __init__(self):
self.sample_rate = 48000
self.protocols = {
'Normal': 0, # Normal audible
'Fast': 1, # Fast audible
'Fastest': 2, # Fastest audible
'Ultrasonic Normal': 3, # Ultrasonic normal
'Ultrasonic Fast': 4, # Ultrasonic fast
'Ultrasonic Fastest': 5, # Ultrasonic fastest
'DT Normal': 6, # Data Transfer normal
'DT Fast': 7, # Data Transfer fast
'DT Fastest': 8, # Data Transfer fastest
}
def encode_text_to_audio(self, text, protocol='Normal', volume=50):
"""Encode text to audio using ggwave"""
try:
protocol_id = self.protocols.get(protocol, 0)
# Use the simple ggwave.encode function
audio_data = ggwave.encode(text, protocolId=protocol_id, volume=volume)
if audio_data is None:
return None, "Failed to encode text"
# Convert bytes to numpy array (ggwave returns raw bytes)
audio_array = np.frombuffer(audio_data, dtype=np.float32)
# Create temporary WAV file
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp_file:
with wave.open(tmp_file.name, 'w') as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(self.sample_rate)
# Convert float32 to int16
audio_int16 = (audio_array * 32767).astype(np.int16)
wav_file.writeframes(audio_int16.tobytes())
return tmp_file.name, f"Successfully encoded: '{text}' using {protocol} protocol"
except Exception as e:
return None, f"Error encoding: {str(e)}"
def decode_audio_to_text(self, audio_file):
"""Decode audio file to text using ggwave"""
try:
if audio_file is None:
return "No audio file provided"
# Read audio file
with wave.open(audio_file, 'r') as wav_file:
frames = wav_file.readframes(wav_file.getnframes())
audio_data = np.frombuffer(frames, dtype=np.int16)
# Convert to float32
audio_float = audio_data.astype(np.float32) / 32767.0
# Initialize ggwave instance for decoding
instance = ggwave.init()
try:
# Decode audio in chunks
chunk_size = 1024
decoded_text = None
for i in range(0, len(audio_float), chunk_size):
chunk = audio_float[i:i+chunk_size]
# Convert chunk to bytes for ggwave
chunk_bytes = chunk.astype(np.float32).tobytes()
# Try to decode this chunk
result = ggwave.decode(instance, chunk_bytes)
if result is not None:
decoded_text = result.decode('utf-8')
break
if decoded_text:
return f"Decoded message: {decoded_text}"
else:
return "No valid ggwave signal detected in audio"
finally:
# Clean up the instance
ggwave.free(instance)
except Exception as e:
return f"Error decoding: {str(e)}"
# Initialize the transceiver
transceiver = GGWaveTransceiver()
# Gradio interface functions
def encode_text(text, protocol, volume):
"""Encode text to audio for Gradio"""
if not text.strip():
return None, "Please enter text to encode"
audio_file, message = transceiver.encode_text_to_audio(text, protocol, volume)
return audio_file, message
def decode_audio(audio_file):
"""Decode audio to text for Gradio"""
result = transceiver.decode_audio_to_text(audio_file)
return result
def create_demo_audio():
"""Create a demo audio file"""
demo_text = "Hello from ggwave!"
try:
# Use the simple ggwave.encode function directly
audio_data = ggwave.encode(demo_text, protocolId=0, volume=50)
if audio_data is None:
return None
# Convert to numpy array and create WAV file
audio_array = np.frombuffer(audio_data, dtype=np.float32)
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp_file:
with wave.open(tmp_file.name, 'w') as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(48000)
# Convert float32 to int16
audio_int16 = (audio_array * 32767).astype(np.int16)
wav_file.writeframes(audio_int16.tobytes())
return tmp_file.name
except Exception as e:
print(f"Error creating demo: {e}")
return None
# Phone integration helper functions
def get_twilio_webhook_code():
"""Return sample Twilio webhook code"""
return '''
# Twilio Webhook Integration Example
from flask import Flask, request
from twilio.twiml import VoiceResponse
import requests
app = Flask(__name__)
@app.route("/webhook", methods=['POST'])
def handle_call():
"""Handle incoming Twilio call"""
response = VoiceResponse()
# Record the call audio for ggwave processing
response.record(
max_length=30,
action='/process_recording',
transcribe=False,
play_beep=False
)
return str(response)
@app.route("/process_recording", methods=['POST'])
def process_recording():
"""Process recorded audio through ggwave"""
recording_url = request.form['RecordingUrl']
# Download the recording
audio_response = requests.get(recording_url)
# Send to your ggwave processing endpoint
# (This would be your Gradio space or separate service)
result = process_with_ggwave(audio_response.content)
# Respond back to caller
response = VoiceResponse()
response.say(f"Received data: {result}")
return str(response)
'''
def get_deployment_instructions():
"""Return deployment instructions"""
return '''
# Deployment Instructions for Phone Integration
## Option 1: Twilio Integration
1. Sign up for Twilio account
2. Get a phone number
3. Set up webhook URL pointing to your server
4. Use the provided webhook code to handle calls
## Option 2: Vonage/Nexmo Integration
Similar to Twilio, but with Vonage APIs
## Option 3: Direct SIP Integration
For more advanced users who want direct SIP handling
## Hugging Face Spaces Limitations:
- Spaces don't directly support phone call handling
- You'll need a separate service (like Heroku, Railway, etc.) for telephony
- Use this Space as your ggwave processing engine
- Call it via API from your phone handling service
## Architecture:
Phone Call β Telephony Service β Your Server β HF Space (ggwave) β Response
'''
# Create Gradio interface
with gr.Blocks(title="GGWave Phone Data Transfer", theme=gr.themes.Soft()) as app:
gr.Markdown("""
# π΅ GGWave Phone Data Transfer System
This system demonstrates data transmission over audio using ggwave. Perfect for sending data through phone calls!
**How it works:**
1. Encode text into audio signals
2. Play the audio during a phone call
3. Decode the received audio back to text
""")
with gr.Tabs():
# Encoding tab
with gr.Tab("π€ Encode Text to Audio"):
with gr.Row():
with gr.Column():
encode_input = gr.Textbox(
label="Text to Encode",
placeholder="Enter your message here...",
lines=3
)
with gr.Row():
protocol_choice = gr.Dropdown(
choices=list(transceiver.protocols.keys()),
value="Normal",
label="Protocol"
)
volume_slider = gr.Slider(
minimum=10,
maximum=100,
value=50,
label="Volume %"
)
encode_btn = gr.Button("π΅ Generate Audio", variant="primary")
with gr.Column():
encoded_audio = gr.Audio(
label="Generated Audio",
type="filepath"
)
encode_status = gr.Textbox(
label="Status",
interactive=False
)
# Decoding tab
with gr.Tab("π₯ Decode Audio to Text"):
with gr.Row():
with gr.Column():
decode_audio_input = gr.Audio(
label="Upload Audio File",
type="filepath"
)
decode_btn = gr.Button("π Decode Audio", variant="primary")
with gr.Column():
decoded_result = gr.Textbox(
label="Decoded Message",
interactive=False,
lines=5
)
# Phone integration tab
with gr.Tab("π Phone Integration"):
gr.Markdown("""
## Setting up Phone Call Integration
Since Hugging Face Spaces can't directly handle phone calls, you'll need to integrate with a telephony service:
""")
with gr.Accordion("π Twilio Webhook Code", open=False):
twilio_code = gr.Code(
value=get_twilio_webhook_code(),
language="python",
label="Twilio Integration Code"
)
with gr.Accordion("π Deployment Instructions", open=True):
deployment_info = gr.Markdown(get_deployment_instructions())
gr.Markdown("""
## API Usage
You can call this Space programmatically:
```python
import requests
# For encoding
response = requests.post(
"https://your-space-url/api/predict",
json={"data": ["your text", "Normal", 50]}
)
# Download the generated audio
audio_url = response.json()["data"][0]
```
""")
# Testing tab
with gr.Tab("π§ͺ Test & Demo"):
gr.Markdown("## Try the Demo")
with gr.Row():
demo_btn = gr.Button("π― Generate Demo Audio", variant="secondary")
demo_audio = gr.Audio(label="Demo Audio")
gr.Markdown("""
## Testing Workflow:
1. Click "Generate Demo Audio" above
2. Download the audio file
3. Go to the "Decode" tab and upload it
4. Verify it decodes correctly
## Phone Testing:
1. Generate audio for your message
2. Call your phone integration service
3. Play the audio during the call
4. Verify the server receives the correct data
""")
# Event handlers
encode_btn.click(
fn=encode_text,
inputs=[encode_input, protocol_choice, volume_slider],
outputs=[encoded_audio, encode_status]
)
decode_btn.click(
fn=decode_audio,
inputs=[decode_audio_input],
outputs=[decoded_result]
)
demo_btn.click(
fn=create_demo_audio,
outputs=[demo_audio]
)
# Launch the app
if __name__ == "__main__":
app.launch(
server_name="0.0.0.0",
server_port=7860,
share=True
) |