Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 16,491 Bytes
5acd9c3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 |
// lib/formats/openclap.dart
import 'dart:convert';
import 'dart:typed_data';
import 'dart:math';
import 'dart:io';
import 'package:uuid/uuid.dart';
import 'package:yaml/yaml.dart';
import 'package:http/http.dart' as http;
enum ClapFormat {
clap0('clap-0'),
clap0b('clap-0b');
final String value;
const ClapFormat(this.value);
static ClapFormat fromString(String value) {
return ClapFormat.values.firstWhere(
(e) => e.value == value,
orElse: () => ClapFormat.clap0,
);
}
}
enum ClapSegmentCategory {
splat('SPLAT'),
mesh('MESH'),
depth('DEPTH'),
effect('EFFECT'),
event('EVENT'),
interface('INTERFACE'),
phenomenon('PHENOMENON'),
video('VIDEO'),
image('IMAGE'),
transition('TRANSITION'),
character('CHARACTER'),
location('LOCATION'),
time('TIME'),
era('ERA'),
lighting('LIGHTING'),
weather('WEATHER'),
action('ACTION'),
music('MUSIC'),
sound('SOUND'),
dialogue('DIALOGUE'),
style('STYLE'),
camera('CAMERA'),
group('GROUP'),
generic('GENERIC');
final String value;
const ClapSegmentCategory(this.value);
// Updated to handle nullable String input
static ClapSegmentCategory fromString(String? value) {
if (value == null) return ClapSegmentCategory.generic;
return ClapSegmentCategory.values.firstWhere(
(e) => e.value == value.toUpperCase(),
orElse: () => ClapSegmentCategory.generic,
);
}
}
enum ClapImageRatio {
landscape('LANDSCAPE'),
portrait('PORTRAIT'),
square('SQUARE');
final String value;
const ClapImageRatio(this.value);
static ClapImageRatio fromString(String? value) {
if (value == null) return ClapImageRatio.landscape;
return ClapImageRatio.values.firstWhere(
(e) => e.value == value.toUpperCase(),
orElse: () => ClapImageRatio.landscape,
);
}
}
enum ClapOutputType {
text('TEXT'),
animation('ANIMATION'),
interface('INTERFACE'),
event('EVENT'),
phenomenon('PHENOMENON'),
transition('TRANSITION'),
image('IMAGE'),
imageSegmentation('IMAGE_SEGMENTATION'),
imageDepth('IMAGE_DEPTH'),
video('VIDEO'),
videoSegmentation('VIDEO_SEGMENTATION'),
videoDepth('VIDEO_DEPTH'),
audio('AUDIO');
final String value;
const ClapOutputType(this.value);
static ClapOutputType fromString(String? value) {
if (value == null) return ClapOutputType.text;
return ClapOutputType.values.firstWhere(
(e) => e.value == value.toUpperCase(),
orElse: () => ClapOutputType.text,
);
}
}
enum ClapAssetSource {
remote('REMOTE'),
path('PATH'),
data('DATA'),
prompt('PROMPT'),
empty('EMPTY');
final String value;
const ClapAssetSource(this.value);
static ClapAssetSource fromString(String? value) {
if (value == null) return ClapAssetSource.empty;
return ClapAssetSource.values.firstWhere(
(e) => e.value == value.toUpperCase(),
orElse: () => ClapAssetSource.empty,
);
}
}
/// Data classes for CLAP structure
class ClapMeta {
final String id;
final String title;
final String description;
final String caption;
final String licence;
final int bpm;
final double frameRate;
final List<String> tags;
final String thumbnailUrl;
final ClapImageRatio imageRatio;
final int durationInMs;
final int width;
final int height;
final String imagePrompt;
final String systemPrompt;
final String storyPrompt;
final bool isLoop;
final bool isInteractive;
ClapMeta({
String? id,
this.title = '',
this.description = '',
this.caption = '',
this.licence = '',
this.bpm = 120,
this.frameRate = 24,
this.tags = const [],
this.thumbnailUrl = '',
ClapImageRatio? imageRatio,
this.durationInMs = 4000,
this.width = 1024,
this.height = 576,
this.imagePrompt = '',
this.systemPrompt = '',
this.storyPrompt = '',
this.isLoop = false,
this.isInteractive = false,
}) : id = id ?? const Uuid().v4(),
imageRatio = imageRatio ?? ClapImageRatio.landscape;
factory ClapMeta.fromMap(Map<String, dynamic> map) {
return ClapMeta(
id: map['id'] as String?,
title: map['title'] as String? ?? '',
description: map['description'] as String? ?? '',
caption: map['caption'] as String? ?? '',
licence: map['licence'] as String? ?? '',
bpm: (map['bpm'] as num?)?.toInt() ?? 120,
frameRate: (map['frameRate'] as num?)?.toDouble() ?? 24,
tags: List<String>.from(map['tags'] ?? []),
thumbnailUrl: map['thumbnailUrl'] as String? ?? '',
imageRatio: ClapImageRatio.fromString(map['imageRatio'] as String?),
durationInMs: (map['durationInMs'] as num?)?.toInt() ?? 4000,
width: (map['width'] as num?)?.toInt() ?? 1024,
height: (map['height'] as num?)?.toInt() ?? 576,
imagePrompt: map['imagePrompt'] as String? ?? '',
systemPrompt: map['systemPrompt'] as String? ?? '',
storyPrompt: map['storyPrompt'] as String? ?? '',
isLoop: map['isLoop'] as bool? ?? false,
isInteractive: map['isInteractive'] as bool? ?? false,
);
}
Map<String, dynamic> toMap() {
return {
'id': id,
'title': title,
'description': description,
'caption': caption,
'licence': licence,
'bpm': bpm,
'frameRate': frameRate,
'tags': tags,
'thumbnailUrl': thumbnailUrl,
'imageRatio': imageRatio.value,
'durationInMs': durationInMs,
'width': width,
'height': height,
'imagePrompt': imagePrompt,
'systemPrompt': systemPrompt,
'storyPrompt': storyPrompt,
'isLoop': isLoop,
'isInteractive': isInteractive,
};
}
}
class ClapSegment {
final String id;
final String parentId;
final List<String> childrenIds;
final int track;
final int startTimeInMs;
final int endTimeInMs;
final ClapSegmentCategory category;
final String entityId;
final String workflowId;
final String sceneId;
final int startTimeInLines;
final int endTimeInLines;
final String prompt;
final String label;
final ClapOutputType outputType;
final String renderId;
final String status;
final String assetUrl;
final int assetDurationInMs;
final ClapAssetSource assetSourceType;
final String assetFileFormat;
final String createdAt;
final String createdBy;
final int revision;
final String editedBy;
final double outputGain;
final int seed;
ClapSegment({
String? id,
this.parentId = '',
this.childrenIds = const [],
this.track = 0,
this.startTimeInMs = 0,
this.endTimeInMs = 0,
ClapSegmentCategory? category,
this.entityId = '',
this.workflowId = '',
this.sceneId = '',
this.startTimeInLines = 0,
this.endTimeInLines = 0,
this.prompt = '',
this.label = '',
ClapOutputType? outputType,
this.renderId = '',
this.status = 'TO_GENERATE',
this.assetUrl = '',
this.assetDurationInMs = 0,
ClapAssetSource? assetSourceType,
this.assetFileFormat = '',
String? createdAt,
this.createdBy = 'ai',
this.revision = 0,
this.editedBy = 'ai',
this.outputGain = 0,
int? seed,
}) : id = id ?? const Uuid().v4(),
category = category ?? ClapSegmentCategory.generic,
outputType = outputType ?? ClapOutputType.text,
assetSourceType = assetSourceType ?? ClapAssetSource.empty,
createdAt = createdAt ?? DateTime.now().toIso8601String(),
seed = seed ?? Random().nextInt(1 << 31);
factory ClapSegment.fromMap(Map<String, dynamic> map) {
return ClapSegment(
id: map['id'] as String?,
parentId: map['parentId'] as String? ?? '',
childrenIds: List<String>.from(map['childrenIds'] ?? []),
track: (map['track'] as num?)?.toInt() ?? 0,
startTimeInMs: (map['startTimeInMs'] as num?)?.toInt() ?? 0,
endTimeInMs: (map['endTimeInMs'] as num?)?.toInt() ?? 0,
category: ClapSegmentCategory.fromString(map['category'] as String?),
entityId: map['entityId'] as String? ?? '',
workflowId: map['workflowId'] as String? ?? '',
sceneId: map['sceneId'] as String? ?? '',
startTimeInLines: (map['startTimeInLines'] as num?)?.toInt() ?? 0,
endTimeInLines: (map['endTimeInLines'] as num?)?.toInt() ?? 0,
prompt: map['prompt'] as String? ?? '',
label: map['label'] as String? ?? '',
outputType: ClapOutputType.fromString(map['outputType'] as String?),
renderId: map['renderId'] as String? ?? '',
status: map['status'] as String? ?? 'TO_GENERATE',
assetUrl: map['assetUrl'] as String? ?? '',
assetDurationInMs: (map['assetDurationInMs'] as num?)?.toInt() ?? 0,
assetSourceType: ClapAssetSource.fromString(map['assetSourceType'] as String?),
assetFileFormat: map['assetFileFormat'] as String? ?? '',
createdAt: map['createdAt'] as String?,
createdBy: map['createdBy'] as String? ?? 'ai',
revision: (map['revision'] as num?)?.toInt() ?? 0,
editedBy: map['editedBy'] as String? ?? 'ai',
outputGain: (map['outputGain'] as num?)?.toDouble() ?? 0,
seed: (map['seed'] as num?)?.toInt(),
);
}
Map<String, dynamic> toMap() {
return {
'id': id,
'parentId': parentId,
'childrenIds': childrenIds,
'track': track,
'startTimeInMs': startTimeInMs,
'endTimeInMs': endTimeInMs,
'category': category.value,
'entityId': entityId,
'workflowId': workflowId,
'sceneId': sceneId,
'startTimeInLines': startTimeInLines,
'endTimeInLines': endTimeInLines,
'prompt': prompt,
'label': label,
'outputType': outputType.value,
'renderId': renderId,
'status': status,
'assetUrl': assetUrl,
'assetDurationInMs': assetDurationInMs,
'assetSourceType': assetSourceType.value,
'assetFileFormat': assetFileFormat,
'createdAt': createdAt,
'createdBy': createdBy,
'revision': revision,
'editedBy': editedBy,
'outputGain': outputGain,
'seed': seed,
};
}
}
/// Main CLAP parser class
class ClapParser {
static Future<Map<String, dynamic>> parseClap(dynamic source, {
bool debug = false,
void Function(double progress, String message)? onProgress,
}) async {
onProgress?.call(0, 'Opening .clap file...');
// Handle different input types
String yamlString;
if (source is String) {
if (source.startsWith('data:application/x-gzip;base64,') ||
source.startsWith('data:application/octet-stream;base64,')) {
// Handle base64 data URI
yamlString = await _decompressBase64(source);
} else if (source.startsWith('http://') || source.startsWith('https://')) {
// Handle remote URL
onProgress?.call(0.2, 'Downloading .clap file...');
final response = await http.get(Uri.parse(source));
if (response.statusCode != 200) {
throw Exception('Failed to download the .clap file');
}
yamlString = await _decompressBytes(response.bodyBytes);
} else {
// Assume direct YAML string
yamlString = source;
}
} else if (source is Uint8List) {
// Handle compressed bytes
yamlString = await _decompressBytes(source);
} else {
throw Exception('Unsupported source type');
}
onProgress?.call(0.4, 'Parsing .clap file...');
// Parse YAML
final yaml = loadYaml(yamlString) as YamlList;
if (yaml.length < 2) {
throw Exception('Invalid CLAP file: missing header or metadata');
}
// Validate format
final header = yaml[0] as YamlMap;
if (header['format'] != ClapFormat.clap0.value) {
throw Exception('Invalid CLAP format');
}
onProgress?.call(0.6, 'Processing metadata...');
// Parse metadata
final meta = ClapMeta.fromMap(_yamlToMap(yaml[1] as YamlMap));
// Parse segments and other components
final segments = <ClapSegment>[];
final expectedSegments = (header['numberOfSegments'] as int?) ?? 0;
onProgress?.call(0.8, 'Processing segments...');
for (int i = 2; i < yaml.length && i < (2 + expectedSegments); i++) {
segments.add(ClapSegment.fromMap(_yamlToMap(yaml[i] as YamlMap)));
}
onProgress?.call(1.0, 'Completed parsing');
return {
'meta': meta,
'segments': segments,
// Add other components as needed
};
}
/// Helper method to decompress base64 data URI
static Future<String> _decompressBase64(String dataUri) async {
final base64Data = dataUri.split(',')[1];
final bytes = base64Decode(base64Data);
return _decompressBytes(bytes);
}
/// Helper method to decompress gzipped bytes
static Future<String> _decompressBytes(Uint8List bytes) async {
try {
final decompressed = GZipCodec().decode(bytes);
return utf8.decode(decompressed);
} catch (e) {
throw Exception('Failed to decompress CLAP file: $e');
}
}
/// Helper method to convert YamlMap to regular Map
static Map<String, dynamic> _yamlToMap(YamlMap yaml) {
return Map<String, dynamic>.from(yaml);
}
}
/// CLAP Serializer class for creating CLAP files
class ClapSerializer {
static Future<Uint8List> serializeClap(Map<String, dynamic> clap) async {
final meta = clap['meta'] as ClapMeta;
final segments = (clap['segments'] as List<ClapSegment>?)?.toList() ?? [];
// Create header
final header = {
'format': ClapFormat.clap0.value,
'numberOfSegments': segments.length,
// Add other counts as needed
};
// Create YAML entries
final entries = [
header,
meta.toMap(),
...segments.map((s) => s.toMap()),
];
// Convert to YAML string
final yaml = toYamlString(entries);
// Compress
final compressed = GZipCodec().encode(utf8.encode(yaml));
return Uint8List.fromList(compressed);
}
/// Helper method to convert data to YAML string
static String toYamlString(List<Map<String, dynamic>> entries) {
final buffer = StringBuffer();
for (final entry in entries) {
buffer.writeln('---');
_writeYamlMap(entry, buffer);
}
return buffer.toString();
}
/// Helper method to write map as YAML
static void _writeYamlMap(Map<String, dynamic> map, StringBuffer buffer, [String indent = '']) {
for (final entry in map.entries) {
if (entry.value == null) continue;
if (entry.value is Map) {
buffer.writeln('$indent${entry.key}:');
_writeYamlMap(entry.value as Map<String, dynamic>, buffer, '$indent ');
} else if (entry.value is List) {
if ((entry.value as List).isEmpty) {
buffer.writeln('$indent${entry.key}: []');
} else {
buffer.writeln('$indent${entry.key}:');
for (final item in entry.value as List) {
if (item is Map) {
buffer.writeln('$indent -');
_writeYamlMap(item as Map<String, dynamic>, buffer, '$indent ');
} else {
buffer.writeln('$indent - $item');
}
}
}
} else {
buffer.writeln('$indent${entry.key}: ${_formatYamlValue(entry.value)}');
}
}
}
/// Helper method to format YAML values
static String _formatYamlValue(dynamic value) {
if (value is String) {
if (value.contains('\n') || value.contains(':') || value.contains('#')) {
return '|\n ${value.replaceAll('\n', '\n ')}';
}
return value.contains(' ') ? '"$value"' : value;
}
return value.toString();
}
}
/// Example usage class
class ClapFile {
static Future<ClapFile> fromSource(dynamic source) async {
final parsed = await ClapParser.parseClap(source);
return ClapFile._(parsed);
}
final ClapMeta meta;
final List<ClapSegment> segments;
// Add other components as needed
ClapFile._(Map<String, dynamic> parsed)
: meta = parsed['meta'] as ClapMeta,
segments = (parsed['segments'] as List<ClapSegment>?)?.toList() ?? [];
Future<Uint8List> serialize() async {
return ClapSerializer.serializeClap({
'meta': meta,
'segments': segments,
});
}
/// Helper method to save to a file
Future<void> saveToFile(String path) async {
final bytes = await serialize();
await File(path).writeAsBytes(bytes);
}
/// Helper method to create a data URI
Future<String> toDataUri() async {
final bytes = await serialize();
final base64 = base64Encode(bytes);
return 'data:application/x-gzip;base64,$base64';
}
} |