All files / services sherpaTTS.ts

0% Statements 0/103
0% Branches 0/50
0% Functions 0/25
0% Lines 0/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Sherpa TTS Service - Native implementation for offline Text-to-Speech
 * Uses react-native-sherpa-onnx-offline-tts with Piper VITS models
 */
 
import { Platform, NativeModules, NativeEventEmitter } from 'react-native';
import { Paths, type Directory, File } from 'expo-file-system';
import { Asset } from 'expo-asset';
 
// Helper to get directory URI from Paths
const getDocumentDirectory = (): string => {
  try {
    return (Paths.document as Directory).uri;
  } catch {
    return '';
  }
};
 
const getBundleDirectory = (): string => {
  try {
    return (Paths.bundle as Directory).uri;
  } catch {
    return '';
  }
};
 
// Helper to check if file exists
const fileExists = async (path: string): Promise<boolean> => {
  try {
    const file = new File(path);
    return file.exists;
  } catch {
    return false;
  }
};
 
// Available Piper neural voices
export interface PiperVoice {
  id: string;
  name: string;
  description: string;
  modelDir: string;
  onnxFile: string;
  gender: 'male' | 'female';
  accent: string;
}
 
export const AVAILABLE_VOICES: PiperVoice[] = [
  {
    id: 'lessac',
    name: 'Lessac',
    description: 'American Female (Natural)',
    modelDir: 'vits-piper-en_US-lessac-medium',
    onnxFile: 'en_US-lessac-medium.onnx',
    gender: 'female',
    accent: 'US',
  },
  {
    id: 'ryan',
    name: 'Ryan',
    description: 'American Male (Natural)',
    modelDir: 'vits-piper-en_US-ryan-medium',
    onnxFile: 'en_US-ryan-medium.onnx',
    gender: 'male',
    accent: 'US',
  },
  {
    id: 'alba',
    name: 'Alba',
    description: 'British Female',
    modelDir: 'vits-piper-en_GB-alba-medium',
    onnxFile: 'en_GB-alba-medium.onnx',
    gender: 'female',
    accent: 'UK',
  },
];
 
interface SherpaTTSState {
  initialized: boolean;
  initializing: boolean;
  error: string | null;
  currentVoice: PiperVoice;
}
 
// Check if native module is available
const TTSManager = NativeModules.TTSManager;
const NATIVE_MODULE_AVAILABLE = !!TTSManager;
 
let ttsManagerEmitter: NativeEventEmitter | null = null;
if (NATIVE_MODULE_AVAILABLE) {
  ttsManagerEmitter = new NativeEventEmitter(TTSManager);
}
 
let currentState: SherpaTTSState = {
  initialized: false,
  initializing: false,
  error: null,
  currentVoice: AVAILABLE_VOICES[0],
};
 
// State listeners
const stateListeners: ((state: SherpaTTSState) => void)[] = [];
 
function updateState(updates: Partial<SherpaTTSState>) {
  currentState = { ...currentState, ...updates };
  notifyListeners();
}
 
function notifyListeners() {
  stateListeners.forEach(listener => listener({ ...currentState }));
}
 
export function addStateListener(listener: (state: SherpaTTSState) => void) {
  stateListeners.push(listener);
  listener({ ...currentState });
  return () => {
    const index = stateListeners.indexOf(listener);
    if (index >= 0) stateListeners.splice(index, 1);
  };
}
 
export function getState(): SherpaTTSState {
  return { ...currentState };
}
 
/**
 * Copy bundled TTS model assets to document directory for native access
 * NOTE: Temporarily disabled dynamic requires for Metro bundler compatibility
 */
async function copyModelToDocuments(voice: PiperVoice): Promise<string | null> {
  // TEMP: Skip dynamic requires - TTS models will be loaded differently
  return null;
 
  /* DISABLED - dynamic requires don't work with Metro bundler
  try {
    const destDir = `${FileSystem.documentDirectory}tts-models/${voice.modelDir}`;
    const onnxPath = `${destDir}/${voice.onnxFile}`;
 
    // Check if already copied
    const onnxInfo = await FileSystem.getInfoAsync(onnxPath);
    if (onnxInfo.exists) {
      return destDir;
    }
 
 
    // Create destination directory
    await FileSystem.makeDirectoryAsync(destDir, { intermediates: true });
 
    // For Expo, we need to copy from assets
    // The models are in assets/tts-models/
    const assetBase = `../assets/tts-models/${voice.modelDir}`;
 
    // Copy main ONNX file
    const onnxAsset = Asset.fromModule(require(`../assets/tts-models/${voice.modelDir}/${voice.onnxFile}`));
    await onnxAsset.downloadAsync();
    if (onnxAsset.localUri) {
      await FileSystem.copyAsync({
        from: onnxAsset.localUri,
        to: onnxPath,
      });
    }
 
    // Copy tokens.txt
    const tokensAsset = Asset.fromModule(require(`../assets/tts-models/${voice.modelDir}/tokens.txt`));
    await tokensAsset.downloadAsync();
    if (tokensAsset.localUri) {
      await FileSystem.copyAsync({
        from: tokensAsset.localUri,
        to: `${destDir}/tokens.txt`,
      });
    }
 
    // Copy espeak-ng-data directory
    // This is more complex - need to copy entire directory
    const espeakDestDir = `${destDir}/espeak-ng-data`;
    await FileSystem.makeDirectoryAsync(espeakDestDir, { intermediates: true });
 
    // For now, we'll use the bundle path directly on iOS
    return destDir;
 
  } catch (error) {
    return null;
  }
  */
}
 
/**
 * Get the path to bundled models (iOS bundle or Android assets)
 */
function getBundledModelPath(voice: PiperVoice): string | null {
  if (Platform.OS === 'ios') {
    // On iOS, assets are in the main bundle
    const bundlePath = NativeModules.RNFSManager?.MainBundlePath || '';
    if (!bundlePath) {
      // Try to construct path from FileSystem
      // Models should be copied during pod install or prebuild
      return null;
    }
    return `${bundlePath}/assets/tts-models/${voice.modelDir}`;
  } else if (Platform.OS === 'android') {
    // On Android, assets are extracted to files dir
    return `${getDocumentDirectory()}tts-models/${voice.modelDir}`;
  }
  return null;
}
 
/**
 * Initialize Sherpa TTS with a specific voice model
 */
export async function initializeSherpaTTS(voice?: PiperVoice): Promise<boolean> {
  if (!NATIVE_MODULE_AVAILABLE) {
    updateState({
      initialized: false,
      error: 'Native module not available - use native build'
    });
    return false;
  }
 
  if (currentState.initializing) {
    return false;
  }
 
  const selectedVoice = voice || currentState.currentVoice;
  updateState({ initializing: true, error: null });
 
  try {
 
    // Get model paths
    // For native build, models should be in the app bundle
    // We use Paths.bundle on iOS, Paths.document on Android
    let modelBasePath: string;
 
    if (Platform.OS === 'ios') {
      // iOS: Models are copied to bundle during build
      // Access via MainBundle
      const bundleDir = getBundleDirectory();
      const bundleExists = bundleDir && await fileExists(`${bundleDir}assets/tts-models/${selectedVoice.modelDir}/${selectedVoice.onnxFile}`);
      if (bundleExists) {
        modelBasePath = `${bundleDir}assets/tts-models/${selectedVoice.modelDir}`;
      } else {
        // Fallback: try document directory
        modelBasePath = `${getDocumentDirectory()}tts-models/${selectedVoice.modelDir}`;
      }
    } else {
      // Android: Extract from assets to document directory
      modelBasePath = `${getDocumentDirectory()}tts-models/${selectedVoice.modelDir}`;
    }
 
    // Check if model exists
    const modelPath = `${modelBasePath}/${selectedVoice.onnxFile}`;
    const tokensPath = `${modelBasePath}/tokens.txt`;
    const dataDirPath = `${modelBasePath}/espeak-ng-data`;
 
    // Create config JSON for native module
    const config = JSON.stringify({
      modelPath,
      tokensPath,
      dataDirPath,
    });
 
    // Initialize native TTS
    // Sample rate 22050, mono channel
    TTSManager.initializeTTS(22050, 1, config);
 
    updateState({
      initialized: true,
      initializing: false,
      currentVoice: selectedVoice,
      error: null
    });
 
    return true;
 
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    updateState({
      initialized: false,
      initializing: false,
      error: errorMessage
    });
    return false;
  }
}
 
/**
 * Speak text using Sherpa TTS
 */
export async function speak(
  text: string,
  options?: {
    speed?: number;
    speakerId?: number;
    onStart?: () => void;
    onDone?: () => void;
    onError?: (error: Error) => void;
  }
): Promise<void> {
  if (!NATIVE_MODULE_AVAILABLE || !currentState.initialized) {
    options?.onError?.(new Error('Sherpa TTS not initialized'));
    return;
  }
 
  const speed = options?.speed ?? 1.0;
  const speakerId = options?.speakerId ?? 0;
 
  try {
    options?.onStart?.();
 
    await TTSManager.generateAndPlay(text, speakerId, speed);
 
    options?.onDone?.();
  } catch (error) {
    const err = error instanceof Error ? error : new Error('TTS playback failed');
    options?.onError?.(err);
  }
}
 
/**
 * Stop current speech playback
 */
export function stop(): void {
  if (NATIVE_MODULE_AVAILABLE && currentState.initialized) {
    try {
      TTSManager.deinitialize();
      // Re-initialize after stop to be ready for next speech
      setTimeout(() => {
        if (currentState.currentVoice) {
          initializeSherpaTTS(currentState.currentVoice);
        }
      }, 100);
    } catch (error) {
      // Silently ignore stop errors
    }
  }
}
 
/**
 * Deinitialize and free resources
 */
export function deinitialize(): void {
  if (NATIVE_MODULE_AVAILABLE) {
    try {
      TTSManager.deinitialize();
    } catch (error) {
      // Silently ignore deinitialize errors
    }
  }
  updateState({ initialized: false, error: null });
}
 
/**
 * Check if Sherpa TTS is available (native module loaded)
 */
export function isAvailable(): boolean {
  return NATIVE_MODULE_AVAILABLE && currentState.initialized;
}
 
/**
 * Get current voice
 */
export function getCurrentVoice(): PiperVoice {
  return currentState.currentVoice;
}
 
/**
 * Set and switch to a different voice
 */
export async function setVoice(voiceId: string): Promise<boolean> {
  const voice = AVAILABLE_VOICES.find(v => v.id === voiceId);
  if (!voice) {
    return false;
  }
 
  // Deinitialize current and reinitialize with new voice
  deinitialize();
  return initializeSherpaTTS(voice);
}
 
/**
 * Add listener for volume updates during playback
 */
export function addVolumeListener(callback: (volume: number) => void): (() => void) | null {
  if (!ttsManagerEmitter) return null;
 
  const subscription = ttsManagerEmitter.addListener('VolumeUpdate', (event) => {
    callback(event.volume);
  });
 
  return () => subscription.remove();
}
 
/**
 * Load saved voice preference
 */
export async function loadSavedVoice(): Promise<PiperVoice> {
  // For now, just return default voice
  // Could add AsyncStorage persistence later
  return AVAILABLE_VOICES[0];
}
 
export default {
  initialize: initializeSherpaTTS,
  speak,
  stop,
  deinitialize,
  isAvailable,
  addStateListener,
  getState,
  getVoices: () => AVAILABLE_VOICES,
  getCurrentVoice,
  setVoice,
  loadSavedVoice,
  addVolumeListener,
};