Spaces:
Sleeping
Sleeping
File size: 17,684 Bytes
58eb194 | 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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | # React Native Migration Guide
## From HTML/JS to Mobile App with FastAPI Backend
---
## Overview
You'll migrate your voice translation app from browser (HTML/JS) to a native mobile app using React Native while keeping your FastAPI backend unchanged.
**Architecture:**
```
React Native App (Mobile)
β WebSocket
FastAPI Backend (Same as before)
β
ASR β MT β TTS Pipeline
```
---
## Phase 1: Setup React Native Project
### 1. Install Prerequisites
```bash
# Install Node.js (if not already installed)
# Download from: https://nodejs.org/
# Install React Native CLI
npm install -g react-native-cli
# For Android: Install Android Studio
# For iOS: Install Xcode (Mac only)
```
### 2. Create New Project
```bash
# Create React Native project
npx react-native init VoiceTranslationApp
cd VoiceTranslationApp
# Install required packages
npm install @react-native-community/netinfo
npm install react-native-webrtc
npm install @react-native-async-storage/async-storage
```
---
## Phase 2: Audio Capture Setup
### Install Audio Libraries
```bash
# For microphone access and audio recording
npm install react-native-audio-recorder-player
# For real-time audio streaming
npm install react-native-live-audio-stream
```
### Configure Permissions
**Android: `android/app/src/main/AndroidManifest.xml`**
```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Add these permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application>
...
</application>
</manifest>
```
**iOS: `ios/VoiceTranslationApp/Info.plist`**
```xml
<key>NSMicrophoneUsageDescription</key>
<string>We need microphone access for voice translation</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
```
---
## Phase 3: Core Components
### 1. WebSocket Service (`src/services/WebSocketService.js`)
```javascript
class WebSocketService {
constructor() {
this.ws = null;
this.listeners = {};
}
connect(roomId, userId, nativeLanguage, onMessage, onError) {
const wsUrl = `ws://YOUR_BACKEND_IP:8000/ws/call/${roomId}/${userId}`;
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('WebSocket connected');
// Send initial config
this.ws.send(JSON.stringify({
native_lang: nativeLanguage
}));
if (this.listeners.onConnect) {
this.listeners.onConnect();
}
};
this.ws.onmessage = (event) => {
if (typeof event.data === 'string') {
// JSON message
const msg = JSON.parse(event.data);
onMessage(msg);
} else {
// Binary audio data
onMessage({ type: 'audio', data: event.data });
}
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
onError(error);
};
this.ws.onclose = () => {
console.log('WebSocket disconnected');
if (this.listeners.onDisconnect) {
this.listeners.onDisconnect();
}
};
}
sendAudio(audioData) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(audioData);
}
}
disconnect() {
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
on(event, callback) {
this.listeners[event] = callback;
}
}
export default new WebSocketService();
```
### 2. Audio Streaming Service (`src/services/AudioStreamService.js`)
```javascript
import LiveAudioStream from 'react-native-live-audio-stream';
class AudioStreamService {
constructor() {
this.isStreaming = false;
}
async start(onAudioData) {
const options = {
sampleRate: 16000, // Match your backend
channels: 1, // Mono
bitsPerSample: 16, // 16-bit PCM
audioSource: 6, // VOICE_RECOGNITION for Android
bufferSize: 8192 // Chunk size
};
LiveAudioStream.init(options);
LiveAudioStream.on('data', data => {
// data is base64 encoded PCM audio
if (onAudioData) {
// Convert base64 to binary
const audioBuffer = Buffer.from(data, 'base64');
onAudioData(audioBuffer);
}
});
LiveAudioStream.start();
this.isStreaming = true;
console.log('Audio streaming started');
}
stop() {
if (this.isStreaming) {
LiveAudioStream.stop();
this.isStreaming = false;
console.log('Audio streaming stopped');
}
}
}
export default new AudioStreamService();
```
### 3. Audio Playback Service (`src/services/AudioPlaybackService.js`)
```javascript
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
import RNFS from 'react-native-fs';
class AudioPlaybackService {
constructor() {
this.audioRecorderPlayer = new AudioRecorderPlayer();
}
async playAudioFromBlob(audioBlob) {
try {
// Save blob to temp file
const tempPath = `${RNFS.CachesDirectoryPath}/temp_audio.wav`;
// Convert blob to base64
const base64Audio = await this.blobToBase64(audioBlob);
// Write to file
await RNFS.writeFile(tempPath, base64Audio, 'base64');
// Play audio
await this.audioRecorderPlayer.startPlayer(tempPath);
this.audioRecorderPlayer.addPlayBackListener((e) => {
if (e.currentPosition === e.duration) {
this.audioRecorderPlayer.stopPlayer();
// Clean up temp file
RNFS.unlink(tempPath);
}
});
} catch (error) {
console.error('Playback error:', error);
}
}
blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64 = reader.result.split(',')[1];
resolve(base64);
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
async stop() {
await this.audioRecorderPlayer.stopPlayer();
}
}
export default new AudioPlaybackService();
```
---
## Phase 4: Main Screen Component
### `App.js`
```javascript
import React, { useState, useEffect } from 'react';
import {
SafeAreaView,
StyleSheet,
View,
Text,
TouchableOpacity,
ActivityIndicator,
TextInput,
Picker
} from 'react-native';
import WebSocketService from './src/services/WebSocketService';
import AudioStreamService from './src/services/AudioStreamService';
import AudioPlaybackService from './src/services/AudioPlaybackService';
const App = () => {
const [isConnected, setIsConnected] = useState(false);
const [isStreaming, setIsStreaming] = useState(false);
const [roomId, setRoomId] = useState('room1');
const [userId] = useState(`user_${Math.random().toString(36).substr(2, 9)}`);
const [nativeLanguage, setNativeLanguage] = useState('en');
const [translatedText, setTranslatedText] = useState('Waiting for translation...');
const [originalText, setOriginalText] = useState('-');
const [status, setStatus] = useState('Disconnected');
useEffect(() => {
// Setup WebSocket listeners
WebSocketService.on('onConnect', () => {
setIsConnected(true);
setStatus('Connected');
});
WebSocketService.on('onDisconnect', () => {
setIsConnected(false);
setIsStreaming(false);
setStatus('Disconnected');
AudioStreamService.stop();
});
return () => {
handleLeaveCall();
};
}, []);
const handleJoinCall = async () => {
try {
setStatus('Connecting...');
// Connect WebSocket
WebSocketService.connect(
roomId,
userId,
nativeLanguage,
handleWebSocketMessage,
(error) => {
console.error('WebSocket error:', error);
setStatus('Connection Error');
}
);
// Start audio streaming
await AudioStreamService.start((audioData) => {
// Send audio chunks to backend
WebSocketService.sendAudio(audioData);
});
setIsStreaming(true);
} catch (error) {
console.error('Failed to join call:', error);
setStatus('Failed to connect');
}
};
const handleLeaveCall = () => {
AudioStreamService.stop();
WebSocketService.disconnect();
setIsConnected(false);
setIsStreaming(false);
setStatus('Disconnected');
};
const handleWebSocketMessage = async (message) => {
if (message.type === 'audio') {
// Play received audio
await AudioPlaybackService.playAudioFromBlob(message.data);
} else if (message.type === 'caption') {
setTranslatedText(message.text);
setOriginalText(message.original);
} else if (message.info) {
setStatus(message.info);
}
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>π Voice Translation</Text>
</View>
{!isConnected && (
<View style={styles.settingsContainer}>
<Text style={styles.label}>Room ID:</Text>
<TextInput
style={styles.input}
value={roomId}
onChangeText={setRoomId}
placeholder="Enter room ID"
/>
<Text style={styles.label}>My Language:</Text>
<Picker
selectedValue={nativeLanguage}
style={styles.picker}
onValueChange={(itemValue) => setNativeLanguage(itemValue)}
>
<Picker.Item label="English" value="en" />
<Picker.Item label="French" value="fr" />
<Picker.Item label="German" value="de" />
<Picker.Item label="Spanish" value="es" />
</Picker>
</View>
)}
<View style={styles.statusContainer}>
<View style={[
styles.statusIndicator,
{ backgroundColor: isConnected ? '#4CAF50' : '#F44336' }
]} />
<Text style={styles.statusText}>{status}</Text>
</View>
{isStreaming && (
<View style={styles.recordingIndicator}>
<View style={styles.pulseCircle} />
<Text style={styles.recordingText}>Microphone Active</Text>
</View>
)}
<View style={styles.captionContainer}>
<Text style={styles.captionLabel}>Incoming Translation:</Text>
<Text style={styles.captionText}>{translatedText}</Text>
</View>
<View style={styles.captionContainer}>
<Text style={styles.captionLabel}>Original:</Text>
<Text style={styles.captionTextSmall}>{originalText}</Text>
</View>
<View style={styles.buttonContainer}>
{!isConnected ? (
<TouchableOpacity
style={[styles.button, styles.joinButton]}
onPress={handleJoinCall}
>
<Text style={styles.buttonText}>Join Call</Text>
</TouchableOpacity>
) : (
<TouchableOpacity
style={[styles.button, styles.leaveButton]}
onPress={handleLeaveCall}
>
<Text style={styles.buttonText}>Leave Call</Text>
</TouchableOpacity>
)}
</View>
<View style={styles.infoContainer}>
<Text style={styles.infoText}>
βΉοΈ Just speak naturally - the app automatically detects when you finish speaking and translates to the other person.
</Text>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5f5f5',
},
header: {
padding: 20,
backgroundColor: '#007bff',
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: 'white',
textAlign: 'center',
},
settingsContainer: {
padding: 20,
backgroundColor: 'white',
margin: 10,
borderRadius: 10,
},
label: {
fontSize: 16,
fontWeight: 'bold',
marginTop: 10,
marginBottom: 5,
},
input: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 5,
padding: 10,
fontSize: 16,
},
picker: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 5,
},
statusContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 15,
backgroundColor: 'white',
margin: 10,
borderRadius: 10,
},
statusIndicator: {
width: 12,
height: 12,
borderRadius: 6,
marginRight: 10,
},
statusText: {
fontSize: 16,
fontWeight: 'bold',
},
recordingIndicator: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
padding: 10,
backgroundColor: '#ffe6e6',
margin: 10,
borderRadius: 10,
},
pulseCircle: {
width: 12,
height: 12,
borderRadius: 6,
backgroundColor: '#F44336',
marginRight: 10,
},
recordingText: {
color: '#F44336',
fontWeight: 'bold',
},
captionContainer: {
padding: 15,
backgroundColor: 'white',
margin: 10,
borderRadius: 10,
borderLeftWidth: 4,
borderLeftColor: '#007bff',
},
captionLabel: {
fontSize: 12,
color: '#666',
marginBottom: 5,
},
captionText: {
fontSize: 18,
color: '#333',
},
captionTextSmall: {
fontSize: 14,
color: '#666',
},
buttonContainer: {
padding: 20,
},
button: {
padding: 15,
borderRadius: 10,
alignItems: 'center',
},
joinButton: {
backgroundColor: '#007bff',
},
leaveButton: {
backgroundColor: '#F44336',
},
buttonText: {
color: 'white',
fontSize: 18,
fontWeight: 'bold',
},
infoContainer: {
padding: 15,
backgroundColor: '#e7f3ff',
margin: 10,
borderRadius: 10,
},
infoText: {
fontSize: 14,
color: '#333',
},
});
export default App;
```
---
## Phase 5: Backend Changes
### Update Your Backend IP Address
In your FastAPI backend, make sure it's accessible from your phone:
**Option A: Same WiFi Network**
```bash
# Find your computer's local IP
# Windows: ipconfig
# Mac/Linux: ifconfig
# Run backend with:
uvicorn main:app --host 0.0.0.0 --port 8000
```
**Option B: Ngrok Tunnel (for testing)**
```bash
# Install ngrok
# Download from: https://ngrok.com/
# Tunnel to your backend
ngrok http 8000
# Use the ngrok URL in your React Native app
# ws://YOUR_NGROK_URL/ws/call/...
```
### Update CORS (if needed)
Add to your `main.py`:
```python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # For development - restrict in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
```
---
## Phase 6: Build and Run
### Android
```bash
# Connect Android device via USB with USB debugging enabled
# OR start Android emulator
# Run app
npx react-native run-android
```
### iOS (Mac only)
```bash
# Install pods
cd ios && pod install && cd ..
# Run app
npx react-native run-ios
```
---
## Common Issues and Solutions
### Issue 1: Audio Not Streaming
**Solution:** Check microphone permissions
```javascript
import { PermissionsAndroid, Platform } from 'react-native';
async function requestMicrophonePermission() {
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
}
return true;
}
// Call before starting audio
await requestMicrophonePermission();
```
### Issue 2: WebSocket Not Connecting
**Solution:** Make sure backend IP is correct
```javascript
// Test backend accessibility
fetch('http://YOUR_BACKEND_IP:8000/health')
.then(res => console.log('Backend reachable'))
.catch(err => console.error('Cannot reach backend:', err));
```
### Issue 3: Audio Quality Issues
**Solution:** Adjust audio parameters
```javascript
const options = {
sampleRate: 16000, // Match backend
channels: 1,
bitsPerSample: 16,
audioSource: 6, // VOICE_RECOGNITION
bufferSize: 4096 // Try different sizes: 2048, 4096, 8192
};
```
---
## Testing Checklist
- [ ] Microphone permission granted
- [ ] WebSocket connects to backend
- [ ] Audio streams continuously
- [ ] VAD detects speech/silence
- [ ] Translation received and played
- [ ] Captions display correctly
- [ ] Leave call cleans up resources
- [ ] Works on both WiFi and mobile data (if using ngrok)
---
## Production Deployment
### Backend Hosting
**Option 1: Cloud Server (AWS, DigitalOcean, etc.)**
```bash
# Deploy FastAPI to cloud
# Use Nginx + Uvicorn for production
# Enable SSL (wss:// for WebSocket)
```
**Option 2: Serverless (AWS Lambda + API Gateway)**
- More complex setup
- WebSocket support via API Gateway
- May have latency issues
### App Store Deployment
**Android (Google Play)**
```bash
# Generate signed APK
cd android
./gradlew assembleRelease
```
**iOS (App Store)**
```bash
# Build in Xcode
# Archive and submit to App Store Connect
```
---
## Next Steps
1. **Test with current HTML frontend first** - Make sure VAD works
2. **Set up React Native project** - Get basic UI working
3. **Implement audio streaming** - Test microphone β WebSocket
4. **Add playback** - Test receiving and playing audio
5. **Polish UI** - Add animations, better error handling
6. **Deploy** - Cloud backend + app stores
---
## Estimated Timeline
- **Week 1:** VAD in HTML/JS (verify it works)
- **Week 2:** React Native setup + basic UI
- **Week 3:** Audio streaming + WebSocket integration
- **Week 4:** Polish + testing + deployment
Good luck! π
|