import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:crypto/crypto.dart'; import 'package:flutter/foundation.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:path/path.dart' as p; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../persistence/app_settings_repositories.dart'; import '../../errors/app_failure.dart'; import '../app_failure_adapter.dart'; part 'processing_resource_repository.g.dart'; part 'processing_resource_repository.freezed.dart'; enum ProcessingResourceState { notInstalled, downloading, installed, failed } enum ProcessingCapability { transcription, translation, vocalSeparation, backgroundRemoval, } class ProcessingResourceCancelledException implements Exception { const ProcessingResourceCancelledException(); } @freezed abstract class ProcessingResourceArtifact with _$ProcessingResourceArtifact { const ProcessingResourceArtifact._(); const factory ProcessingResourceArtifact({ required String path, required Uri url, required String sha256, required int bytes, }) = _ProcessingResourceArtifact; } @freezed abstract class ProcessingResourcePackage with _$ProcessingResourcePackage { const ProcessingResourcePackage._(); const factory ProcessingResourcePackage({ required ProcessingCapability capability, required String id, required String version, required String name, required String description, required List artifacts, }) = _ProcessingResourcePackage; int get bytes => artifacts.fold(0, (total, artifact) => total + artifact.bytes); } @freezed abstract class ProcessingResourceInstall with _$ProcessingResourceInstall { const ProcessingResourceInstall._(); const factory ProcessingResourceInstall({ required ProcessingResourcePackage package, required ProcessingResourceState state, @Default(0) int downloadedBytes, AppFailure? error, }) = _ProcessingResourceInstall; double get progress => package.bytes == 0 ? 0 : (downloadedBytes / package.bytes).clamp(0, 1); } const _translationRevision = '18e406c615ef2991fa74d53734bf66b0a6b10cb4'; const _whisperRevision = '5359861c739e955e79d9a303bcbc70fb988958b1'; final defaultProcessingResourceCatalog = [ ProcessingResourcePackage( capability: ProcessingCapability.transcription, id: 'whisper-turbo', version: '1', name: 'Whisper Large V3 Turbo', description: '语音识别与字幕生成', artifacts: [ ProcessingResourceArtifact( path: 'ggml-model.bin', url: Uri.parse( 'https://huggingface.co/ggerganov/whisper.cpp/resolve/' '$_whisperRevision/ggml-large-v3-turbo-q5_0.bin', ), sha256: '394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2', bytes: 574041195, ), ProcessingResourceArtifact( path: 'silero_vad.onnx', url: Uri.parse( 'https://github.com/k2-fsa/sherpa-onnx/releases/download/' 'asr-models/silero_vad.onnx', ), sha256: '9e2449e1087496d8d4caba907f23e0bd3f78d91fa552479bb9c23ac09cbb1fd6', bytes: 643854, ), ], ), ProcessingResourcePackage( capability: ProcessingCapability.translation, id: 'm2m100-418m', version: '1', name: 'M2M100 418M', description: '字幕翻译', artifacts: [ ProcessingResourceArtifact( path: 'config.json', url: Uri.parse( 'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/config.json', ), sha256: '8f6496adfc930cbfecbe8281112197705c488fab47d34b4829b06d7f478909af', bytes: 223, ), ProcessingResourceArtifact( path: 'model.bin', url: Uri.parse( 'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/model.bin', ), sha256: 'a1826980fc5c037e69c7ac94fcb56c03001a66f380eb71863cc0a3879e71421b', bytes: 490667752, ), ProcessingResourceArtifact( path: 'sentencepiece.bpe.model', url: Uri.parse( 'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/sentencepiece.bpe.model', ), sha256: 'd8f7c76ed2a5e0822be39f0a4f95a55eb19c78f4593ce609e2edbc2aea4d380a', bytes: 2423393, ), ProcessingResourceArtifact( path: 'shared_vocabulary.json', url: Uri.parse( 'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/shared_vocabulary.json', ), sha256: '7eb5d0ff184c6095c7c10f9911c0aea492250abd12854f9c3d787c64b1c6397e', bytes: 2796509, ), ], ), ProcessingResourcePackage( capability: ProcessingCapability.backgroundRemoval, id: 'birefnet-matting', version: '1', name: 'BiRefNet Matting', description: '图片与视频背景移除', artifacts: [ ProcessingResourceArtifact( path: 'model.onnx', url: Uri.parse( 'https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/' 'BiRefNet-matting-epoch_100.onnx', ), sha256: '6065d27c615ea27308f5b88598dd8db116eb07436c7a323ca40d13b2866c309e', bytes: 972667742, ), ], ), ]; @Riverpod(keepAlive: true) FutureOr> processingResourceRepository( Ref ref, ) async { final resources = await ref .watch(resourceLocationSettingsRepositoryProvider) .load(); final resourcesRoot = resources!; final repository = ProcessingResourceRepository( root: Directory(p.join(resourcesRoot, 'Processing')), downloadsRoot: Directory(p.join(resourcesRoot, 'Downloads')), ); await repository.load(); ref.onDispose(repository.dispose); return repository; } /// Owns optional resources required by processing capabilities. /// Downloads never publish a partially installed /// version: verified files are assembled in staging and the directory is then /// atomically renamed into place. final class ProcessingResourceRepository extends ChangeNotifier { ProcessingResourceRepository({ Directory? root, this.downloadsRoot, List? catalog, }) : root = root ?? Directory(_defaultRoot()), catalog = List.unmodifiable(catalog ?? defaultProcessingResourceCatalog); final Directory root; final Directory? downloadsRoot; final List catalog; final Map _installs = {}; final Set _cancelled = {}; bool _loaded = false; bool _disposed = false; bool _subtitleDownloading = false; bool _subtitleCancelled = false; bool _subtitlePaused = false; Set _subtitleAvailable = const {}; Completer? _subtitleResume; final Map _downloadClients = {}; final Map _downloadRates = {}; final Map> _pausedDownloads = {}; void _changed() { if (!_disposed) notifyListeners(); } @override void dispose() { if (_disposed) return; _disposed = true; _subtitleCancelled = true; resumeSubtitleResources(); _cancelled.addAll( _installs.values .where( (install) => install.state == ProcessingResourceState.downloading, ) .map((install) => install.package.id), ); for (final id in _downloadClients.keys.toList()) { _cancelled.add(id); _pausedDownloads.remove(id)?.complete(); _downloadClients[id]?.close(force: true); } super.dispose(); } static const subtitleCapabilities = [ ProcessingCapability.transcription, ProcessingCapability.translation, ]; bool get subtitlePaused => _subtitlePaused; bool get subtitleDownloading => _subtitleDownloading; int get subtitleDownloadBytesPerSecond => _subtitlePaused ? 0 : subtitleCapabilities.fold( 0, (total, capability) => total + downloadBytesPerSecondFor(capability), ); int downloadBytesPerSecondFor(ProcessingCapability capability) { final package = packageFor(capability); if (installFor(capability).state != ProcessingResourceState.downloading) { return 0; } return _downloadRates[package.id]?.bytesPerSecond ?? 0; } bool downloadPausedFor(ProcessingCapability capability) => _pausedDownloads.containsKey(packageFor(capability).id); void pauseDownload(ProcessingCapability capability) { final id = packageFor(capability).id; if (installFor(capability).state != ProcessingResourceState.downloading || _pausedDownloads.containsKey(id)) { return; } _pausedDownloads[id] = Completer(); _downloadRates[id]?.reset(); _changed(); } void resumeDownload(ProcessingCapability capability) { final id = packageFor(capability).id; final gate = _pausedDownloads.remove(id); if (gate == null) return; _downloadRates[id]?.reset(); gate.complete(); _changed(); } Future _waitForDownloadResume(String packageId) async { while (_pausedDownloads.containsKey(packageId)) { await _pausedDownloads[packageId]!.future; } if (_cancelled.contains(packageId)) { throw const ProcessingResourceCancelledException(); } } int get subtitleTotalBytes => subtitleCapabilities.fold( 0, (total, capability) => total + packageFor(capability).bytes, ); int get subtitleDownloadedBytes => subtitleCapabilities.fold(0, ( total, capability, ) { final install = installFor(capability); return total + (_subtitleAvailable.contains(capability) || install.state == ProcessingResourceState.installed ? install.package.bytes : install.downloadedBytes.clamp(0, install.package.bytes).toInt()); }); void pauseSubtitleResources() { if (!_subtitleDownloading || _subtitlePaused) return; _subtitlePaused = true; for (final capability in subtitleCapabilities) { _downloadRates[packageFor(capability).id]?.reset(); } _subtitleResume = Completer(); _changed(); } void resumeSubtitleResources() { if (!_subtitlePaused) return; _subtitlePaused = false; for (final capability in subtitleCapabilities) { _downloadRates[packageFor(capability).id]?.reset(); } _subtitleResume?.complete(); _subtitleResume = null; _changed(); } Future _waitForSubtitleResume(String packageId) async { if (!_subtitleDownloading || !subtitleCapabilities.any( (capability) => packageFor(capability).id == packageId, )) { return; } while (_subtitlePaused && !_subtitleCancelled) { await _subtitleResume!.future; } if (_subtitleCancelled) { throw const ProcessingResourceCancelledException(); } } /// Installs both subtitle resources with one byte-weighted progress value. /// Already configured resources participate as completed bytes. Future ensureSubtitleResources({ Set available = const {}, required void Function(ProcessingCapability stage, double progress) onProgress, }) async { if (_subtitleDownloading) { throw StateError('Subtitle download is already in progress'); } var stage = ProcessingCapability.transcription; final total = subtitleTotalBytes; _subtitleDownloading = true; _subtitleCancelled = false; _subtitlePaused = false; _subtitleAvailable = Set.unmodifiable(available); _changed(); void report() { final completed = subtitleDownloadedBytes; var installed = true; for (final capability in subtitleCapabilities) { final install = installFor(capability); final ready = available.contains(capability) || install.state == ProcessingResourceState.installed; installed = installed && ready; } onProgress( stage, installed ? 1.0 : (total == 0 ? 0.0 : completed / total) .clamp(0.0, 0.99) .toDouble(), ); } try { await load(); addListener(report); for (final capability in subtitleCapabilities) { await _waitForSubtitleResume(packageFor(capability).id); if (_subtitleCancelled) { throw const ProcessingResourceCancelledException(); } if (available.contains(capability) || installFor(capability).state == ProcessingResourceState.installed) { continue; } stage = capability; report(); if (_subtitleCancelled) { throw const ProcessingResourceCancelledException(); } await ensureAvailable(capability); } if (_subtitleCancelled) { throw const ProcessingResourceCancelledException(); } report(); } finally { removeListener(report); _subtitleDownloading = false; _subtitleAvailable = const {}; resumeSubtitleResources(); _changed(); } } void cancelSubtitleResources() { _subtitleCancelled = true; resumeSubtitleResources(); for (final capability in subtitleCapabilities) { cancel(capability); } } List get installs => [ for (final package in catalog) _installs[package.id] ?? ProcessingResourceInstall( package: package, state: ProcessingResourceState.notInstalled, ), ]; static String _defaultRoot() { if (Platform.isMacOS) { return p.join( Platform.environment['HOME'] ?? '', 'Library', 'Application Support', 'Cutdex', 'models', ); } if (Platform.isWindows) { return p.join( Platform.environment['LOCALAPPDATA'] ?? '', 'Cutdex', 'models', ); } return p.join( Platform.environment['XDG_DATA_HOME'] ?? p.join(Platform.environment['HOME'] ?? '', '.local', 'share'), 'cutdex', 'models', ); } Directory directoryFor(ProcessingResourcePackage package) => Directory( p.join( root.path, switch (package.capability) { ProcessingCapability.transcription => 'Transcription', ProcessingCapability.translation => 'Translation', ProcessingCapability.vocalSeparation => 'VocalSeparation', ProcessingCapability.backgroundRemoval => 'BackgroundRemoval', }, package.id, package.version, ), ); ProcessingResourcePackage packageFor(ProcessingCapability capability) => catalog.singleWhere((item) => item.capability == capability); ProcessingResourceInstall installFor(ProcessingCapability capability) { final package = packageFor(capability); return _installs[package.id] ?? ProcessingResourceInstall( package: package, state: ProcessingResourceState.notInstalled, ); } Future load() async { if (_loaded) return; _loaded = true; for (final package in catalog) { final installed = await _isValidInstall(package); _installs[package.id] = ProcessingResourceInstall( package: package, state: installed ? ProcessingResourceState.installed : ProcessingResourceState.notInstalled, ); } _changed(); } Future ensureAvailable(ProcessingCapability capability) async { await load(); final package = packageFor(capability); final id = package.id; if (_installs[id]?.state == ProcessingResourceState.installed) { return directoryFor(package); } if (_installs[id]?.state == ProcessingResourceState.downloading) { throw StateError('Resource download is already in progress'); } _cancelled.remove(id); _set(package, ProcessingResourceState.downloading); final destination = directoryFor(package); final staging = downloadsRoot == null ? Directory('${destination.path}.download') : Directory( p.join(downloadsRoot!.path, '${package.id}-${package.version}'), ); try { if (await staging.exists()) await staging.delete(recursive: true); await staging.create(recursive: true); var completed = 0; for (final artifact in package.artifacts) { await _waitForSubtitleResume(id); if (_cancelled.contains(id)) { throw const ProcessingResourceCancelledException(); } final target = File(p.join(staging.path, artifact.path)); await target.parent.create(recursive: true); await _download(id, artifact, target, (received) { _set( package, ProcessingResourceState.downloading, downloadedBytes: completed + received, ); }); completed += artifact.bytes; } if (_cancelled.contains(id)) { throw const ProcessingResourceCancelledException(); } await File(p.join(staging.path, '.installed.json')).writeAsString( jsonEncode({'id': package.id, 'version': package.version}), flush: true, ); await destination.parent.create(recursive: true); if (await destination.exists()) await destination.delete(recursive: true); await staging.rename(destination.path); _set( package, ProcessingResourceState.installed, downloadedBytes: package.bytes, ); return destination; } on ProcessingResourceCancelledException { if (await staging.exists()) await staging.delete(recursive: true); _set(package, ProcessingResourceState.notInstalled); throw const ProcessingResourceCancelledException(); } catch (error) { if (await staging.exists()) await staging.delete(recursive: true); if (_cancelled.contains(id)) { _set(package, ProcessingResourceState.notInstalled); throw const ProcessingResourceCancelledException(); } _set( package, ProcessingResourceState.failed, error: appFailureFromError(error), ); rethrow; } finally { _pausedDownloads.remove(id)?.complete(); _cancelled.remove(id); } } void cancel(ProcessingCapability capability) { final id = packageFor(capability).id; if (_subtitleDownloading && subtitleCapabilities.contains(capability)) { _subtitleCancelled = true; resumeSubtitleResources(); } _cancelled.add(id); resumeDownload(capability); _downloadClients[id]?.close(force: true); } Future remove(ProcessingCapability capability) async { await load(); final package = packageFor(capability); cancel(capability); final directory = directoryFor(package); if (await directory.exists()) await directory.delete(recursive: true); _set(package, ProcessingResourceState.notInstalled); } Future _isValidInstall(ProcessingResourcePackage package) async { final directory = directoryFor(package); final marker = File(p.join(directory.path, '.installed.json')); if (!await marker.exists()) return false; try { final value = jsonDecode(await marker.readAsString()); if (value is! Map || value['id'] != package.id || value['version'] != package.version) { return false; } return package.artifacts.every( (artifact) => File(p.join(directory.path, artifact.path)).existsSync(), ); } on FormatException { return false; } } Future _download( String packageId, ProcessingResourceArtifact artifact, File target, ValueChanged onProgress, ) async { if (_disposed) throw const ProcessingResourceCancelledException(); final client = HttpClient(); _downloadClients[packageId] = client; final rate = _DownloadRate(); _downloadRates[packageId] = rate; try { await _waitForSubtitleResume(packageId); await _waitForDownloadResume(packageId); final request = await client.getUrl(artifact.url); request.headers.set(HttpHeaders.userAgentHeader, 'Cutdex/1'); final response = await request.close(); if (response.statusCode < 200 || response.statusCode >= 300) { throw AppException( AppErrorCode.resourceDownloadHttpFailed, httpStatusCode: response.statusCode, diagnostic: artifact.url.toString(), ); } final output = target.openWrite(); final digestOutput = _DigestSink(); final digestInput = sha256.startChunkedConversion(digestOutput); var received = 0; try { await for (final chunk in response) { await _waitForSubtitleResume(packageId); await _waitForDownloadResume(packageId); if (_cancelled.contains(packageId)) { throw const ProcessingResourceCancelledException(); } digestInput.add(chunk); output.add(chunk); received += chunk.length; rate.record(received); onProgress(received); } } finally { digestInput.close(); await output.close(); } final actual = digestOutput.value.toString(); if (received != artifact.bytes || actual != artifact.sha256) { throw AppException(AppErrorCode.resourceChecksumFailed); } } finally { _downloadRates.remove(packageId); _downloadClients.remove(packageId); client.close(force: true); } } void _set( ProcessingResourcePackage package, ProcessingResourceState state, { int downloadedBytes = 0, AppFailure? error, }) { _installs[package.id] = ProcessingResourceInstall( package: package, state: state, downloadedBytes: downloadedBytes, error: error, ); _changed(); } } final class _DownloadRate { final Stopwatch _clock = Stopwatch()..start(); int _sampleBytes = 0; int _sampleMilliseconds = 0; int _lastBytes = 0; int bytesPerSecond = 0; void record(int receivedBytes) { _lastBytes = receivedBytes; final now = _clock.elapsedMilliseconds; final elapsed = now - _sampleMilliseconds; if (elapsed < 500) return; bytesPerSecond = ((receivedBytes - _sampleBytes) * 1000 / elapsed).round(); _sampleBytes = receivedBytes; _sampleMilliseconds = now; } void reset() { _sampleBytes = _lastBytes; _sampleMilliseconds = _clock.elapsedMilliseconds; bytesPerSecond = 0; } } final class _DigestSink implements Sink { Digest? _digest; Digest get value => _digest ?? (throw StateError('Missing digest')); @override void add(Digest data) => _digest = data; @override void close() {} }