processImageForAI static method

Future<MultimodalImageResult> processImageForAI({
  1. required Uint8List imageBytes,
  2. required ModelType modelType,
  3. String? originalFormat,
  4. bool enableValidation = true,
  5. bool enableProcessing = true,
})

Processes and validates an image for use with AI models

Implementation

static Future<MultimodalImageResult> processImageForAI({
  required Uint8List imageBytes,
  required ModelType modelType,
  String? originalFormat,
  bool enableValidation = true,
  bool enableProcessing = true,
}) async {
  try {
    debugPrint('MultimodalImageHandler: Starting image processing for $modelType...');

    // Step 1: Validate image for vision encoder compatibility
    ProcessedImage? processedImage;
    if (enableProcessing) {
      processedImage = await _processImageWithValidation(imageBytes, modelType, originalFormat);
    } else {
      // Just validate format if processing is disabled
      final format = ImageProcessor.detectFormat(imageBytes);
      processedImage = ProcessedImage(
        originalBytes: imageBytes,
        processedBytes: imageBytes,
        base64String: '', // Will be set later if needed
        width: 0,
        height: 0,
        format: format,
        originalFormat: originalFormat ?? format,
      );
    }

    // Step 2: Validate for specific vision encoder
    if (enableValidation) {
      final encoderType = _getVisionEncoderType(modelType);
      final validationResult = VisionEncoderValidator.validateForEncoder(
        imageBytes: processedImage.processedBytes,
        encoderType: encoderType,
        originalFormat: processedImage.originalFormat,
      );

      if (!validationResult.isValid) {
        throw VisionEncoderValidationException(
          'Image validation failed: ${validationResult.message}'
        );
      }
    }

    debugPrint('MultimodalImageHandler: Image processing completed successfully');

    return MultimodalImageResult(
      success: true,
      processedImage: processedImage,
      modelType: modelType,
      validationPassed: enableValidation,
    );
  } catch (e) {
    debugPrint('MultimodalImageHandler: Image processing failed - $e');

    // Handle the error and provide recovery suggestions
    final errorResult = ImageErrorHandler.handleImageProcessingError(
      e,
      StackTrace.current,
      imageBytes: imageBytes,
      context: 'MultimodalImageHandler.processImageForAI',
    );

    return MultimodalImageResult(
      success: false,
      error: errorResult,
      modelType: modelType,
      validationPassed: false,
    );
  }
}