Instructions to use augustZheng/TTS-Core-AI with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Supertonic
How to use augustZheng/TTS-Core-AI with Supertonic:
from supertonic import TTS tts = TTS(auto_download=True) style = tts.get_voice_style(voice_name="M1") text = "The train delay was announced at 4:45 PM on Wed, Apr 3, 2024 due to track maintenance." wav, duration = tts.synthesize(text, voice_style=style) tts.save_audio(wav, "output.wav")
- Notebooks
- Google Colab
- Kaggle
Fix dynamic Kokoro profiles and Supertonic baseline lookup
Browse filesFiles changed (4)
123---license: mit---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140# TTS Core AI LabLocal iOS workbench for incrementally porting and profiling the split Kokoropipeline in Swift.The app integrates the official KittenTTS Swift package and Supertonic 3ONNX pipeline, and provides four modes:- KittenTTS: ONNX Runtime CPU, eight voices, configurable speed.- Kokoro: the existing 11-stage split Core AI pipeline.- Supertonic 3: four Core AI models, ten voices, configurable flow steps,44.1 kHz.- Compare: sequentially generates all three models for the same text, preservesPCM results for independent playback, and displays wall time, inferencetime, RTF, Core AI coverage, and speedup.KittenTTS downloads its Nano model and phonemizer assets on first use. Kokoroand Supertonic 3 use Core AI model assets hosted separately on Hugging Face:<https://huggingface.co/augustZheng/TTS-Core-AI>.## Model AssetsThe Xcode project expects these asset directories:- `TTSCoreAILab/Models`- `TTSCoreAILab/SupertonicResources`They are not committed to GitHub because the full asset bundle is about 4.2 GBand contains files larger than GitHub's regular 100 MB file limit.Download them from Hugging Face before building:```bash./scripts/download-assets.sh```The script uses `uv` to run the Hugging Face CLI without creating a projectvirtual environment.The current stage runs a fixed `Hi.` text-to-acoustic-feature chain:```textfixed token ids + attention mask-> ALBERT-> BERT projection-> fixed-length duration encoder-> duration head-> Swift duration/alignment calculation-> text encoder CNN + LSTM-> Swift ASR alignment-> F0/noise shared LSTM + residual blocks```Bundled assets:- `kokoro_bert_eager_64.aimodel`- `kokoro_bert_projection.aimodel`- `kokoro_duration_encoder_no_pack_64_intmask.aimodel`- `kokoro_duration_head.aimodel`- `kokoro_text_encoder_conv_64_intmask.aimodel`- `kokoro_text_encoder_lstm.aimodel`- `kokoro_f0n_shared_lstm_64.aimodel`- `kokoro_f0n_blocks_64.aimodel`## How to Try1. Open `TTSCoreAILab.xcodeproj` in Xcode.2. Select the same physical iPhone target that passed the original smoke test.3. Run the `TTSCoreAILab` app target.4. Tap `Run Acoustic Stage`.Expected reference result from the Python CoreAI runtime:- shapes: `[1,64,768]`, `[1,512,64]`, `[1,64,640]`, `[1,64,50]`- valid-token durations: `[18, 2, 5, 9, 6, 1]`- raw predicted frames: `41`- fixed target frames: `64`- aligned ASR: `[1, 512, 64]`- F0: `[1, 128]`- noise: `[1, 128]`Python CoreAI reference mean-absolute values:- shared features: `0.35923`- F0: `72.4452`- noise: `6.59444`- text conv: `0.02399`- text hidden: `0.16430`- aligned ASR: `0.18732`The current build now also includes:- `kokoro_decoder_pre.aimodel`- `kokoro_generator_core.aimodel`- `kokoro_istft.aimodel`- fixed `Hi.` decoder style and harmonic-source fixtures- Swift PCM-to-WAV playback through `AVAudioPlayer`The current UI mirrors the browser Local Lab:- editable text and `af_heart` voice selection;- selectable bundled Core AI budgets (`64 / 64`, `128 / 256`, and `256 / 512`), with automatic profile escalation for longer segments;- optional automatic segmentation;- total time, Core AI inference time, audio duration, and RTF;- per-stage Core AI timing bars;- generated audio playback controls and a detailed run log.The PyTorch reference and native Kokoro comparison controls are visible butdisabled because those runtimes are not bundled in the iOS app.The bundled profiles increase the text/frame budget from `64 / 64` to`128 / 256` and `256 / 512`; automatic mode chooses the smallest profile thatfits a segment. Supertonic ships its validated `64 / 32` baseline assets under`SupertonicResources/coreai-assets-baseline`.Tap `Generate Locally`. A successful run should play generated audio and report:- generator input: `[1, 512, 128]`- spec/phase: `[1, 22, 7681]`- audio: `[1, 1, 38400]`- audio mean absolute value: approximately `0.01756`- audio min/max: approximately `-0.2076 / 0.3555`- ## RTF ResultThe current benchmark on iPhone 17 Pro.**RTF (Real-Time Factor)** measures how long it takes to generate one second of audio.- **RTF < 1.0** → Faster than real time (suitable for interactive TTS)- **Lower is better**The benchmark below compares the same prompt on the same device across different runtimes.<p align="center"><img src="docs/images/rtf-result.png" width="900"></p>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466// !$*UTF8*$!{ archiveVersion = 1; classes = { }; objectVersion = 56; objects = {
/* Begin PBXBuildFile section */ A10000000000000000000001 /* TTSCoreAILabApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000011 /* TTSCoreAILabApp.swift */; }; A10000000000000000000002 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000012 /* ContentView.swift */; }; A10000000000000000000003 /* CoreAIModelSmokeRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000013 /* CoreAIModelSmokeRunner.swift */; }; A10000000000000000000004 /* Models/kokoro_bert_projection.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000015 /* Models/kokoro_bert_projection.aimodel */; }; A10000000000000000000005 /* HiFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000016 /* HiFixture.swift */; }; A10000000000000000000006 /* Models/kokoro_bert_eager_64.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000017 /* Models/kokoro_bert_eager_64.aimodel */; }; A10000000000000000000007 /* Models/kokoro_duration_encoder_no_pack_64_intmask.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000018 /* Models/kokoro_duration_encoder_no_pack_64_intmask.aimodel */; }; A10000000000000000000008 /* Models/kokoro_duration_head.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000019 /* Models/kokoro_duration_head.aimodel */; }; A10000000000000000000009 /* Models/kokoro_text_encoder_conv_64_intmask.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000001A /* Models/kokoro_text_encoder_conv_64_intmask.aimodel */; }; A1000000000000000000000A /* Models/kokoro_text_encoder_lstm.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000001B /* Models/kokoro_text_encoder_lstm.aimodel */; }; A1000000000000000000000B /* Models/kokoro_f0n_shared_lstm_64.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000001C /* Models/kokoro_f0n_shared_lstm_64.aimodel */; }; A1000000000000000000000C /* Models/kokoro_f0n_blocks_64.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000001D /* Models/kokoro_f0n_blocks_64.aimodel */; }; A1000000000000000000000D /* AudioPlayback.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000001E /* AudioPlayback.swift */; }; A1000000000000000000000E /* Models/kokoro_decoder_pre.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000001F /* Models/kokoro_decoder_pre.aimodel */; }; A1000000000000000000000F /* Models/kokoro_generator_core.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000021 /* Models/kokoro_generator_core.aimodel */; }; A10000000000000000000022 /* Models/kokoro_istft.aimodel in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000023 /* Models/kokoro_istft.aimodel */; }; A10000000000000000000024 /* Models/hi_decoder_style.f32 in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000025 /* Models/hi_decoder_style.f32 */; }; A10000000000000000000026 /* Models/hi_harmonic_features.f32 in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000027 /* Models/hi_harmonic_features.f32 */; }; A10000000000000000000028 /* Models/LongDemo in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000029 /* Models/LongDemo */; }; A1000000000000000000002A /* LongDemoFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000002B /* LongDemoFixture.swift */; }; A1000000000000000000002C /* DynamicTextPipeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000002D /* DynamicTextPipeline.swift */; }; A1000000000000000000002E /* Models/DynamicText in Resources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000002F /* Models/DynamicText */; }; A10000000000000000000035 /* PlainTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000036 /* PlainTextView.swift */; }; A10000000000000000000037 /* Models/Profiles/128x256 in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000038 /* Models/Profiles/128x256 */; }; A10000000000000000000094 /* Models/Profiles/256x512 in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000095 /* Models/Profiles/256x512 */; }; A10000000000000000000039 /* UnifiedTTSLabRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000003A /* UnifiedTTSLabRunner.swift */; }; A1000000000000000000003B /* KittenTTS in Frameworks */ = {isa = PBXBuildFile; productRef = A1000000000000000000003D /* KittenTTS */; }; A10000000000000000000080 /* SupertonicTTSService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000081 /* SupertonicTTSService.swift */; }; A10000000000000000000084 /* coreai-assets in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000085 /* coreai-assets */; }; A10000000000000000000086 /* voice_styles in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000087 /* voice_styles */; }; A1000000000000000000008B /* unicode_indexer.json in Resources */ = {isa = PBXBuildFile; fileRef = A1000000000000000000008C /* unicode_indexer.json */; }; A10000000000000000000090 /* KokoroCoreMLService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000091 /* KokoroCoreMLService.swift */; }; A10000000000000000000092 /* Models/KokoroCoreML in Resources */ = {isa = PBXBuildFile; fileRef = A10000000000000000000093 /* Models/KokoroCoreML */; };/* End PBXBuildFile section */
/* Begin PBXFileReference section */ A10000000000000000000010 /* TTSCoreAILab.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TTSCoreAILab.app; sourceTree = BUILT_PRODUCTS_DIR; }; A10000000000000000000011 /* TTSCoreAILabApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TTSCoreAILabApp.swift; sourceTree = "<group>"; }; A10000000000000000000012 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; }; A10000000000000000000013 /* CoreAIModelSmokeRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreAIModelSmokeRunner.swift; sourceTree = "<group>"; }; A10000000000000000000014 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; A10000000000000000000015 /* Models/kokoro_bert_projection.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_bert_projection.aimodel; sourceTree = "<group>"; }; A10000000000000000000016 /* HiFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HiFixture.swift; sourceTree = "<group>"; }; A10000000000000000000017 /* Models/kokoro_bert_eager_64.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_bert_eager_64.aimodel; sourceTree = "<group>"; }; A10000000000000000000018 /* Models/kokoro_duration_encoder_no_pack_64_intmask.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_duration_encoder_no_pack_64_intmask.aimodel; sourceTree = "<group>"; }; A10000000000000000000019 /* Models/kokoro_duration_head.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_duration_head.aimodel; sourceTree = "<group>"; }; A1000000000000000000001A /* Models/kokoro_text_encoder_conv_64_intmask.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_text_encoder_conv_64_intmask.aimodel; sourceTree = "<group>"; }; A1000000000000000000001B /* Models/kokoro_text_encoder_lstm.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_text_encoder_lstm.aimodel; sourceTree = "<group>"; }; A1000000000000000000001C /* Models/kokoro_f0n_shared_lstm_64.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_f0n_shared_lstm_64.aimodel; sourceTree = "<group>"; }; A1000000000000000000001D /* Models/kokoro_f0n_blocks_64.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_f0n_blocks_64.aimodel; sourceTree = "<group>"; }; A1000000000000000000001E /* AudioPlayback.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioPlayback.swift; sourceTree = "<group>"; }; A1000000000000000000001F /* Models/kokoro_decoder_pre.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_decoder_pre.aimodel; sourceTree = "<group>"; }; A10000000000000000000021 /* Models/kokoro_generator_core.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_generator_core.aimodel; sourceTree = "<group>"; }; A10000000000000000000023 /* Models/kokoro_istft.aimodel */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/kokoro_istft.aimodel; sourceTree = "<group>"; }; A10000000000000000000025 /* Models/hi_decoder_style.f32 */ = {isa = PBXFileReference; lastKnownFileType = file; path = Models/hi_decoder_style.f32; sourceTree = "<group>"; }; A10000000000000000000027 /* Models/hi_harmonic_features.f32 */ = {isa = PBXFileReference; lastKnownFileType = file; path = Models/hi_harmonic_features.f32; sourceTree = "<group>"; }; A10000000000000000000029 /* Models/LongDemo */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/LongDemo; sourceTree = "<group>"; }; A1000000000000000000002B /* LongDemoFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LongDemoFixture.swift; sourceTree = "<group>"; }; A1000000000000000000002D /* DynamicTextPipeline.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DynamicTextPipeline.swift; sourceTree = "<group>"; }; A1000000000000000000002F /* Models/DynamicText */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/DynamicText; sourceTree = "<group>"; }; A10000000000000000000036 /* PlainTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlainTextView.swift; sourceTree = "<group>"; }; A10000000000000000000038 /* Models/Profiles/128x256 */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/Profiles/128x256; sourceTree = "<group>"; }; A10000000000000000000095 /* Models/Profiles/256x512 */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/Profiles/256x512; sourceTree = "<group>"; }; A1000000000000000000003A /* UnifiedTTSLabRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnifiedTTSLabRunner.swift; sourceTree = "<group>"; }; A10000000000000000000081 /* SupertonicTTSService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SupertonicTTSService.swift; sourceTree = "<group>"; }; A10000000000000000000085 /* coreai-assets */ = {isa = PBXFileReference; lastKnownFileType = folder; name = "coreai-assets"; path = "SupertonicResources/coreai-assets-baseline"; sourceTree = "<group>"; }; A10000000000000000000087 /* voice_styles */ = {isa = PBXFileReference; lastKnownFileType = folder; name = voice_styles; path = SupertonicResources/voice_styles; sourceTree = "<group>"; }; A1000000000000000000008C /* unicode_indexer.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; name = unicode_indexer.json; path = SupertonicResources/unicode_indexer.json; sourceTree = "<group>"; }; A10000000000000000000091 /* KokoroCoreMLService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KokoroCoreMLService.swift; sourceTree = "<group>"; }; A10000000000000000000093 /* Models/KokoroCoreML */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Models/KokoroCoreML; sourceTree = "<group>"; };/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */ A10000000000000000000020 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( A1000000000000000000003B /* KittenTTS in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; };/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */ A10000000000000000000030 = { isa = PBXGroup; children = ( A10000000000000000000031 /* TTSCoreAILab */, A10000000000000000000032 /* Products */, ); sourceTree = "<group>"; }; A10000000000000000000031 /* TTSCoreAILab */ = { isa = PBXGroup; children = ( A10000000000000000000011 /* TTSCoreAILabApp.swift */, A10000000000000000000012 /* ContentView.swift */, A10000000000000000000036 /* PlainTextView.swift */, A10000000000000000000013 /* CoreAIModelSmokeRunner.swift */, A1000000000000000000003A /* UnifiedTTSLabRunner.swift */, A10000000000000000000081 /* SupertonicTTSService.swift */, A10000000000000000000091 /* KokoroCoreMLService.swift */, A10000000000000000000016 /* HiFixture.swift */, A1000000000000000000002B /* LongDemoFixture.swift */, A1000000000000000000002D /* DynamicTextPipeline.swift */, A1000000000000000000001E /* AudioPlayback.swift */, A10000000000000000000014 /* Info.plist */, A10000000000000000000015 /* Models/kokoro_bert_projection.aimodel */, A10000000000000000000017 /* Models/kokoro_bert_eager_64.aimodel */, A10000000000000000000018 /* Models/kokoro_duration_encoder_no_pack_64_intmask.aimodel */, A10000000000000000000019 /* Models/kokoro_duration_head.aimodel */, A1000000000000000000001A /* Models/kokoro_text_encoder_conv_64_intmask.aimodel */, A1000000000000000000001B /* Models/kokoro_text_encoder_lstm.aimodel */, A1000000000000000000001C /* Models/kokoro_f0n_shared_lstm_64.aimodel */, A1000000000000000000001D /* Models/kokoro_f0n_blocks_64.aimodel */, A1000000000000000000001F /* Models/kokoro_decoder_pre.aimodel */, A10000000000000000000021 /* Models/kokoro_generator_core.aimodel */, A10000000000000000000023 /* Models/kokoro_istft.aimodel */, A10000000000000000000025 /* Models/hi_decoder_style.f32 */, A10000000000000000000027 /* Models/hi_harmonic_features.f32 */, A10000000000000000000029 /* Models/LongDemo */, A1000000000000000000002F /* Models/DynamicText */, A10000000000000000000038 /* Models/Profiles/128x256 */, A10000000000000000000095 /* Models/Profiles/256x512 */, A10000000000000000000093 /* Models/KokoroCoreML */, A10000000000000000000085 /* coreai-assets */, A10000000000000000000087 /* voice_styles */, A1000000000000000000008C /* unicode_indexer.json */, ); path = TTSCoreAILab; sourceTree = "<group>"; }; A10000000000000000000032 /* Products */ = { isa = PBXGroup; children = ( A10000000000000000000010 /* TTSCoreAILab.app */, ); name = Products; sourceTree = "<group>"; };/* End PBXGroup section */
/* Begin PBXNativeTarget section */ A10000000000000000000040 /* TTSCoreAILab */ = { isa = PBXNativeTarget; buildConfigurationList = A10000000000000000000070 /* Build configuration list for PBXNativeTarget "TTSCoreAILab" */; buildPhases = ( A10000000000000000000050 /* Sources */, A10000000000000000000020 /* Frameworks */, A10000000000000000000051 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = TTSCoreAILab; packageProductDependencies = ( A1000000000000000000003D /* KittenTTS */, ); productName = TTSCoreAILab; productReference = A10000000000000000000010 /* TTSCoreAILab.app */; productType = "com.apple.product-type.application"; };/* End PBXNativeTarget section */
/* Begin PBXProject section */ A10000000000000000000060 /* Project object */ = { isa = PBXProject; attributes = { BuildIndependentTargetsInParallel = 1; LastSwiftUpdateCheck = 1600; LastUpgradeCheck = 2700; TargetAttributes = { A10000000000000000000040 = { CreatedOnToolsVersion = 16.0; }; }; }; buildConfigurationList = A10000000000000000000061 /* Build configuration list for PBXProject "TTSCoreAILab" */; compatibilityVersion = "Xcode 14.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = A10000000000000000000030; packageReferences = ( A1000000000000000000003C /* XCRemoteSwiftPackageReference "KittenTTS-swift" */, ); productRefGroup = A10000000000000000000032 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( A10000000000000000000040 /* TTSCoreAILab */, ); };/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */ A10000000000000000000051 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( A10000000000000000000004 /* Models/kokoro_bert_projection.aimodel in Resources */, A10000000000000000000006 /* Models/kokoro_bert_eager_64.aimodel in Resources */, A10000000000000000000007 /* Models/kokoro_duration_encoder_no_pack_64_intmask.aimodel in Resources */, A10000000000000000000008 /* Models/kokoro_duration_head.aimodel in Resources */, A10000000000000000000009 /* Models/kokoro_text_encoder_conv_64_intmask.aimodel in Resources */, A1000000000000000000000A /* Models/kokoro_text_encoder_lstm.aimodel in Resources */, A1000000000000000000000B /* Models/kokoro_f0n_shared_lstm_64.aimodel in Resources */, A1000000000000000000000C /* Models/kokoro_f0n_blocks_64.aimodel in Resources */, A1000000000000000000000E /* Models/kokoro_decoder_pre.aimodel in Resources */, A1000000000000000000000F /* Models/kokoro_generator_core.aimodel in Resources */, A10000000000000000000022 /* Models/kokoro_istft.aimodel in Resources */, A10000000000000000000024 /* Models/hi_decoder_style.f32 in Resources */, A10000000000000000000026 /* Models/hi_harmonic_features.f32 in Resources */, A10000000000000000000028 /* Models/LongDemo in Resources */, A1000000000000000000002E /* Models/DynamicText in Resources */, A10000000000000000000037 /* Models/Profiles/128x256 in Resources */, A10000000000000000000094 /* Models/Profiles/256x512 in Resources */, A10000000000000000000084 /* coreai-assets in Resources */, A10000000000000000000086 /* voice_styles in Resources */, A1000000000000000000008B /* unicode_indexer.json in Resources */, ); runOnlyForDeploymentPostprocessing = 0; };/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */ A10000000000000000000050 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( A10000000000000000000001 /* TTSCoreAILabApp.swift in Sources */, A10000000000000000000002 /* ContentView.swift in Sources */, A10000000000000000000003 /* CoreAIModelSmokeRunner.swift in Sources */, A10000000000000000000005 /* HiFixture.swift in Sources */, A1000000000000000000000D /* AudioPlayback.swift in Sources */, A1000000000000000000002A /* LongDemoFixture.swift in Sources */, A1000000000000000000002C /* DynamicTextPipeline.swift in Sources */, A10000000000000000000035 /* PlainTextView.swift in Sources */, A10000000000000000000039 /* UnifiedTTSLabRunner.swift in Sources */, A10000000000000000000080 /* SupertonicTTSService.swift in Sources */, A10000000000000000000090 /* KokoroCoreMLService.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; };/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */ A10000000000000000000062 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu17; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 27.0; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; STRING_CATALOG_GENERATE_SYMBOLS = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; A10000000000000000000063 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES; GCC_C_LANGUAGE_STANDARD = gnu17; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 27.0; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = iphoneos; STRING_CATALOG_GENERATE_SYMBOLS = YES; SWIFT_COMPILATION_MODE = wholemodule; VALIDATE_PRODUCT = YES; }; name = Release; }; A10000000000000000000071 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = NO; INFOPLIST_FILE = TTSCoreAILab/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = com.coreai.TTSCoreAILab; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_VERSION = 6.0; TARGETED_DEVICE_FAMILY = 1; }; name = Debug; }; A10000000000000000000072 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = NO; INFOPLIST_FILE = TTSCoreAILab/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.coreai.TTSCoreAILab; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_VERSION = 6.0; TARGETED_DEVICE_FAMILY = 1; }; name = Release; };/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */ A10000000000000000000061 /* Build configuration list for PBXProject "TTSCoreAILab" */ = { isa = XCConfigurationList; buildConfigurations = ( A10000000000000000000062 /* Debug */, A10000000000000000000063 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; A10000000000000000000070 /* Build configuration list for PBXNativeTarget "TTSCoreAILab" */ = { isa = XCConfigurationList; buildConfigurations = ( A10000000000000000000071 /* Debug */, A10000000000000000000072 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */ A1000000000000000000003C /* XCRemoteSwiftPackageReference "KittenTTS-swift" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/KittenML/KittenTTS-swift.git"; requirement = { kind = revision; revision = 20cd4d8784c1bad348326955709892c8dfe7226b; }; };/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */ A1000000000000000000003D /* KittenTTS */ = { isa = XCSwiftPackageProductDependency; package = A1000000000000000000003C /* XCRemoteSwiftPackageReference "KittenTTS-swift" */; productName = KittenTTS; };/* End XCSwiftPackageProductDependency section */ }; rootObject = A10000000000000000000060 /* Project object */;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137import Foundation
#if canImport(CoreAI)import CoreAI#endif
struct LabStageTiming: Identifiable, Sendable { let name: String let seconds: Double var id: String { name }}
struct LabRunReport: Sendable { let totalSeconds: Double let coreAISeconds: Double let audioSeconds: Double let segmentCount: Int let stages: [LabStageTiming] let summary: String let samples: [Float] let sampleRate: Int
var realTimeFactor: Double { audioSeconds > 0 ? totalSeconds / audioSeconds : 0 }}
struct CoreAIProfile: Sendable { static let dynamicID = "dynamic"
let id: String let tokenBudget: Int let frameBudget: Int let assetDirectory: String? let tokenStageProfileID: String? let frameStageProfileID: String? let names: [String: String]
static let compact = CoreAIProfile( id: "64x64", tokenBudget: 64, frameBudget: 64, assetDirectory: nil, tokenStageProfileID: nil, frameStageProfileID: nil, names: [ "bert": "kokoro_bert_eager_64", "projection": "kokoro_bert_projection", "durationEncoder": "kokoro_duration_encoder_no_pack_64_intmask", "durationHead": "kokoro_duration_head", "f0Shared": "kokoro_f0n_shared_lstm_64", "f0Blocks": "kokoro_f0n_blocks_64", "textConv": "kokoro_text_encoder_conv_64_intmask", "textLSTM": "kokoro_text_encoder_lstm", "decoder": "kokoro_decoder_pre", "generator": "kokoro_generator_core", "istft": "kokoro_istft", ] )
static let large = CoreAIProfile( id: "128x256", tokenBudget: 128, frameBudget: 256, assetDirectory: "128x256", tokenStageProfileID: nil, frameStageProfileID: nil, names: [ "bert": "kokoro_bert_eager", "projection": "kokoro_bert_projection", "durationEncoder": "kokoro_duration_encoder", "durationHead": "kokoro_duration_head", "f0Shared": "kokoro_f0n_shared_lstm", "f0Blocks": "kokoro_f0n_blocks", "textConv": "kokoro_text_encoder_conv", "textLSTM": "kokoro_text_encoder_lstm", "decoder": "kokoro_decoder_pre", "generator": "kokoro_generator_core", "istft": "kokoro_istft", ] )
static let frame512 = CoreAIProfile( id: "256x512", tokenBudget: 256, frameBudget: 512, assetDirectory: "256x512", tokenStageProfileID: nil, frameStageProfileID: nil, names: [ "bert": "kokoro_bert_eager", "projection": "kokoro_bert_projection", "durationEncoder": "kokoro_duration_encoder", "durationHead": "kokoro_duration_head", "f0Shared": "kokoro_f0n_shared_lstm", "f0Blocks": "kokoro_f0n_blocks", "textConv": "kokoro_text_encoder_conv", "textLSTM": "kokoro_text_encoder_lstm", "decoder": "kokoro_decoder_pre", "generator": "kokoro_generator_core", "istft": "kokoro_istft", ] )
static let hybrid128x512 = CoreAIProfile( id: "128x512-hybrid", tokenBudget: 128, frameBudget: 512, assetDirectory: nil, tokenStageProfileID: "128x256", frameStageProfileID: "256x512", names: [ "bert": "kokoro_bert_eager", "projection": "kokoro_bert_projection", "durationEncoder": "kokoro_duration_encoder", "durationHead": "kokoro_duration_head", "f0Shared": "kokoro_f0n_shared_lstm", "f0Blocks": "kokoro_f0n_blocks", "textConv": "kokoro_text_encoder_conv", "textLSTM": "kokoro_text_encoder_lstm", "decoder": "kokoro_decoder_pre", "generator": "kokoro_generator_core", "istft": "kokoro_istft", ] )
static func profile(id: String) -> CoreAIProfile { switch id { case large.id: large case frame512.id: frame512 case hybrid128x512.id: hybrid128x512 default: compact } }
static func autoCandidates(for validTokenLength: Int) -> [CoreAIProfile] { if validTokenLength <= compact.tokenBudget { return [.compact, .large, .frame512] } if validTokenLength <= large.tokenBudget { return [.large, .frame512] } if validTokenLength <= frame512.tokenBudget { return [.frame512] } return [] }}
enum CoreAIModelSmokeError: Error, CustomStringConvertible { case assetMissing(String) case functionMissing(String) case inputMissing(String) case outputMissing(String) case unsupportedScalarType(String) case invalidFixture(String) case unsupportedText(String) case segmentTooLong(text: String, frames: Int)
var description: String { switch self { case .assetMissing(let name): return "Bundled asset missing: \(name)" case .functionMissing(let asset): return "Cannot load Core AI function main from \(asset)" case .inputMissing(let name): return "Input descriptor missing: \(name)" case .outputMissing(let name): return "Output missing: \(name)" case .unsupportedScalarType(let message): return message case .invalidFixture(let message): return message case .unsupportedText(let text): return "Text is not prepared yet: \(text)" case .segmentTooLong(let text, let frames): return "Segment is too long (\(frames) frames): \(text)" } }}
actor CoreAIModelSmokeRunner { static let shared = CoreAIModelSmokeRunner()
#if canImport(CoreAI) private var stageSeconds: [String: Double] = [:] private var loadedFunctions: [String: LoadedFunction] = [:]
private struct LoadedFunction { let model: AIModel let function: InferenceFunction }
private struct SegmentResult { let text: String let phonemes: String let validTokenLength: Int let durations: [Int] let rawFrameCount: Int let samples: [Float] let meanAbs: Float } #endif
func run() async throws -> String { #if canImport(CoreAI) loadedFunctions.removeAll(keepingCapacity: false) defer { loadedFunctions.removeAll(keepingCapacity: false) } let decoderStyle = try loadFloatFixture(name: "hi_decoder_style", count: 128) let result = try await synthesize(HiFixture().segment(decoderStyle: decoderStyle)) try await AudioPlayback.shared.play(samples: result.samples, sampleRate: 24_000) return """ Core AI TTS passed and played.
text: \(result.text) phonemes: \(result.phonemes) valid tokens: \(result.validTokenLength)/64 durations: \(result.durations) predicted frames: \(result.rawFrameCount) audio samples: \(result.samples.count) audio meanAbs: \(result.meanAbs) """ #else return "This SDK does not expose the CoreAI Swift module." #endif }
func runText( _ text: String, progress: @escaping @MainActor @Sendable (String) -> Void ) async throws -> String { (try await runLab(text, progress: progress)).summary }
func runLab( _ text: String, profileID: String = "64x64", autoSplit: Bool = true, playAudio: Bool = true, progress: @escaping @MainActor @Sendable (String) -> Void ) async throws -> LabRunReport { #if canImport(CoreAI) stageSeconds = [:] loadedFunctions.removeAll(keepingCapacity: false) defer { loadedFunctions.removeAll(keepingCapacity: false) } let totalStart = ContinuousClock.now let isDynamic = profileID == CoreAIProfile.dynamicID let requestedProfile = CoreAIProfile.profile(id: profileID) let planningProfile = isDynamic ? CoreAIProfile.frame512 : requestedProfile let pipeline = try DynamicTextPipeline() let selectedSegments = try pipeline.makeSegments( text: text, tokenBudget: planningProfile.tokenBudget, segmentTokenLimit: isDynamic ? planningProfile.tokenBudget - 2 : (planningProfile.frameBudget == 64 ? 20 : planningProfile.tokenBudget - 2), autoSplit: autoSplit ) var pendingSegments = selectedSegments var combined: [Float] = [] var summaries: [String] = [] var completedTexts: [String] = [] var index = 0
while index < pendingSegments.count { let segment = pendingSegments[index] let candidateProfiles: [CoreAIProfile] if isDynamic { candidateProfiles = CoreAIProfile.autoCandidates(for: segment.validTokenLength) } else { candidateProfiles = [requestedProfile] }
var selectedResult: SegmentResult? var selectedProfile: CoreAIProfile? var finalOverflow: CoreAIModelSmokeError?
for (candidateIndex, candidate) in candidateProfiles.enumerated() { let candidateSegment: TTSegmentFixture if segment.inputIds.count == candidate.tokenBudget { candidateSegment = segment } else { guard let rebuilt = try pipeline.makeSegments( text: segment.text, tokenBudget: candidate.tokenBudget, autoSplit: false ).first else { throw CoreAIModelSmokeError.unsupportedText(segment.text) } candidateSegment = rebuilt }
await progress( "Generating \(index + 1) of \(pendingSegments.count) with \(candidate.id)\n" + "\(candidateSegment.validTokenLength) tokens · \(candidateSegment.text)" ) do { selectedResult = try await synthesize( candidateSegment, profile: candidate, progress: progress ) selectedProfile = candidate break } catch let error as CoreAIModelSmokeError { guard case .segmentTooLong(_, let frames) = error else { throw error } finalOverflow = error if candidateIndex + 1 < candidateProfiles.count { let next = candidateProfiles[candidateIndex + 1] await progress( "\(candidate.id) predicted \(frames) frames.\n" + "Upgrading this segment to \(next.id)…" ) } } }
guard let result = selectedResult, let profile = selectedProfile else { guard autoSplit else { throw finalOverflow ?? CoreAIModelSmokeError.unsupportedText(segment.text) } let split = try pipeline.splitForFrameOverflow(segment.text) let replacements = try split.flatMap { try pipeline.makeSegments( text: $0, tokenBudget: planningProfile.tokenBudget, autoSplit: false ) } pendingSegments.replaceSubrange(index...index, with: replacements) await progress( "Predicted duration exceeded \(planningProfile.frameBudget) frames.\n" + "Split into \(pendingSegments.count) segments and retrying…" ) continue } let samplesPerFrame = 600 let predictedSamples = max(1, result.rawFrameCount) * samplesPerFrame let audibleSamples = min(result.samples.count, predictedSamples) let trimmedTailSamples = max(0, result.samples.count - audibleSamples) var audible = Array(result.samples.prefix(audibleSamples)) applyFadeOut(to: &audible, count: min(240, audible.count)) appendSmoothly( audible, after: completedTexts.last, to: &combined, sampleRate: 24_000 ) summaries.append( "\(index + 1). \(result.text)\n" + " \(result.validTokenLength)/\(profile.tokenBudget) tokens · " + "\(result.rawFrameCount)/\(profile.frameBudget) frames · \(profile.id)\n" + " audio \(String(format: "%.2f", Double(audibleSamples) / 24_000))s · " + "trimmed tail \(String(format: "%.2f", Double(trimmedTailSamples) / 24_000))s" ) completedTexts.append(result.text) loadedFunctions.removeAll(keepingCapacity: false) index += 1 }
if playAudio { await progress("Playing \(pendingSegments.count) generated segments...") try await AudioPlayback.shared.play(samples: combined, sampleRate: 24_000) } let totalSeconds = durationSeconds(since: totalStart) let coreAISeconds = stageSeconds.values.reduce(0, +) let audioSeconds = Double(combined.count) / 24_000 let summary = """ Long Core AI TTS passed and played.
\(text)
\(summaries.joined(separator: "\n"))
total audio: \(String(format: "%.1f", Double(combined.count) / 24_000)) seconds samples: \(combined.count) """ let stages = stageSeconds .map { LabStageTiming(name: $0.key, seconds: $0.value) } .sorted { $0.seconds > $1.seconds } return LabRunReport( totalSeconds: totalSeconds, coreAISeconds: coreAISeconds, audioSeconds: audioSeconds, segmentCount: pendingSegments.count, stages: stages, summary: summary, samples: combined, sampleRate: 24_000 ) #else return LabRunReport( totalSeconds: 0, coreAISeconds: 0, audioSeconds: 0, segmentCount: 0, stages: [], summary: "This SDK does not expose the CoreAI Swift module.", samples: [], sampleRate: 24_000 ) #endif }
#if canImport(CoreAI) private func stageProfile(for stage: String, profile: CoreAIProfile) -> CoreAIProfile { guard let tokenProfileID = profile.tokenStageProfileID, let frameProfileID = profile.frameStageProfileID else { return profile } let tokenStages: Set<String> = [ "bert", "projection", "durationEncoder", "durationHead", "textConv", "textLSTM", ] return CoreAIProfile.profile(id: tokenStages.contains(stage) ? tokenProfileID : frameProfileID) }
private func synthesize( _ fixture: TTSegmentFixture, profile: CoreAIProfile = .compact, progress: @escaping @MainActor @Sendable (String) -> Void = { _ in } ) async throws -> SegmentResult { let tokenCount = profile.tokenBudget let frameCount = profile.frameBudget guard fixture.inputIds.count == tokenCount, fixture.attentionMask.count == tokenCount, fixture.textMask.count == tokenCount, fixture.prosodyStyle.count == 128 else { throw CoreAIModelSmokeError.invalidFixture("Hi fixture has invalid tensor sizes") }
await progress("Loading and running BERT…") let bertHidden = try await withFunction(asset: profile.names["bert"]!, profile: stageProfile(for: "bert", profile: profile)) { function in let inputIds = try makeInt32Input( descriptor: function.descriptor, name: "input_ids", values: fixture.inputIds ) let attentionMask = try makeInt32Input( descriptor: function.descriptor, name: "attention_mask", values: fixture.attentionMask ) return try await run( function, inputs: ["input_ids": inputIds, "attention_mask": attentionMask], output: "bert_hidden", stage: "kokoro_bert_eager" ) }
let dEn = try await withFunction(asset: profile.names["projection"]!, profile: stageProfile(for: "projection", profile: profile)) { function in try await run( function, inputs: ["bert_hidden": bertHidden], output: "d_en", stage: "kokoro_bert_projection" ) }
await progress("Predicting phoneme durations…") let durationFeatures = try await withFunction( asset: profile.names["durationEncoder"]!, profile: stageProfile(for: "durationEncoder", profile: profile) ) { function in let style = try makeFloat32Input( descriptor: function.descriptor, name: "style", values: fixture.prosodyStyle ) let textMask = try makeInt32Input( descriptor: function.descriptor, name: "text_mask", values: fixture.textMask ) return try await run( function, inputs: ["d_en": dEn, "style": style, "text_mask": textMask], output: "d", stage: "kokoro_duration_encoder" ) }
let durationLogits = try await withFunction( asset: profile.names["durationHead"]!, profile: stageProfile(for: "durationHead", profile: profile) ) { function in try await run( function, inputs: ["d": durationFeatures], output: "duration_logits", stage: "kokoro_duration_head" ) }
let durations = predictedDurations( logits: durationLogits, tokenCount: tokenCount, binsPerToken: 50, validTokenLength: fixture.validTokenLength ) let rawFrameCount = durations.reduce(0, +) guard rawFrameCount <= frameCount else { throw CoreAIModelSmokeError.segmentTooLong( text: fixture.text, frames: rawFrameCount ) } let alignment = fixedAlignment( durations: durations, tokenCount: tokenCount, frameCount: frameCount )
let durationFeatureValues = flattenFloat32(durationFeatures) let enValues = projectTokenFeaturesToFrames( tokenFeatures: durationFeatureValues, tokenCount: tokenCount, featureCount: 640, alignment: alignment.values, frameCount: frameCount )
await progress("Generating pitch and noise curves…") let sharedFeatures = try await withFunction( asset: profile.names["f0Shared"]!, profile: stageProfile(for: "f0Shared", profile: profile) ) { function in let en = try makeFloat32Input( descriptor: function.descriptor, name: "en", values: enValues ) return try await run( function, inputs: ["en": en], output: "shared_features", stage: "kokoro_f0n_shared_lstm" ) }
let f0Noise = try await withFunction( asset: profile.names["f0Blocks"]!, profile: stageProfile(for: "f0Blocks", profile: profile) ) { function in let f0Style = try makeFloat32Input( descriptor: function.descriptor, name: "style", values: fixture.prosodyStyle ) return try await runAll( function, inputs: ["shared_features": sharedFeatures, "style": f0Style], outputs: ["f0", "noise"], stage: "kokoro_f0n_blocks" ) } guard let f0 = f0Noise["f0"], let noise = f0Noise["noise"] else { throw CoreAIModelSmokeError.outputMissing("f0/noise") }
await progress("Encoding text features…") let convFeatures = try await withFunction( asset: profile.names["textConv"]!, profile: stageProfile(for: "textConv", profile: profile) ) { function in let textInputIds = try makeInt32Input( descriptor: function.descriptor, name: "input_ids", values: fixture.inputIds ) let textInputMask = try makeInt32Input( descriptor: function.descriptor, name: "text_mask", values: fixture.textMask ) return try await run( function, inputs: ["input_ids": textInputIds, "text_mask": textInputMask], output: "conv_features", stage: "kokoro_text_encoder_conv" ) }
let textHidden = try await withFunction( asset: profile.names["textLSTM"]!, profile: stageProfile(for: "textLSTM", profile: profile) ) { function in try await run( function, inputs: ["conv_features": convFeatures], output: "asr", stage: "kokoro_text_encoder_lstm" ) } let asrValues = projectChannelTokensToFrames( channelTokens: flattenFloat32(textHidden), channelCount: 512, tokenCount: tokenCount, alignment: alignment.values, frameCount: frameCount )
let f0Stats = summarize(f0) let noiseStats = summarize(noise) let asrStats = summarize(asrValues) let decoderStyle = fixture.decoderStyle let harmonicFeatures: [Float] if let harmonicResource = fixture.harmonicResource { harmonicFeatures = try loadFloatFixture( name: harmonicResource, count: 22 * 7681 ) } else { await progress("Building harmonic source features…") harmonicFeatures = try HarmonicSourceGenerator().makeFeatures( f0: flattenFloat32(f0), frameBudget: frameCount ) }
await progress("Running decoder pre-stage…") let generatorInput = try await withFunction( asset: profile.names["decoder"]!, profile: stageProfile(for: "decoder", profile: profile) ) { function in let decoderASR = try makeFloat32Input( descriptor: function.descriptor, name: "asr", values: asrValues ) let decoderStyleInput = try makeFloat32Input( descriptor: function.descriptor, name: "style", values: decoderStyle ) return try await run( function, inputs: [ "asr": decoderASR, "f0_curve": f0, "noise": noise, "style": decoderStyleInput, ], output: "generator_input", stage: "kokoro_decoder_pre" ) }
await progress("Running generator core… This is the slowest stage.") let specPhase = try await withFunction( asset: profile.names["generator"]!, profile: stageProfile(for: "generator", profile: profile) ) { function in let generatorStyle = try makeFloat32Input( descriptor: function.descriptor, name: "style", values: decoderStyle ) let harmonicInput = try makeFloat32Input( descriptor: function.descriptor, name: "harmonic_features", values: harmonicFeatures ) return try await run( function, inputs: [ "x": generatorInput, "style": generatorStyle, "harmonic_features": harmonicInput, ], output: "spec_phase", stage: "kokoro_generator_core" ) }
await progress("Reconstructing waveform…") let audio = try await withFunction(asset: profile.names["istft"]!, profile: stageProfile(for: "istft", profile: profile)) { function in try await run( function, inputs: ["spec_phase": specPhase], output: "audio", stage: "kokoro_istft" ) } let audioValues = flattenFloat32(audio) let audioStats = summarize(audioValues) _ = (f0Stats, noiseStats, asrStats, generatorInput, specPhase, alignment)
return SegmentResult( text: fixture.text, phonemes: fixture.phonemes, validTokenLength: fixture.validTokenLength, durations: durations, rawFrameCount: rawFrameCount, samples: audioValues, meanAbs: audioStats.meanAbs ) }
private func appendSmoothly( _ segment: [Float], after previousText: String?, to combined: inout [Float], sampleRate: Int ) { guard !combined.isEmpty, let previousText else { combined.append(contentsOf: segment) return }
let trimmed = segment let punctuation = previousText.trimmingCharacters(in: .whitespacesAndNewlines).last let pauseSeconds: Double switch punctuation { case ".", "!", "?": pauseSeconds = 0.16 case ",", ";", ":": pauseSeconds = 0.08 default: pauseSeconds = 0 }
if pauseSeconds > 0 { applyFadeOut(to: &combined, count: min(240, combined.count)) combined.append(contentsOf: repeatElement(0, count: Int(Double(sampleRate) * pauseSeconds))) var faded = trimmed applyFadeIn(to: &faded, count: min(240, faded.count)) combined.append(contentsOf: faded) return }
let overlap = min(Int(Double(sampleRate) * 0.035), combined.count, trimmed.count) guard overlap > 0 else { combined.append(contentsOf: trimmed) return } let start = combined.count - overlap for index in 0..<overlap { let incoming = Float(index + 1) / Float(overlap + 1) let outgoing = 1 - incoming combined[start + index] = combined[start + index] * outgoing + trimmed[index] * incoming } combined.append(contentsOf: trimmed.dropFirst(overlap)) }
private func trimQuietEdges( _ samples: [Float], threshold: Float, guardSamples: Int ) -> [Float] { guard let first = samples.firstIndex(where: { abs($0) >= threshold }), let last = samples.lastIndex(where: { abs($0) >= threshold }) else { return samples } let start = max(0, first - guardSamples) let end = min(samples.count - 1, last + guardSamples) return Array(samples[start...end]) }
private func applyFadeIn(to samples: inout [Float], count: Int) { guard count > 0 else { return } for index in 0..<count { samples[index] *= Float(index + 1) / Float(count) } }
private func applyFadeOut(to samples: inout [Float], count: Int) { guard count > 0 else { return } let start = samples.count - count for index in 0..<count { samples[start + index] *= Float(count - index) / Float(count) } }
private func loadFunction( asset: String, profile: CoreAIProfile = .compact ) async throws -> LoadedFunction { let cacheKey = "\(profile.id)/\(asset)" if let loaded = loadedFunctions[cacheKey] { return loaded }
let modelURL = modelURL(for: asset, profile: profile) guard let modelURL else { throw CoreAIModelSmokeError.assetMissing("\(asset).aimodel") } let options = SpecializationOptions(preferredComputeUnitKind: .gpu) let model = try await AIModel(contentsOf: modelURL, options: options) guard let function = try model.loadFunction(named: "main") else { throw CoreAIModelSmokeError.functionMissing(asset) } let loaded = LoadedFunction(model: model, function: function) loadedFunctions[cacheKey] = loaded return loaded }
private func modelURL(for asset: String, profile: CoreAIProfile) -> URL? { var subdirectories: [String?] = [nil, "Models"] if let assetDirectory = profile.assetDirectory { subdirectories = [ assetDirectory, "Profiles/\(assetDirectory)", "Models/Profiles/\(assetDirectory)", nil, "Models", ] }
for subdirectory in subdirectories { if let url = Bundle.main.url( forResource: asset, withExtension: "aimodel", subdirectory: subdirectory ) { return url } } return recursivelyFindModel( named: "\(asset).aimodel", preferredDirectory: profile.assetDirectory ) }
private func recursivelyFindModel( named modelDirectory: String, preferredDirectory: String? ) -> URL? { guard let resourceURL = Bundle.main.resourceURL, let enumerator = FileManager.default.enumerator( at: resourceURL, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles] ) else { return nil }
var fallbackURL: URL? for case let url as URL in enumerator { guard url.lastPathComponent == modelDirectory else { continue } let resourceValues = try? url.resourceValues(forKeys: [.isDirectoryKey]) guard resourceValues?.isDirectory == true else { continue } if let preferredDirectory { let components = Set(url.pathComponents) if components.contains(preferredDirectory) { return url } continue } else if fallbackURL == nil { fallbackURL = url } } return fallbackURL }
private func withFunction<T>( asset: String, profile: CoreAIProfile = .compact, operation: (InferenceFunction) async throws -> T ) async throws -> T { let loaded = try await loadFunction(asset: asset, profile: profile) defer { loadedFunctions.removeValue(forKey: "\(profile.id)/\(asset)") } return try await operation(loaded.function) }
private func run( _ function: InferenceFunction, inputs: [String: NDArray], output outputName: String, stage: String? = nil ) async throws -> NDArray { let start = ContinuousClock.now var outputs = try await function.run(inputs: inputs) if let stage { stageSeconds[stage, default: 0] += durationSeconds(since: start) } guard let output = outputs.remove(outputName)?.ndArray else { throw CoreAIModelSmokeError.outputMissing(outputName) } return output }
private func runAll( _ function: InferenceFunction, inputs: [String: NDArray], outputs outputNames: [String], stage: String? = nil ) async throws -> [String: NDArray] { let start = ContinuousClock.now var rawOutputs = try await function.run(inputs: inputs) if let stage { stageSeconds[stage, default: 0] += durationSeconds(since: start) } var result: [String: NDArray] = [:] for name in outputNames { guard let output = rawOutputs.remove(name)?.ndArray else { throw CoreAIModelSmokeError.outputMissing(name) } result[name] = output } return result }
private func makeInt32Input( descriptor: InferenceFunctionDescriptor, name: String, values: [Int32] ) throws -> NDArray { guard case .ndArray(let inputDescriptor) = descriptor.inputDescriptor(of: name) else { throw CoreAIModelSmokeError.inputMissing(name) } guard inputDescriptor.scalarType == .int32 else { throw CoreAIModelSmokeError.unsupportedScalarType( "Expected int32 input for \(name), got \(inputDescriptor.scalarType)" ) } var array = NDArray(descriptor: inputDescriptor) var view = array.mutableView(as: Int32.self) view.copyElements(fromContentsOf: values) return array }
private func makeFloat32Input( descriptor: InferenceFunctionDescriptor, name: String, values: [Float] ) throws -> NDArray { guard case .ndArray(let inputDescriptor) = descriptor.inputDescriptor(of: name) else { throw CoreAIModelSmokeError.inputMissing(name) } guard inputDescriptor.scalarType == .float32 else { throw CoreAIModelSmokeError.unsupportedScalarType( "Expected float32 input for \(name), got \(inputDescriptor.scalarType)" ) } var array = NDArray(descriptor: inputDescriptor) var view = array.mutableView(as: Float.self) view.copyElements(fromContentsOf: values) return array }
private func loadFloatFixture(name: String, count: Int) throws -> [Float] { guard let url = Bundle.main.url(forResource: name, withExtension: "f32") ?? Bundle.main.url( forResource: name, withExtension: "f32", subdirectory: "LongDemo" ) else { throw CoreAIModelSmokeError.assetMissing("\(name).f32") } let data = try Data(contentsOf: url) guard data.count == count * MemoryLayout<Float>.size else { throw CoreAIModelSmokeError.invalidFixture( "\(name).f32 has \(data.count) bytes; expected \(count * MemoryLayout<Float>.size)" ) } return data.withUnsafeBytes { rawBuffer in Array(rawBuffer.bindMemory(to: Float.self)) } }
private func predictedDurations( logits: NDArray, tokenCount: Int, binsPerToken: Int, validTokenLength: Int ) -> [Int] { precondition(logits.scalarType == .float32) var durations = [Int]() durations.reserveCapacity(validTokenLength)
logits.view(as: Float.self).withUnsafePointer { pointer, shape, strides in precondition(shape.count == 3) precondition(shape[0] == 1) precondition(shape[1] == tokenCount) precondition(shape[2] == binsPerToken) for token in 0..<validTokenLength { var sum: Float = 0 for bin in 0..<binsPerToken { let offset = token * strides[1] + bin * strides[2] let value = pointer[offset] sum += 1 / (1 + exp(-value)) } durations.append(max(1, Int(sum.rounded()))) } } return durations }
private func fixedAlignment( durations: [Int], tokenCount: Int, frameCount: Int ) -> (values: [Float], frameCount: Int, paddedFrames: Int, truncatedFrames: Int) { let predictedFrames = durations.reduce(0, +) var tokenForFrame: [Int] = [] for (token, duration) in durations.enumerated() { tokenForFrame.append(contentsOf: repeatElement(token, count: duration)) } if tokenForFrame.isEmpty { tokenForFrame = [0] } tokenForFrame = Array(tokenForFrame.prefix(frameCount))
var values = [Float](repeating: 0, count: tokenCount * frameCount) for frame in 0..<tokenForFrame.count { values[tokenForFrame[frame] * frameCount + frame] = 1 } return ( values, frameCount, max(0, frameCount - predictedFrames), max(0, predictedFrames - frameCount) ) }
private func projectTokenFeaturesToFrames( tokenFeatures: [Float], tokenCount: Int, featureCount: Int, alignment: [Float], frameCount: Int ) -> [Float] { var output = [Float](repeating: 0, count: featureCount * frameCount) for token in 0..<tokenCount { for frame in 0..<frameCount where alignment[token * frameCount + frame] != 0 { for feature in 0..<featureCount { output[feature * frameCount + frame] = tokenFeatures[token * featureCount + feature] } } } return output }
private func projectChannelTokensToFrames( channelTokens: [Float], channelCount: Int, tokenCount: Int, alignment: [Float], frameCount: Int ) -> [Float] { var output = [Float](repeating: 0, count: channelCount * frameCount) for channel in 0..<channelCount { for token in 0..<tokenCount { let value = channelTokens[channel * tokenCount + token] for frame in 0..<frameCount where alignment[token * frameCount + frame] != 0 { output[channel * frameCount + frame] = value } } } return output }
private func flattenFloat32(_ array: NDArray) -> [Float] { precondition(array.scalarType == .float32) let outerShape = array.shape let rank = outerShape.count let total = outerShape.reduce(1, *) var result = [Float](repeating: 0, count: total)
array.view(as: Float.self).withUnsafePointer { pointer, shape, strides in var indices = [Int](repeating: 0, count: rank) for outputIndex in 0..<total { var offset = 0 for dimension in 0..<rank { offset += indices[dimension] * strides[dimension] } result[outputIndex] = pointer[offset]
var dimension = rank - 1 while dimension >= 0 { indices[dimension] += 1 if indices[dimension] < shape[dimension] { break } indices[dimension] = 0 dimension -= 1 } } } return result }
private func summarize(_ array: NDArray) -> (min: Float, max: Float, meanAbs: Float) { summarize(flattenFloat32(array)) }
private func summarize(_ values: [Float]) -> (min: Float, max: Float, meanAbs: Float) { guard let first = values.first else { return (0, 0, 0) } var minValue = first var maxValue = first var sumAbs: Float = 0 for value in values { minValue = min(minValue, value) maxValue = max(maxValue, value) sumAbs += abs(value) } return (minValue, maxValue, sumAbs / Float(values.count)) }
private func durationSeconds(since start: ContinuousClock.Instant) -> Double { let duration = start.duration(to: .now) return Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1_000_000_000_000_000_000 } #endif}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873import Foundation
#if canImport(CoreAI)import CoreAI#endif
struct SupertonicOutput: Sendable { let samples: [Float] let sampleRate: Int let inferenceSeconds: Double let profileID: String}
actor SupertonicTTSService { enum Voice: String, CaseIterable, Identifiable, Sendable { case m1 = "M1", m2 = "M2", m3 = "M3", m4 = "M4", m5 = "M5" case f1 = "F1", f2 = "F2", f3 = "F3", f4 = "F4", f5 = "F5"
var id: String { rawValue } var title: String { rawValue } }
private struct VoiceStyleData: Decodable { struct Component: Decodable { let data: [[[Float]]] }
let style_ttl: Component let style_dp: Component }
private struct TextSegment { let text: String let pauseAfter: Float let syntheticEnding: Character? }
private struct Profile: Sendable { static let dynamicID = "dynamic"
let id: String let textBudget: Int let latentBudget: Int
var audioWindowSeconds: Float { Float(latentBudget * 512 * 6) / 44_100 }
func asset(_ name: String) -> String { "supertonic_\(name)_\(id)" }
static let compact = Profile(id: "64x32", textBudget: 64, latentBudget: 32) static let large = Profile(id: "128x64", textBudget: 128, latentBudget: 64) static let wide = Profile(id: "128x128", textBudget: 128, latentBudget: 128) static let kokoroLarge = Profile(id: "128x256", textBudget: 128, latentBudget: 256) }
private struct SegmentRender { let samples: [Float] let pauseAfter: Float let profileID: String }
#if canImport(CoreAI) private struct DurationPrediction { let duration: Float let activeLatents: Int } #endif
private let unicodeIndexer: [Int32] private let sampleRate = 44_100 private let latentChannels = 144 private let latentChunkSamples = 512 * 6 #if canImport(CoreAI) private var loadedModels: [String: LoadedModel] = [:]
private struct LoadedModel { let model: AIModel let function: InferenceFunction } #endif
init() throws { guard let url = Bundle.main.url( forResource: "unicode_indexer", withExtension: "json" ) else { throw NSError( domain: "Supertonic", code: 1, userInfo: [NSLocalizedDescriptionKey: "Missing unicode_indexer.json."] ) } unicodeIndexer = try JSONDecoder().decode( [Int32].self, from: Data(contentsOf: url) ) }
private func profile(id: String, availableProfiles: [Profile]) -> Profile { availableProfiles.first { $0.id == id } ?? .compact }
private func availableProfiles() -> [Profile] { var profiles: [Profile] = [.compact] for profile in [Profile.large, .wide, .kokoroLarge] { if hasAllAssets(for: profile) { profiles.append(profile) } } return profiles }
private func hasAllAssets(for profile: Profile) -> Bool { [ "duration_predictor", "text_encoder", "vector_estimator", "vocoder", ].allSatisfy { hasAsset(profile.asset($0)) } }
private func hasAsset(_ asset: String) -> Bool { let resourceURL = Bundle.main.resourceURL let candidates = [ Bundle.main.url( forResource: asset, withExtension: "aimodel", subdirectory: "coreai-assets" ), Bundle.main.url( forResource: asset, withExtension: "aimodel", subdirectory: "coreai-assets-baseline" ), Bundle.main.url(forResource: asset, withExtension: "aimodel"), resourceURL? .appendingPathComponent("coreai-assets", isDirectory: true) .appendingPathComponent("\(asset).aimodel", isDirectory: true), resourceURL? .appendingPathComponent("coreai-assets-baseline", isDirectory: true) .appendingPathComponent("\(asset).aimodel", isDirectory: true), resourceURL? .appendingPathComponent("\(asset).aimodel", isDirectory: true), ] return candidates.compactMap { $0 }.contains { FileManager.default.fileExists(atPath: $0.path) } }
func generate( _ text: String, voice: Voice, steps: Int, speed: Float, profileID: String = Profile.dynamicID ) async throws -> SupertonicOutput { #if canImport(CoreAI) let clock = ContinuousClock() let start = clock.now let style = try loadStyle(voice) let availableProfiles = availableProfiles() let requestedProfile = profile( id: profileID, availableProfiles: availableProfiles ) let planningProfile = profileID == Profile.dynamicID ? (availableProfiles.last ?? .compact) : requestedProfile var pendingSegments = makeTextSegments(text, profile: planningProfile) guard !pendingSegments.isEmpty else { throw NSError( domain: "Supertonic", code: 11, userInfo: [NSLocalizedDescriptionKey: "Enter text to synthesize."] ) } var renderedSegments: [SegmentRender] = []
while !pendingSegments.isEmpty { let segment = pendingSegments.removeFirst() let textScalarCount = processedScalarCount(segment) let durationProfile: Profile? if profileID == Profile.dynamicID { durationProfile = smallestTextProfile( for: textScalarCount, availableProfiles: availableProfiles ) } else if textScalarCount <= requestedProfile.textBudget { durationProfile = requestedProfile } else { durationProfile = nil }
if let durationProfile { let prediction = try await predictDuration( segment, style: style, speed: speed, profile: durationProfile ) let renderProfile: Profile? if profileID == Profile.dynamicID { renderProfile = smallestRenderProfile( textScalarCount: textScalarCount, activeLatents: prediction.activeLatents, availableProfiles: availableProfiles ) } else if prediction.activeLatents <= requestedProfile.latentBudget { renderProfile = requestedProfile } else { renderProfile = nil }
if let renderProfile { let samples = try await renderSegment( segment, style: style, steps: steps, profile: renderProfile, duration: prediction.duration, activeLatents: prediction.activeLatents ) renderedSegments.append( SegmentRender( samples: samples, pauseAfter: segment.pauseAfter, profileID: profileSummary( durationProfile: durationProfile, renderProfile: renderProfile ) ) ) continue } }
guard let split = splitSegment(segment) else { let maxProfile = profileID == Profile.dynamicID ? (availableProfiles.last ?? requestedProfile) : requestedProfile throw NSError( domain: "Supertonic", code: 2, userInfo: [ NSLocalizedDescriptionKey: "A single segment exceeds " + "\(maxProfile.textBudget) text units or " + "\(String(format: "%.2f", maxProfile.audioWindowSeconds))s " + "Core AI segment profile." ] ) } pendingSegments.insert(split.right, at: 0) pendingSegments.insert(split.left, at: 0) }
var samples: [Float] = [] for (index, segment) in renderedSegments.enumerated() { samples.append(contentsOf: segment.samples) if index < renderedSegments.count - 1 { samples.append( contentsOf: repeatElement( 0, count: Int(segment.pauseAfter * Float(sampleRate)) ) ) } } return SupertonicOutput( samples: samples, sampleRate: sampleRate, inferenceSeconds: Self.seconds(from: start, to: clock.now), profileID: usedProfileSummary(renderedSegments) ) #else throw NSError( domain: "Supertonic", code: 3, userInfo: [NSLocalizedDescriptionKey: "Core AI is unavailable."] ) #endif }
private func loadStyle(_ voice: Voice) throws -> (ttl: [Float], dp: [Float]) { let candidates = [ Bundle.main.url( forResource: voice.rawValue, withExtension: "json", subdirectory: "voice_styles" ), Bundle.main.url(forResource: voice.rawValue, withExtension: "json"), ] guard let url = candidates.compactMap({ $0 }).first else { throw NSError( domain: "Supertonic", code: 4, userInfo: [NSLocalizedDescriptionKey: "Missing \(voice.rawValue).json."] ) } let decoded = try JSONDecoder().decode( VoiceStyleData.self, from: Data(contentsOf: url) ) return ( decoded.style_ttl.data.flatMap { $0.flatMap { $0 } }, decoded.style_dp.data.flatMap { $0.flatMap { $0 } } ) }
#if canImport(CoreAI) private func predictDuration( _ segment: TextSegment, style: (ttl: [Float], dp: [Float]), speed: Float, profile: Profile ) async throws -> DurationPrediction { let (textIDs, textMask) = try makeTextInputs(segment, profile: profile) let durationArray = try await runModel( asset: profile.asset("duration_predictor"), inputs: [ "text_ids": .int32(textIDs), "style_dp": .float32(style.dp), "text_mask": .float32(textMask), ], output: "duration" ) let duration = flattenFloat32(durationArray)[0] / max(0.5, min(2, speed)) let activeLatents = Int( ceil(duration * Float(sampleRate) / Float(latentChunkSamples)) ) return DurationPrediction(duration: duration, activeLatents: activeLatents) }
private func renderSegment( _ segment: TextSegment, style: (ttl: [Float], dp: [Float]), steps: Int, profile: Profile, duration: Float, activeLatents: Int ) async throws -> [Float] { let (textIDs, textMask) = try makeTextInputs(segment, profile: profile) let textEmbedding = try await runModel( asset: profile.asset("text_encoder"), inputs: [ "text_ids": .int32(textIDs), "style_ttl": .float32(style.ttl), "text_mask": .float32(textMask), ], output: "text_emb" )
var latentMask = [Float](repeating: 0, count: profile.latentBudget) for index in 0..<activeLatents { latentMask[index] = 1 } var latent = gaussianValues(count: latentChannels * profile.latentBudget) for channel in 0..<latentChannels { for frame in activeLatents..<profile.latentBudget { latent[channel * profile.latentBudget + frame] = 0 } }
let vectorModel = try await loadModel( asset: profile.asset("vector_estimator") ) let clampedSteps = max(2, min(15, steps)) for step in 0..<clampedSteps { latent = flattenFloat32( try await run( vectorModel.function, inputs: try makeInputs( descriptor: vectorModel.function.descriptor, values: [ "noisy_latent": .float32(latent), "text_emb": .array(textEmbedding), "style_ttl": .float32(style.ttl), "latent_mask": .float32(latentMask), "text_mask": .float32(textMask), "current_step": .float32([Float(step)]), "total_step": .float32([Float(clampedSteps)]), ] ), output: "denoised_latent" ) ) }
let waveform = flattenFloat32( try await runModel( asset: profile.asset("vocoder"), inputs: ["latent": .float32(latent)], output: "wav_tts" ) ) let sampleCount = min( waveform.count, Int(duration * Float(sampleRate)) ) return Array(waveform.prefix(sampleCount)) } #endif
private func makeTextInputs(_ segment: TextSegment, profile: Profile) throws -> ([Int32], [Float]) { var text = normalizeText(segment.text) if let last = text.last, !".!?;:,'\")]}…".contains(last) { text.append(segment.syntheticEnding ?? ".") } text = "<en>\(text)</en>" let scalars = Array(text.unicodeScalars) guard scalars.count <= profile.textBudget else { throw NSError( domain: "Supertonic", code: 5, userInfo: [ NSLocalizedDescriptionKey: "Processed segment uses \(scalars.count) characters; " + "the current Core AI profile supports \(profile.textBudget)." ] ) } var ids = [Int32](repeating: 0, count: profile.textBudget) var mask = [Float](repeating: 0, count: profile.textBudget) for (index, scalar) in scalars.enumerated() { let value = Int(scalar.value) ids[index] = value < unicodeIndexer.count ? unicodeIndexer[value] : -1 mask[index] = 1 } return (ids, mask) }
private func processedScalarCount(_ segment: TextSegment) -> Int { var text = normalizeText(segment.text) if let last = text.last, !".!?;:,'\")]}…".contains(last) { text.append(segment.syntheticEnding ?? ".") } return "<en>\(text)</en>".unicodeScalars.count }
private func smallestTextProfile( for textScalarCount: Int, availableProfiles: [Profile] ) -> Profile? { availableProfiles .sorted { $0.textBudget < $1.textBudget } .first { textScalarCount <= $0.textBudget } }
private func smallestRenderProfile( textScalarCount: Int, activeLatents: Int, availableProfiles: [Profile] ) -> Profile? { availableProfiles .sorted { if $0.latentBudget == $1.latentBudget { return $0.textBudget < $1.textBudget } return $0.latentBudget < $1.latentBudget } .first { textScalarCount <= $0.textBudget && activeLatents <= $0.latentBudget } }
private func profileSummary(durationProfile: Profile, renderProfile: Profile) -> String { durationProfile.id == renderProfile.id ? renderProfile.id : "\(durationProfile.id)->\(renderProfile.id)" }
private func usedProfileSummary(_ segments: [SegmentRender]) -> String { let ids = segments.map(\.profileID) let uniqueIDs = Array(Set(ids)).sorted() guard !uniqueIDs.isEmpty else { return Profile.compact.id } if uniqueIDs.count == 1 { return uniqueIDs[0] } return uniqueIDs.joined(separator: "+") }
private func normalizeText(_ source: String) -> String { var text = source.decomposedStringWithCompatibilityMapping let replacements: [String: String] = [ "–": "-", "‑": "-", "—": "-", "_": " ", "“": "\"", "”": "\"", "‘": "'", "’": "'", "[": " ", "]": " ", "|": " ", "/": " ", "#": " ", "@": " at ", ] for (old, new) in replacements { text = text.replacingOccurrences(of: old, with: new) } text = text .split(whereSeparator: { $0.isWhitespace }) .joined(separator: " ") .trimmingCharacters(in: .whitespacesAndNewlines) return text }
private func makeTextSegments(_ source: String, profile: Profile) -> [TextSegment] { let text = normalizeText(source) guard !text.isEmpty else { return [] }
// The language tags occupy 9 of the fixed Unicode-scalar slots. let contentBudget = profile.textBudget - 9 var segments: [TextSegment] = [] var current = ""
for word in sentenceAwareWords(text) { let candidate = current.isEmpty ? word : "\(current) \(word)" if candidate.unicodeScalars.count <= contentBudget { current = candidate if let last = word.last, ".!?".contains(last) { segments.append( TextSegment( text: current, pauseAfter: pauseDuration(after: last), syntheticEnding: nil ) ) current = "" } else if let last = word.last, ",;:".contains(last), current.unicodeScalars.count >= 18 { segments.append( TextSegment( text: current, pauseAfter: pauseDuration(after: last), syntheticEnding: nil ) ) current = "" } continue }
if !current.isEmpty { segments.append( TextSegment( text: current, pauseAfter: 0.06, syntheticEnding: "," ) ) current = "" } var remaining = word while remaining.unicodeScalars.count > contentBudget { let splitIndex = remaining.unicodeScalars.index( remaining.unicodeScalars.startIndex, offsetBy: contentBudget ) segments.append( TextSegment( text: String(remaining.unicodeScalars[..<splitIndex]), pauseAfter: 0.06, syntheticEnding: "," ) ) remaining = String(remaining.unicodeScalars[splitIndex...]) } current = remaining if let last = current.last, ".!?;:,".contains(last) { segments.append( TextSegment( text: current, pauseAfter: pauseDuration(after: last), syntheticEnding: nil ) ) current = "" } } if !current.isEmpty { segments.append( TextSegment( text: current, pauseAfter: 0.12, syntheticEnding: "." ) ) } return segments }
private func splitSegment( _ segment: TextSegment ) -> (left: TextSegment, right: TextSegment)? { let words = segment.text.split(separator: " ").map(String.init) guard words.count > 1 else { return nil }
let splitIndex = naturalSplitIndex(words) let leftText = words[..<splitIndex].joined(separator: " ") let rightText = words[splitIndex...].joined(separator: " ") return ( TextSegment( text: leftText, pauseAfter: pauseAfterSplit(leftText), syntheticEnding: syntheticEnding(for: leftText, fallback: ",") ), TextSegment( text: rightText, pauseAfter: segment.pauseAfter, syntheticEnding: segment.syntheticEnding ) ) }
private func naturalSplitIndex(_ words: [String]) -> Int { let target = words.joined(separator: " ").unicodeScalars.count / 2 var bestIndex: Int? var bestScore = Int.max var runningCount = 0
for index in 0..<(words.count - 1) { let word = words[index] runningCount += word.unicodeScalars.count + (index == 0 ? 0 : 1) guard let last = word.last else { continue }
let priority: Int if ".!?".contains(last) { priority = 0 } else if ";:".contains(last) { priority = 1 } else if ",".contains(last) { priority = 2 } else { continue }
let distance = abs(runningCount - target) let score = distance * 4 + priority if score < bestScore { bestScore = score bestIndex = index + 1 } }
if let bestIndex { return bestIndex }
runningCount = 0 var leftWords = 0 for word in words.dropLast() { let added = word.unicodeScalars.count + (leftWords == 0 ? 0 : 1) if leftWords > 0, runningCount + added > target { break } runningCount += added leftWords += 1 } return max(1, leftWords) }
private func syntheticEnding(for text: String, fallback: Character) -> Character? { guard let last = text.last else { return fallback } return ".!?;:,'\")]}…".contains(last) ? nil : fallback }
private func pauseAfterSplit(_ text: String) -> Float { guard let last = text.last else { return 0.06 } return ".!?;:,".contains(last) ? pauseDuration(after: last) : 0.06 }
private func sentenceAwareWords(_ text: String) -> [String] { var spaced = "" let characters = Array(text) for index in characters.indices { let character = characters[index] spaced.append(character) guard ".!?;:,".contains(character), index + 1 < characters.count, !characters[index + 1].isWhitespace else { continue } let isDecimalPoint = character == "." && index > 0 && characters[index - 1].isNumber && characters[index + 1].isNumber if !isDecimalPoint { spaced.append(" ") } } return spaced.split(whereSeparator: { $0.isWhitespace }).map(String.init) }
private func pauseDuration(after punctuation: Character) -> Float { switch punctuation { case ".", "!", "?": return 0.38 case ";", ":": return 0.24 case ",": return 0.16 default: return 0.10 } }
private func gaussianValues(count: Int) -> [Float] { var values = [Float]() values.reserveCapacity(count) while values.count < count { let u1 = Float.random(in: 0.0001...1) let u2 = Float.random(in: 0...1) let radius = sqrt(-2 * log(u1)) values.append(radius * cos(2 * .pi * u2)) if values.count < count { values.append(radius * sin(2 * .pi * u2)) } } return values }
#if canImport(CoreAI) private enum InputValue { case int32([Int32]) case float32([Float]) case array(NDArray) }
private func loadModel( asset: String ) async throws -> LoadedModel { if let loaded = loadedModels[asset] { return loaded }
let resourceURL = Bundle.main.resourceURL let candidates = [ Bundle.main.url( forResource: asset, withExtension: "aimodel", subdirectory: "coreai-assets" ), Bundle.main.url( forResource: asset, withExtension: "aimodel", subdirectory: "coreai-assets-baseline" ), Bundle.main.url(forResource: asset, withExtension: "aimodel"), resourceURL? .appendingPathComponent("coreai-assets", isDirectory: true) .appendingPathComponent("\(asset).aimodel", isDirectory: true), resourceURL? .appendingPathComponent("coreai-assets-baseline", isDirectory: true) .appendingPathComponent("\(asset).aimodel", isDirectory: true), resourceURL? .appendingPathComponent("\(asset).aimodel", isDirectory: true), ] guard let url = candidates.compactMap({ $0 }).first(where: { FileManager.default.fileExists(atPath: $0.path) }) else { throw NSError( domain: "Supertonic", code: 6, userInfo: [NSLocalizedDescriptionKey: "Missing \(asset).aimodel."] ) } let options = SpecializationOptions(preferredComputeUnitKind: .gpu) let model = try await AIModel(contentsOf: url, options: options) guard let function = try model.loadFunction(named: "main") else { throw NSError( domain: "Supertonic", code: 7, userInfo: [NSLocalizedDescriptionKey: "Cannot load \(asset)."] ) } let loaded = LoadedModel(model: model, function: function) loadedModels[asset] = loaded return loaded }
private func runModel( asset: String, inputs: [String: InputValue], output: String ) async throws -> NDArray { let loaded = try await loadModel(asset: asset) return try await run( loaded.function, inputs: try makeInputs( descriptor: loaded.function.descriptor, values: inputs ), output: output ) }
private func makeInputs( descriptor: InferenceFunctionDescriptor, values: [String: InputValue] ) throws -> [String: NDArray] { var result: [String: NDArray] = [:] for (name, value) in values { switch value { case .array(let array): result[name] = array case .int32(let contents): guard case .ndArray(let input) = descriptor.inputDescriptor(of: name) else { throw NSError(domain: "Supertonic", code: 8) } var array = NDArray(descriptor: input) var view = array.mutableView(as: Int32.self) view.copyElements(fromContentsOf: contents) result[name] = array case .float32(let contents): guard case .ndArray(let input) = descriptor.inputDescriptor(of: name) else { throw NSError(domain: "Supertonic", code: 9) } var array = NDArray(descriptor: input) var view = array.mutableView(as: Float.self) view.copyElements(fromContentsOf: contents) result[name] = array } } return result }
private func run( _ function: InferenceFunction, inputs: [String: NDArray], output: String ) async throws -> NDArray { var outputs = try await function.run(inputs: inputs) guard let array = outputs.remove(output)?.ndArray else { throw NSError( domain: "Supertonic", code: 10, userInfo: [NSLocalizedDescriptionKey: "Missing output \(output)."] ) } return array }
private func flattenFloat32(_ array: NDArray) -> [Float] { let shape = array.shape let total = shape.reduce(1, *) var result = [Float](repeating: 0, count: total) array.view(as: Float.self).withUnsafePointer { pointer, actualShape, strides in var indices = [Int](repeating: 0, count: actualShape.count) for outputIndex in 0..<total { var offset = 0 for dimension in actualShape.indices { offset += indices[dimension] * strides[dimension] } result[outputIndex] = pointer[offset] for dimension in actualShape.indices.reversed() { indices[dimension] += 1 if indices[dimension] < actualShape[dimension] { break } indices[dimension] = 0 } } } return result } #endif
private static func seconds( from start: ContinuousClock.Instant, to end: ContinuousClock.Instant ) -> Double { let duration = start.duration(to: end) return Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1_000_000_000_000_000_000 }}README.md+140-3
TTSCoreAILab/TTSCoreAILab.xcodeproj/project.pbxprojAdded+466
TTSCoreAILab/TTSCoreAILab/CoreAIModelSmokeRunner.swiftAdded+1137
TTSCoreAILab/TTSCoreAILab/SupertonicTTSService.swiftAdded+873