Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

Add Intel (x86_64) architecture support for universal binary - Changed ARCHS from arm64-only to - Removed x86_64 from EXCLUDED_ARCHS - Added SwiftWhisper package dependency for Intel fallback - Updated signing configuration for release builds

altic-dev10dfb764e90e
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index 88e66426..cbb82a86 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -8,6 +8,7 @@
/* Begin PBXBuildFile section */
7C078DA52E3B386A00FB7CAC /* FluidAudio in Frameworks */ = {isa = PBXBuildFile; productRef = 7C078DA42E3B386A00FB7CAC /* FluidAudio */; };
+ 7C1C72F22EECBD1300E3BF4D /* SwiftWhisper in Frameworks */ = {isa = PBXBuildFile; productRef = 7C1C72F12EECBD1300E3BF4D /* SwiftWhisper */; };
7C3236542EAAD608007E4CB6 /* MCP in Frameworks */ = {isa = PBXBuildFile; productRef = 7C3236532EAAD608007E4CB6 /* MCP */; };
7C3697892ED70F9C005874CE /* DynamicNotchKit in Frameworks */ = {isa = PBXBuildFile; productRef = 7C3697882ED70F9C005874CE /* DynamicNotchKit */; };
7CE006BD2E80EBE600DDCCD6 /* AppUpdater in Frameworks */ = {isa = PBXBuildFile; productRef = 7CE006BC2E80EBE600DDCCD6 /* AppUpdater */; };
@@ -32,6 +33,7 @@
files = (
7C3697892ED70F9C005874CE /* DynamicNotchKit in Frameworks */,
7C3236542EAAD608007E4CB6 /* MCP in Frameworks */,
+ 7C1C72F22EECBD1300E3BF4D /* SwiftWhisper in Frameworks */,
7CE006BD2E80EBE600DDCCD6 /* AppUpdater in Frameworks */,
7C078DA52E3B386A00FB7CAC /* FluidAudio in Frameworks */,
);
@@ -79,6 +81,7 @@
7C3236532EAAD608007E4CB6 /* MCP */,
7C3697882ED70F9C005874CE /* DynamicNotchKit */,
7CE006BC2E80EBE600DDCCD6 /* AppUpdater */,
+ 7C1C72F12EECBD1300E3BF4D /* SwiftWhisper */,
);
productName = FluidVoice;
productReference = 7C078D8F2E3B339200FB7CAC /* FluidVoice Debug.app */;
@@ -113,6 +116,7 @@
7CE006BB2E80EBE600DDCCD6 /* XCRemoteSwiftPackageReference "AppUpdater" */,
7C3236522EAAD608007E4CB6 /* XCRemoteSwiftPackageReference "swift-sdk" */,
7C3697872ED70F9C005874CE /* XCRemoteSwiftPackageReference "DynamicNotchKit" */,
+ 7C1C72F02EECBD1300E3BF4D /* XCRemoteSwiftPackageReference "SwiftWhisper" */,
);
preferredProjectObjectVersion = 77;
productRefGroup = 7C078D902E3B339200FB7CAC /* Products */;
@@ -149,7 +153,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
- ARCHS = arm64;
+ ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
@@ -186,7 +190,7 @@
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
- EXCLUDED_ARCHS = x86_64;
+
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -216,7 +220,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
- ARCHS = arm64;
+ ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
@@ -253,7 +257,7 @@
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
- EXCLUDED_ARCHS = x86_64;
+
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
@@ -279,11 +283,11 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = Fluid.entitlements;
- "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
- CODE_SIGN_STYLE = Automatic;
+ CODE_SIGN_IDENTITY = "Developer ID Application: Barathwaj Anandan (V4J43B279J)";
+ CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
- DEVELOPMENT_TEAM = J67LH9U7BN;
+ DEVELOPMENT_TEAM = V4J43B279J;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
ENABLE_FILE_ACCESS_DOWNLOADS_FOLDER = readwrite;
@@ -300,7 +304,7 @@
ENABLE_RESOURCE_ACCESS_PRINTING = YES;
ENABLE_RESOURCE_ACCESS_USB = YES;
ENABLE_USER_SELECTED_FILES = readwrite;
- EXCLUDED_ARCHS = x86_64;
+
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";
@@ -311,9 +315,10 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 1.4.1;
+ MARKETING_VERSION = 1.5.1;
PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app;
PRODUCT_NAME = "FluidVoice Debug";
+ PROVISIONING_PROFILE_SPECIFIER = "";
REGISTER_APP_GROUPS = YES;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) ARCH_ARM64";
@@ -322,7 +327,7 @@
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
- VALID_ARCHS = arm64;
+ VALID_ARCHS = "$(ARCHS_STANDARD)";
};
name = Debug;
};
@@ -334,12 +339,10 @@
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = Fluid.entitlements;
CODE_SIGN_IDENTITY = "Developer ID Application: Barathwaj Anandan (V4J43B279J)";
- "CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = V4J43B279J;
- "DEVELOPMENT_TEAM[sdk=macosx*]" = J67LH9U7BN;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
ENABLE_FILE_ACCESS_DOWNLOADS_FOLDER = readwrite;
@@ -356,7 +359,7 @@
ENABLE_RESOURCE_ACCESS_PRINTING = YES;
ENABLE_RESOURCE_ACCESS_USB = YES;
ENABLE_USER_SELECTED_FILES = readwrite;
- EXCLUDED_ARCHS = x86_64;
+
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";
@@ -367,7 +370,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 1.4.1;
+ MARKETING_VERSION = 1.5.1;
PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app;
PRODUCT_NAME = FluidVoice;
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -379,7 +382,7 @@
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
SWIFT_VERSION = 5.0;
- VALID_ARCHS = arm64;
+ VALID_ARCHS = "$(ARCHS_STANDARD)";
};
name = Release;
};
@@ -415,6 +418,14 @@
minimumVersion = 0.7.4;
};
};
+ 7C1C72F02EECBD1300E3BF4D /* XCRemoteSwiftPackageReference "SwiftWhisper" */ = {
+ isa = XCRemoteSwiftPackageReference;
+ repositoryURL = "https://github.com/exPHAT/SwiftWhisper.git";
+ requirement = {
+ kind = upToNextMajorVersion;
+ minimumVersion = 1.2.0;
+ };
+ };
7C3236522EAAD608007E4CB6 /* XCRemoteSwiftPackageReference "swift-sdk" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/modelcontextprotocol/swift-sdk.git";
@@ -447,6 +458,11 @@
package = 7C078DA32E3B386A00FB7CAC /* XCRemoteSwiftPackageReference "FluidAudio" */;
productName = FluidAudio;
};
+ 7C1C72F12EECBD1300E3BF4D /* SwiftWhisper */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = 7C1C72F02EECBD1300E3BF4D /* XCRemoteSwiftPackageReference "SwiftWhisper" */;
+ productName = SwiftWhisper;
+ };
7C3236532EAAD608007E4CB6 /* MCP */ = {
isa = XCSwiftPackageProductDependency;
package = 7C3236522EAAD608007E4CB6 /* XCRemoteSwiftPackageReference "swift-sdk" */;
diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index f265f4b1..c7aa0aea 100644
--- a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "08725b27cbcc3e1db547ffd44b1132eb063ef3464f375f35265fbfffd0613368",
+ "originHash" : "07b7e586f8c2dbe68088e0fae56a23bdb8b67860e17657504b256be525b2ca5b",
"pins" : [
{
"identity" : "appupdater",
@@ -91,6 +91,15 @@
"version" : "1.6.3"
}
},
+ {
+ "identity" : "swiftwhisper",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/exPHAT/SwiftWhisper.git",
+ "state" : {
+ "revision" : "a192004db08de7c6eaa169eede77f1625e7d23fb",
+ "version" : "1.2.0"
+ }
+ },
{
"identity" : "version",
"kind" : "remoteSourceControl",
diff --git a/Info.plist b/Info.plist
index 8ea0745b..26ae34d5 100644
--- a/Info.plist
+++ b/Info.plist
@@ -11,7 +11,7 @@
<key>CFBundleVersion</key>
<string>1</string>
<key>CFBundleShortVersionString</key>
- <string>1.5.0</string>
+ <string>1.5.1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>LSApplicationCategoryType</key>
diff --git a/Package.resolved b/Package.resolved
index 4f4208ab..c724edff 100644
--- a/Package.resolved
+++ b/Package.resolved
@@ -54,6 +54,15 @@
"version" : "6.22.1"
}
},
+ {
+ "identity" : "swiftwhisper",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/exPHAT/SwiftWhisper.git",
+ "state" : {
+ "branch" : "master",
+ "revision" : "c340197966ebd264f3135d3955874b40f8ed58bc"
+ }
+ },
{
"identity" : "version",
"kind" : "remoteSourceControl",
diff --git a/Package.swift b/Package.swift
index 47c43664..4148039b 100644
--- a/Package.swift
+++ b/Package.swift
@@ -12,7 +12,8 @@ let package = Package(
.package(url: "https://github.com/mxcl/AppUpdater.git", from: "1.0.0"),
.package(url: "https://github.com/FluidInference/FluidAudio", from: "0.7.4"),
.package(url: "https://github.com/mxcl/PromiseKit", from: "6.0.0"),
- .package(url: "https://github.com/MrKai77/DynamicNotchKit", from: "1.0.0")
+ .package(url: "https://github.com/MrKai77/DynamicNotchKit", from: "1.0.0"),
+ .package(url: "https://github.com/exPHAT/SwiftWhisper.git", branch: "master")
],
targets: [
.executableTarget(
@@ -21,7 +22,8 @@ let package = Package(
"AppUpdater",
"FluidAudio",
"PromiseKit",
- "DynamicNotchKit"
+ "DynamicNotchKit",
+ "SwiftWhisper"
]
)
]
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 08b302b6..35a787af 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -520,6 +520,11 @@ struct ContentView: View {
? "FluidVoice stores provider API keys securely in your macOS Keychain. Please grant access by choosing \"Always Allow\" when prompted."
: keychainPermissionMessage)
}
+ .alert(asr.errorTitle, isPresented: $asr.showError) {
+ Button("OK", role: .cancel) { }
+ } message: {
+ Text(asr.errorMessage)
+ }
.onReceive(audioObserver.changePublisher) { _ in
// Hardware change detected → refresh lists and apply preferences if available
refreshDevices()
diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swift
index 5dc74686..5c21a202 100644
--- a/Sources/Fluid/Networking/ModelDownloader.swift
+++ b/Sources/Fluid/Networking/ModelDownloader.swift
@@ -1,6 +1,9 @@
import Foundation
import CoreML
+import CoreML
+#if arch(arm64)
import FluidAudio
+#endif
/// A robust downloader for Hugging Face models with progress tracking and error handling.
/// Supports downloading entire model repositories with proper file structure preservation.
@@ -296,6 +299,7 @@ final class HuggingFaceModelDownloader
}
}
+#if arch(arm64)
extension HuggingFaceModelDownloader
{
/// Load ASR models directly from disk using unified v3 model names
@@ -379,3 +383,4 @@ extension HuggingFaceModelDownloader
)
}
}
+#endif
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 0637fa6d..86a49ef3 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -64,6 +64,9 @@ final class SettingsStore: ObservableObject
// Filler Words
static let fillerWords = "FillerWords"
static let removeFillerWordsEnabled = "RemoveFillerWordsEnabled"
+
+ // Transcription Provider (ASR)
+ static let selectedTranscriptionProvider = "SelectedTranscriptionProvider"
}
// MARK: - Model Reasoning Configuration
@@ -759,4 +762,46 @@ final class SettingsStore: ObservableObject
defaults.set(newValue, forKey: Keys.removeFillerWordsEnabled)
}
}
+
+ // MARK: - Transcription Provider (ASR)
+
+ /// Available transcription providers
+ enum TranscriptionProviderOption: String, CaseIterable, Identifiable {
+ case auto = "auto"
+ case fluidAudio = "fluidAudio"
+ case whisper = "whisper"
+
+ var id: String { rawValue }
+
+ var displayName: String {
+ switch self {
+ case .auto: return "Automatic (Recommended)"
+ case .fluidAudio: return "FluidAudio (Apple Silicon)"
+ case .whisper: return "Whisper (Intel/Universal)"
+ }
+ }
+
+ var description: String {
+ switch self {
+ case .auto: return "Uses FluidAudio on Apple Silicon, Whisper on Intel"
+ case .fluidAudio: return "Fast CoreML-based transcription optimized for M-series chips"
+ case .whisper: return "whisper.cpp - works on any Mac, useful for testing"
+ }
+ }
+ }
+
+ /// Selected transcription provider - defaults to "auto" which picks based on architecture
+ var selectedTranscriptionProvider: TranscriptionProviderOption {
+ get {
+ guard let rawValue = defaults.string(forKey: Keys.selectedTranscriptionProvider),
+ let option = TranscriptionProviderOption(rawValue: rawValue) else {
+ return .auto
+ }
+ return option
+ }
+ set {
+ objectWillChange.send()
+ defaults.set(newValue.rawValue, forKey: Keys.selectedTranscriptionProvider)
+ }
+ }
}
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index f97906c0..e8dde906 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -2,7 +2,9 @@ import Foundation
import AVFoundation
import Combine
import Accelerate
+#if arch(arm64)
import FluidAudio
+#endif
import CoreAudio
import AppKit
@@ -71,6 +73,11 @@ final class ASRService: ObservableObject
@Published var modelsExistOnDisk: Bool = false
@Published var selectedModel: ModelOption = .parakeetTdt06bV3
+ // MARK: - Error Handling
+ @Published var errorTitle: String = "Error"
+ @Published var errorMessage: String = ""
+ @Published var showError: Bool = false
+
/// Returns a user-friendly status message for model loading state
var modelStatusMessage: String {
if isAsrReady { return "Model ready" }
@@ -83,9 +90,78 @@ final class ASRService: ObservableObject
enum ModelOption: String, CaseIterable, Identifiable, Hashable
{
case parakeetTdt06bV3 = "Parakeet TDT-0.6b v3"
+ case whisperBase = "Whisper Base (Intel)"
var id: String { rawValue }
var displayName: String { rawValue }
}
+
+ // MARK: - Transcription Provider (Settable)
+
+ /// Cached providers to avoid re-instantiation
+ private var fluidAudioProvider: FluidAudioProvider?
+ private var whisperProvider: WhisperProvider?
+
+ /// Prevent concurrent provider.prepare() calls (download/load) from overlapping.
+ /// Subsequent callers await the in-flight task.
+ private var ensureReadyTask: Task<Void, Error>?
+ private var ensureReadyProviderKey: String?
+
+ /// The transcription provider, selected based on user settings or architecture:
+ /// - Auto: Uses FluidAudio on Apple Silicon, Whisper on Intel
+ /// - FluidAudio: Forces FluidAudio (may not work well on Intel)
+ /// - Whisper: Forces Whisper (works on any Mac, useful for testing)
+ private var transcriptionProvider: TranscriptionProvider {
+ let setting = SettingsStore.shared.selectedTranscriptionProvider
+
+ switch setting {
+ case .auto:
+ // Auto-select based on architecture
+ if CPUArchitecture.isAppleSilicon {
+ return getFluidAudioProvider()
+ } else {
+ return getWhisperProvider()
+ }
+ case .fluidAudio:
+ return getFluidAudioProvider()
+ case .whisper:
+ return getWhisperProvider()
+ }
+ }
+
+ private func getFluidAudioProvider() -> FluidAudioProvider {
+ if let existing = fluidAudioProvider {
+ return existing
+ }
+ let provider = FluidAudioProvider()
+ fluidAudioProvider = provider
+ DebugLogger.shared.info("ASRService: Created FluidAudio provider", source: "ASRService")
+ return provider
+ }
+
+ private func getWhisperProvider() -> WhisperProvider {
+ if let existing = whisperProvider {
+ return existing
+ }
+ let provider = WhisperProvider()
+ whisperProvider = provider
+ DebugLogger.shared.info("ASRService: Created Whisper provider", source: "ASRService")
+ return provider
+ }
+
+ /// Returns the name of the active transcription provider
+ var activeProviderName: String {
+ transcriptionProvider.name
+ }
+
+ /// Call this when the transcription provider setting changes to reset state
+ func resetTranscriptionProvider() {
+ isAsrReady = false
+ modelsExistOnDisk = false
+ ensureReadyTask?.cancel()
+ ensureReadyTask = nil
+ ensureReadyProviderKey = nil
+ DebugLogger.shared.info("ASRService: Provider reset, will re-initialize on next use", source: "ASRService")
+ }
// CRITICAL FIX: Use lazy initialization to prevent AVAudioEngine() from being called during
@@ -97,7 +173,14 @@ final class ASRService: ObservableObject
private var micPermissionGranted = false
// Internal access for MeetingTranscriptionService to share models
- var asrManager: AsrManager?
+ // Note: Only available when using FluidAudioProvider (Apple Silicon)
+ #if arch(arm64)
+ var asrManager: AsrManager? {
+ (transcriptionProvider as? FluidAudioProvider)?.underlyingManager
+ }
+ #else
+ var asrManager: Any? { nil }
+ #endif
private var isRecordingWholeSession: Bool = false
// Thread-safe buffer to prevent "Array mutation while enumerating" and memory corruption crashes
@@ -162,9 +245,7 @@ final class ASRService: ObservableObject
/// Check if models exist on disk without loading them
func checkIfModelsExist() {
- let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
- let v3CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")
- modelsExistOnDisk = FileManager.default.fileExists(atPath: v3CacheDir.path)
+ modelsExistOnDisk = transcriptionProvider.modelsExistOnDisk()
DebugLogger.shared.debug("Models exist on disk: \(modelsExistOnDisk)", source: "ASRService")
}
@@ -289,15 +370,15 @@ final class ASRService: ObservableObject
do
{
try await self.ensureAsrReady()
- guard let manager = self.asrManager else {
- DebugLogger.shared.error("ASR manager is nil", source: "ASRService")
+ guard transcriptionProvider.isReady else {
+ DebugLogger.shared.error("Transcription provider is not ready", source: "ASRService")
return ""
}
DebugLogger.shared.debug("Starting transcription with \(pcm.count) samples (\(Float(pcm.count)/16000.0) seconds)", source: "ASRService")
- DebugLogger.shared.debug("stop(): starting full transcription (samples: \(pcm.count))", source: "ASRService")
- let result = try await transcriptionExecutor.run {
- try await manager.transcribe(pcm, source: AudioSource.microphone)
+ DebugLogger.shared.debug("stop(): starting full transcription (samples: \(pcm.count)) using \(transcriptionProvider.name)", source: "ASRService")
+ let result = try await transcriptionExecutor.run { [provider = self.transcriptionProvider] in
+ try await provider.transcribe(pcm)
}
DebugLogger.shared.debug("stop(): full transcription finished", source: "ASRService")
DebugLogger.shared.debug("Transcription completed: '\(result.text)' (confidence: \(result.confidence))", source: "ASRService")
@@ -313,6 +394,12 @@ final class ASRService: ObservableObject
let nsError = error as NSError
DebugLogger.shared.error("Error domain: \(nsError.domain), code: \(nsError.code)", source: "ASRService")
DebugLogger.shared.error("Error userInfo: \(nsError.userInfo)", source: "ASRService")
+
+ // Expose error to UI (specifically for model download failures on Intel)
+ self.errorTitle = "Transcription Failed"
+ self.errorMessage = error.localizedDescription
+ self.showError = true
+
return ""
}
}
@@ -548,20 +635,13 @@ final class ASRService: ObservableObject
/// Ensures that ASR models are downloaded and ready for transcription.
///
- /// This method handles the complete model lifecycle:
- /// 1. Checks if models are already available and loaded
- /// 2. Downloads models from Hugging Face if needed
- /// 3. Loads models into memory for inference
- /// 4. Initializes the ASR manager with loaded models
- ///
- /// ## Model Management
- /// - Models are downloaded from the configured Hugging Face repository
- /// - Downloads are cached to avoid repeated network requests
- /// - Download state is reported via `isDownloadingModel`
- /// - Models include: melspectrogram, encoder, decoder, joint, and token prediction
+ /// This method handles the complete model lifecycle using the appropriate
+ /// TranscriptionProvider based on CPU architecture:
+ /// - Apple Silicon: FluidAudio (CoreML optimized)
+ /// - Intel: SwiftWhisper (whisper.cpp)
///
/// ## Performance
- /// - First run will download ~100-500MB of models
+ /// - First run will download models (~100-500MB depending on provider)
/// - Subsequent runs use cached models (much faster)
/// - Model loading happens asynchronously to avoid blocking UI
///
@@ -569,120 +649,120 @@ final class ASRService: ObservableObject
/// Throws if model download or loading fails. Common causes:
/// - Network connectivity issues
/// - Insufficient disk space
- /// - Invalid model repository configuration
- ///
- /// ## Note
- /// This method is called automatically when starting transcription.
- /// Manual calls are typically not needed unless you want to preload models.
func ensureAsrReady() async throws
{
- // Check if we're already ready and models are loaded - avoid unnecessary flicker
- if isAsrReady && asrManager != nil {
- DebugLogger.shared.debug("ASR already ready with loaded models, skipping initialization", source: "ASRService")
+ let provider = transcriptionProvider
+ let providerKey = "\(type(of: provider)):\(provider.name)"
+
+ // Single-flight: if a prepare is already running for this provider, await it.
+ if let task = ensureReadyTask, ensureReadyProviderKey == providerKey {
+ try await task.value
return
}
-
- // CRITICAL FIX: Early return if already ready to prevent UI flicker and crashes
- // This prevents unnecessary state resets that can cause SwiftUI object deallocation
- if isAsrReady {
- DebugLogger.shared.debug("ASR already marked as ready, skipping state reset", source: "ASRService")
+
+ let task = Task { @MainActor in
+ try await self.performEnsureAsrReady(provider: provider)
+ }
+ ensureReadyTask = task
+ ensureReadyProviderKey = providerKey
+
+ defer {
+ if ensureReadyProviderKey == providerKey {
+ ensureReadyTask = nil
+ ensureReadyProviderKey = nil
+ }
+ }
+
+ try await task.value
+ }
+
+ private func performEnsureAsrReady(provider: TranscriptionProvider) async throws
+ {
+ // Check if already ready
+ if isAsrReady && provider.isReady {
+ DebugLogger.shared.debug("ASR already ready with loaded models, skipping initialization", source: "ASRService")
return
}
-
- // Force reinitialization for v3 models by resetting state
+
+ // If the flag is set but provider isn't ready (e.g., provider switch without reset), re-init.
+ if isAsrReady && !provider.isReady {
+ DebugLogger.shared.debug("ASR marked ready but provider not ready; re-initializing", source: "ASRService")
+ }
+
isAsrReady = false
- asrManager = nil
- if isAsrReady == false
+ let totalStartTime = Date()
+ do
{
- let totalStartTime = Date()
- do
- {
- DebugLogger.shared.info("=== ASR INITIALIZATION START ===", source: "ASRService")
-
- // Use separate cache directory for v3 models
- let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
- let cacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")
- let modelsAlreadyCached = FileManager.default.fileExists(atPath: cacheDir.path)
-
- DebugLogger.shared.info("Model cache directory: \(cacheDir.path)", source: "ASRService")
- DebugLogger.shared.info("Models already cached on disk: \(modelsAlreadyCached)", source: "ASRService")
-
- let originalStderr = dup(STDERR_FILENO)
+ DebugLogger.shared.info("=== ASR INITIALIZATION START ===", source: "ASRService")
+ DebugLogger.shared.info("Using provider: \(provider.name)", source: "ASRService")
+
+ let modelsAlreadyCached = provider.modelsExistOnDisk()
+ DebugLogger.shared.info("Models already cached on disk: \(modelsAlreadyCached)", source: "ASRService")
+
+ // Suppress stderr noise during model loading (ALWAYS restore, even on failure).
+ let originalStderr = dup(STDERR_FILENO)
+ var didRedirectStderr = false
+ if originalStderr != -1 {
let devNull = open("/dev/null", O_WRONLY)
- dup2(devNull, STDERR_FILENO)
- close(devNull)
-
- // Force v3: remove any v2 cache directory so no fallback occurs
- let v2CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v2-coreml")
- if FileManager.default.fileExists(atPath: v2CacheDir.path) {
- try FileManager.default.removeItem(at: v2CacheDir)
- DebugLogger.shared.debug("Removed v2 cache directory to force v3", source: "ASRService")
+ if devNull != -1 {
+ dup2(devNull, STDERR_FILENO)
+ close(devNull)
+ didRedirectStderr = true
}
+ }
- // Set correct loading state based on whether models are cached
- DispatchQueue.main.async {
- if modelsAlreadyCached {
- self.isLoadingModel = true
- self.isDownloadingModel = false
- DebugLogger.shared.info("📦 LOADING cached model into memory (this takes 30-60 sec)...", source: "ASRService")
- } else {
- self.isDownloadingModel = true
- self.isLoadingModel = false
- DebugLogger.shared.info("⬇️ DOWNLOADING model from Hugging Face...", source: "ASRService")
- }
- }
-
- // This call either downloads (if needed) OR just loads from cache
- let downloadStartTime = Date()
- DebugLogger.shared.info("Calling AsrModels.downloadAndLoad()...", source: "ASRService")
- let models = try await AsrModels.downloadAndLoad()
- let downloadDuration = Date().timeIntervalSince(downloadStartTime)
- DebugLogger.shared.info("✓ AsrModels.downloadAndLoad() completed in \(String(format: "%.1f", downloadDuration)) seconds", source: "ASRService")
-
- DispatchQueue.main.async {
- self.isDownloadingModel = false
- self.isLoadingModel = false
- self.modelsExistOnDisk = true
- }
-
- // Initialize AsrManager
- if self.asrManager == nil
- {
- DebugLogger.shared.debug("Creating new AsrManager...", source: "ASRService")
- self.asrManager = AsrManager(config: ASRConfig.default)
+ defer {
+ // Only restore if we actually redirected stderr.
+ if didRedirectStderr, originalStderr != -1 {
+ dup2(originalStderr, STDERR_FILENO)
}
- if let manager = self.asrManager
- {
- let initStartTime = Date()
- DebugLogger.shared.info("Initializing AsrManager with loaded models...", source: "ASRService")
- try await manager.initialize(models: models)
- let initDuration = Date().timeIntervalSince(initStartTime)
- DebugLogger.shared.info("✓ AsrManager.initialize() completed in \(String(format: "%.1f", initDuration)) seconds", source: "ASRService")
+ if originalStderr != -1 {
+ close(originalStderr)
}
-
- dup2(originalStderr, STDERR_FILENO)
- close(originalStderr)
-
- let totalDuration = Date().timeIntervalSince(totalStartTime)
- DebugLogger.shared.info("=== ASR INITIALIZATION COMPLETE ===", source: "ASRService")
- DebugLogger.shared.info("Total initialization time: \(String(format: "%.1f", totalDuration)) seconds", source: "ASRService")
}
- catch
- {
- DebugLogger.shared.error("ASR initialization failed with error: \(error)", source: "ASRService")
- DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")
- DispatchQueue.main.async {
+
+ // Set correct loading state based on whether models are cached
+ DispatchQueue.main.async {
+ if modelsAlreadyCached {
+ self.isLoadingModel = true
self.isDownloadingModel = false
+ DebugLogger.shared.info("📦 LOADING cached model into memory...", source: "ASRService")
+ } else {
+ self.isDownloadingModel = true
self.isLoadingModel = false
+ DebugLogger.shared.info("⬇️ DOWNLOADING model...", source: "ASRService")
}
- throw error
}
+
+ // Use the transcription provider to prepare models
+ let downloadStartTime = Date()
+ DebugLogger.shared.info("Calling transcriptionProvider.prepare()...", source: "ASRService")
+ try await provider.prepare(progressHandler: nil)
+ let downloadDuration = Date().timeIntervalSince(downloadStartTime)
+ DebugLogger.shared.info("✓ Provider preparation completed in \(String(format: "%.1f", downloadDuration)) seconds", source: "ASRService")
+
+ DispatchQueue.main.async {
+ self.isDownloadingModel = false
+ self.isLoadingModel = false
+ self.modelsExistOnDisk = true
+ }
+
+ let totalDuration = Date().timeIntervalSince(totalStartTime)
+ DebugLogger.shared.info("=== ASR INITIALIZATION COMPLETE ===", source: "ASRService")
+ DebugLogger.shared.info("Total initialization time: \(String(format: "%.1f", totalDuration)) seconds", source: "ASRService")
+
isAsrReady = true
}
- else
+ catch
{
- DebugLogger.shared.debug("ASR already ready, skipping initialization", source: "ASRService")
+ DebugLogger.shared.error("ASR initialization failed with error: \(error)", source: "ASRService")
+ DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")
+ DispatchQueue.main.async {
+ self.isDownloadingModel = false
+ self.isLoadingModel = false
+ }
+ throw error
}
}
@@ -702,6 +782,9 @@ final class ASRService: ObservableObject
catch
{
DebugLogger.shared.error("Model predownload failed: \(error)", source: "ASRService")
+ self.errorTitle = "Download Failed"
+ self.errorMessage = error.localizedDescription
+ self.showError = true
}
}
}
@@ -723,26 +806,9 @@ final class ASRService: ObservableObject
// MARK: - Cache management
func clearModelCache() async throws
{
- DebugLogger.shared.debug("Clearing all model caches to force fresh download", source: "ASRService")
-
- // Clear v2 cache
- let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
- let v2CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v2-coreml")
- if FileManager.default.fileExists(atPath: v2CacheDir.path) {
- try FileManager.default.removeItem(at: v2CacheDir)
- DebugLogger.shared.debug("Removed v2 cache directory", source: "ASRService")
- }
-
- // Clear v3 cache
- let v3CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")
- if FileManager.default.fileExists(atPath: v3CacheDir.path) {
- try FileManager.default.removeItem(at: v3CacheDir)
- DebugLogger.shared.debug("Removed v3 cache directory", source: "ASRService")
- }
-
- // Force reinitialization
+ DebugLogger.shared.debug("Clearing model cache via transcription provider", source: "ASRService")
+ try await transcriptionProvider.clearCache()
isAsrReady = false
- asrManager = nil
modelsExistOnDisk = false
}
@@ -799,7 +865,7 @@ final class ASRService: ObservableObject
return
}
- guard isAsrReady, let manager = asrManager else { return }
+ guard isAsrReady, transcriptionProvider.isReady else { return }
// Thread-safe count check
let currentSampleCount = audioBuffer.count
@@ -815,14 +881,14 @@ final class ASRService: ObservableObject
let startTime = Date()
do {
- DebugLogger.shared.debug("Streaming chunk starting CoreML transcription (samples: \(chunk.count))", source: "ASRService")
- let result = try await transcriptionExecutor.run {
- try await manager.transcribe(chunk, source: AudioSource.microphone)
+ DebugLogger.shared.debug("Streaming chunk starting transcription (samples: \(chunk.count)) using \(transcriptionProvider.name)", source: "ASRService")
+ let result = try await transcriptionExecutor.run { [provider = self.transcriptionProvider] in
+ try await provider.transcribe(chunk)
}
let duration = Date().timeIntervalSince(startTime)
DebugLogger.shared.debug(
- "Streaming chunk CoreML transcription finished in \(String(format: "%.2f", duration))s",
+ "Streaming chunk transcription finished in \(String(format: "%.2f", duration))s",
source: "ASRService"
)
let rawText = result.text.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -900,4 +966,3 @@ final class ASRService: ObservableObject
return filtered.joined(separator: " ")
}
}
-
diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swift
new file mode 100644
index 00000000..3799efe5
--- /dev/null
+++ b/Sources/Fluid/Services/FluidAudioProvider.swift
@@ -0,0 +1,93 @@
+import Foundation
+#if arch(arm64)
+import FluidAudio
+
+/// TranscriptionProvider implementation using FluidAudio (optimized for Apple Silicon)
+/// This wraps the existing FluidAudio-based ASR for use on Apple Silicon Macs.
+final class FluidAudioProvider: TranscriptionProvider {
+
+ let name = "FluidAudio (Apple Silicon Optimized)"
+
+ /// Whether this provider is supported on the current system.
+ /// FluidAudio is optimized for Apple Silicon, but may still function on Intel.
+ var isAvailable: Bool {
+ true
+ }
+
+ private var asrManager: AsrManager?
+ private(set) var isReady: Bool = false
+
+ func prepare(progressHandler: ((Double) -> Void)? = nil) async throws {
+ guard isReady == false else { return }
+
+ DebugLogger.shared.info("FluidAudioProvider: Starting model preparation", source: "FluidAudioProvider")
+
+ // Download and load models
+ let models = try await AsrModels.downloadAndLoad()
+
+ // Initialize AsrManager
+ let manager = AsrManager(config: ASRConfig.default)
+ try await manager.initialize(models: models)
+ self.asrManager = manager
+
+ isReady = true
+ DebugLogger.shared.info("FluidAudioProvider: Models ready", source: "FluidAudioProvider")
+ }
+
+ func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult {
+ guard let manager = asrManager else {
+ throw NSError(domain: "FluidAudioProvider", code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "ASR manager not initialized"])
+ }
+
+ let result = try await manager.transcribe(samples, source: AudioSource.microphone)
+ return ASRTranscriptionResult(text: result.text, confidence: result.confidence)
+ }
+
+ func modelsExistOnDisk() -> Bool {
+ let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
+ let v3CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")
+ return FileManager.default.fileExists(atPath: v3CacheDir.path)
+ }
+
+ func clearCache() async throws {
+ let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()
+
+ // Clear v2 cache
+ let v2CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v2-coreml")
+ if FileManager.default.fileExists(atPath: v2CacheDir.path) {
+ try FileManager.default.removeItem(at: v2CacheDir)
+ }
+
+ // Clear v3 cache
+ let v3CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")
+ if FileManager.default.fileExists(atPath: v3CacheDir.path) {
+ try FileManager.default.removeItem(at: v3CacheDir)
+ }
+
+ isReady = false
+ asrManager = nil
+ }
+
+ /// Provides direct access to the underlying AsrManager for advanced use cases
+ /// (e.g., MeetingTranscriptionService sharing)
+ var underlyingManager: AsrManager? {
+ return asrManager
+ }
+}
+#else
+/// Check-shim for Intel Macs where FluidAudio is not available
+final class FluidAudioProvider: TranscriptionProvider {
+ let name = "FluidAudio (Apple Silicon ONLY)"
+ var isAvailable: Bool { false }
+ var isReady: Bool { false }
+
+ func prepare(progressHandler: ((Double) -> Void)?) async throws {
+ throw NSError(domain: "FluidAudioProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "FluidAudio is not supported on Intel Macs"])
+ }
+
+ func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult {
+ throw NSError(domain: "FluidAudioProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "FluidAudio is not supported on Intel Macs"])
+ }
+}
+#endif
diff --git a/Sources/Fluid/Services/MeetingTranscriptionService.swift b/Sources/Fluid/Services/MeetingTranscriptionService.swift
index e25fc7fa..bfc0e711 100644
--- a/Sources/Fluid/Services/MeetingTranscriptionService.swift
+++ b/Sources/Fluid/Services/MeetingTranscriptionService.swift
@@ -1,6 +1,10 @@
import Foundation
import AVFoundation
+import AVFoundation
+#if arch(arm64)
import FluidAudio
+#endif
+import Combine
import Combine
/// Result of a transcription operation
@@ -92,6 +96,7 @@ final class MeetingTranscriptionService: ObservableObject {
try await initializeModels()
}
+ #if arch(arm64)
guard let asrManager = asrService.asrManager else {
throw TranscriptionError.modelLoadFailed("ASR Manager not initialized")
}
@@ -140,6 +145,9 @@ final class MeetingTranscriptionService: ObservableObject {
self.result = result
return result
+ #else
+ throw TranscriptionError.transcriptionFailed("File transcription is only supported on Apple Silicon Macs at this time.")
+ #endif
} catch let error as TranscriptionError {
self.error = error.localizedDescription
diff --git a/Sources/Fluid/Services/TranscriptionProvider.swift b/Sources/Fluid/Services/TranscriptionProvider.swift
new file mode 100644
index 00000000..5ee5a17e
--- /dev/null
+++ b/Sources/Fluid/Services/TranscriptionProvider.swift
@@ -0,0 +1,75 @@
+import Foundation
+
+// MARK: - Transcription Result
+
+/// Unified result type for ASR transcription across all providers
+/// Named ASRTranscriptionResult to avoid conflict with MeetingTranscriptionService.TranscriptionResult
+struct ASRTranscriptionResult {
+ let text: String
+ let confidence: Float
+
+ init(text: String, confidence: Float = 1.0) {
+ self.text = text
+ self.confidence = confidence
+ }
+}
+
+// MARK: - Transcription Provider Protocol
+
+/// Protocol that abstracts speech-to-text transcription.
+/// Implementations can use different backends (FluidAudio, SwiftWhisper, etc.)
+protocol TranscriptionProvider {
+ /// Display name of the provider
+ var name: String { get }
+
+ /// Whether this provider is available on the current system
+ var isAvailable: Bool { get }
+
+ /// Whether models are downloaded and ready
+ var isReady: Bool { get }
+
+ /// Download/prepare models for transcription
+ /// - Parameter progressHandler: Optional callback for download progress (0.0 to 1.0)
+ func prepare(progressHandler: ((Double) -> Void)?) async throws
+
+ /// Transcribe audio samples
+ /// - Parameter samples: 16kHz mono PCM float samples
+ /// - Returns: Transcription result with text and confidence
+ func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult
+
+ /// Check if models exist on disk (without loading them)
+ func modelsExistOnDisk() -> Bool
+
+ /// Clear cached models
+ func clearCache() async throws
+}
+
+// Default implementation for optional methods
+extension TranscriptionProvider {
+ func modelsExistOnDisk() -> Bool { return false }
+ func clearCache() async throws { }
+}
+
+// MARK: - Architecture Detection
+
+/// Utility to detect the current CPU architecture
+enum CPUArchitecture {
+ case applesilicon
+ case intel
+
+ static var current: CPUArchitecture {
+ #if arch(arm64)
+ return .applesilicon
+ #else
+ return .intel
+ #endif
+ }
+
+ static var isAppleSilicon: Bool {
+ current == .applesilicon
+ }
+
+ static var isIntel: Bool {
+ current == .intel
+ }
+}
diff --git a/Sources/Fluid/Services/WhisperProvider.swift b/Sources/Fluid/Services/WhisperProvider.swift
new file mode 100644
index 00000000..2e59888b
--- /dev/null
+++ b/Sources/Fluid/Services/WhisperProvider.swift
@@ -0,0 +1,135 @@
+import Foundation
+import SwiftWhisper
+
+/// TranscriptionProvider implementation using SwiftWhisper (whisper.cpp) for Intel Macs.
+/// This provides on-device speech recognition that works on Intel x86_64 architecture.
+final class WhisperProvider: TranscriptionProvider {
+
+ let name = "Whisper (Intel/Universal)"
+
+ /// Whether this provider is supported on the current system.
+ /// SwiftWhisper (whisper.cpp) works on both Intel and Apple Silicon.
+ var isAvailable: Bool {
+ true
+ }
+
+ private var whisper: Whisper?
+ private(set) var isReady: Bool = false
+
+ /// Model size to use - base is a good balance of speed and accuracy
+ /// Models: tiny (~75MB), base (~142MB), small (~466MB), medium (~1.5GB), large (~2.9GB)
+ private let modelName = "ggml-base.bin"
+
+ private var modelURL: URL {
+ let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
+ return cacheDir.appendingPathComponent("WhisperModels").appendingPathComponent(modelName)
+ }
+
+ private var modelDirectory: URL {
+ modelURL.deletingLastPathComponent()
+ }
+
+ func prepare(progressHandler: ((Double) -> Void)? = nil) async throws {
+ guard isReady == false else { return }
+
+ DebugLogger.shared.info("WhisperProvider: Starting model preparation", source: "WhisperProvider")
+
+ // Ensure model directory exists
+ try FileManager.default.createDirectory(at: modelDirectory, withIntermediateDirectories: true)
+
+ // Download model if not present
+ if !FileManager.default.fileExists(atPath: modelURL.path) {
+ DebugLogger.shared.info("WhisperProvider: Downloading Whisper model...", source: "WhisperProvider")
+ try await downloadModel(progressHandler: progressHandler)
+ }
+
+ // Load the model
+ DebugLogger.shared.info("WhisperProvider: Loading Whisper model...", source: "WhisperProvider")
+ whisper = Whisper(fromFileURL: modelURL)
+
+ isReady = true
+ DebugLogger.shared.info("WhisperProvider: Model ready", source: "WhisperProvider")
+ }
+
+ func transcribe(_ samples: [Float]) async throws -> ASRTranscriptionResult {
+ guard let whisper = whisper else {
+ throw NSError(domain: "WhisperProvider", code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Whisper model not loaded"])
+ }
+
+ // SwiftWhisper expects 16kHz PCM audio frames (which is what we receive)
+ let segments = try await whisper.transcribe(audioFrames: samples)
+
+ // Combine all segments into one string
+ let fullText = segments.map { $0.text }.joined(separator: " ").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
+
+ // SwiftWhisper doesn't provide confidence, so we use 1.0
+ return ASRTranscriptionResult(text: fullText, confidence: 1.0)
+ }
+
+ func modelsExistOnDisk() -> Bool {
+ return FileManager.default.fileExists(atPath: modelURL.path)
+ }
+
+ func clearCache() async throws {
+ if FileManager.default.fileExists(atPath: modelDirectory.path) {
+ try FileManager.default.removeItem(at: modelDirectory)
+ }
+ isReady = false
+ whisper = nil
+ }
+
+ // MARK: - Model Download
+
+ private func downloadModel(progressHandler: ((Double) -> Void)?) async throws {
+ // Whisper models are hosted on Hugging Face
+ let modelURLString = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/\(modelName)"
+
+ guard let url = URL(string: modelURLString) else {
+ throw NSError(domain: "WhisperProvider", code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid model URL"])
+ }
+
+ DebugLogger.shared.info("WhisperProvider: Downloading from \(modelURLString)", source: "WhisperProvider")
+
+ do {
+ let (tempURL, response) = try await URLSession.shared.download(from: url)
+
+ guard let httpResponse = response as? HTTPURLResponse else {
+ throw NSError(domain: "WhisperProvider", code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid server response"])
+ }
+
+ guard httpResponse.statusCode == 200 else {
+ throw NSError(domain: "WhisperProvider", code: httpResponse.statusCode,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to download model (HTTP \(httpResponse.statusCode))"])
+ }
+
+ // Move to final location
+ if FileManager.default.fileExists(atPath: modelURL.path) {
+ try FileManager.default.removeItem(at: modelURL)
+ }
+ try FileManager.default.moveItem(at: tempURL, to: modelURL)
+
+ DebugLogger.shared.info("WhisperProvider: Model downloaded successfully", source: "WhisperProvider")
+ } catch let error as NSError {
+ // Provide user-friendly error messages
+ if error.domain == NSURLErrorDomain {
+ let message: String
+ switch error.code {
+ case NSURLErrorNotConnectedToInternet:
+ message = "No internet connection. Please connect to the internet to download the Whisper model."
+ case NSURLErrorTimedOut:
+ message = "Download timed out. Please check your internet connection and try again."
+ case NSURLErrorCannotFindHost, NSURLErrorCannotConnectToHost:
+ message = "Cannot reach download server. Please check your internet connection."
+ default:
+ message = "Network error: \(error.localizedDescription)"
+ }
+ throw NSError(domain: "WhisperProvider", code: error.code,
+ userInfo: [NSLocalizedDescriptionKey: message])
+ }
+ throw error
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index cd673b5a..84edb084 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -563,6 +563,89 @@ struct SettingsView: View {
}
.padding(16)
}
+
+ // Transcription Engine Card
+ ThemedCard(style: .standard) {
+ VStack(alignment: .leading, spacing: 14) {
+ Label("Transcription Engine", systemImage: "waveform.badge.mic")
+ .font(.headline)
+ .foregroundStyle(.primary)
+
+ VStack(alignment: .leading, spacing: 12) {
+ // Current provider info
+ HStack(spacing: 8) {
+ Circle()
+ .fill(theme.palette.success)
+ .frame(width: 8, height: 8)
+ Text("Active: \(asr.activeProviderName)")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+
+ Spacer()
+
+ // Only show architecture badge when NOT in Auto mode
+ if SettingsStore.shared.selectedTranscriptionProvider != .auto {
+ Text(CPUArchitecture.isAppleSilicon ? "Apple Silicon" : "Intel")
+ .font(.caption)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 4)
+ .background(
+ RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .fill(.quaternary)
+ )
+ }
+ }
+
+ // Provider picker
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Engine")
+ .font(.body)
+ Text(SettingsStore.shared.selectedTranscriptionProvider.description)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ Picker("", selection: Binding(
+ get: { SettingsStore.shared.selectedTranscriptionProvider },
+ set: { newValue in
+ SettingsStore.shared.selectedTranscriptionProvider = newValue
+ // Reset ASR to use new provider
+ asr.resetTranscriptionProvider()
+ }
+ )) {
+ ForEach(SettingsStore.TranscriptionProviderOption.allCases) { option in
+ Text(option.displayName).tag(option)
+ }
+ }
+ .pickerStyle(.menu)
+ .frame(width: 240)
+ }
+
+ // Note for developers
+ HStack(alignment: .top, spacing: 6) {
+ Image(systemName: "info.circle.fill")
+ .foregroundStyle(theme.palette.accent)
+ .font(.caption)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("For Development/Testing")
+ .font(.caption.weight(.medium))
+ Text("Use \"Whisper\" to test Intel Mac experience on Apple Silicon. FluidAudio provides best performance on M-series chips.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ .padding(10)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(theme.palette.accent.opacity(0.1))
+ )
+ }
+ }
+ .padding(16)
+ }
// Debug Settings Card
ThemedCard(style: .standard) {