Skip to content

A production-ready .NET library for Replicate AI API integration. Generate AI images and videos using popular models like Stable Diffusion XL, HiDream, Google Veo 3, Kling, Luma Ray, and more.

License

Notifications You must be signed in to change notification settings

MarketAlly/Replicate.Maui

Repository files navigation

MarketAlly.Replicate.Maui

NuGet Version NuGet Downloads License: MIT .NET Platform

A production-ready .NET library for Replicate AI API integration. Generate AI images and videos using popular models like Stable Diffusion XL, HiDream, Google Veo 3, Kling, Luma Ray, and more.

Features

  • Dual-target support: Use with .NET MAUI apps (iOS, Android, Windows, macOS) or plain .NET 9 (console, ASP.NET Core, Blazor)
  • Pre-configured model presets: Ready-to-use configurations for popular AI models
  • Ready-to-use MAUI controls: Drop-in UI components for image/video transformation
  • Prediction tracking: Real-time status updates and history management
  • BYOK support: Bring Your Own Key for multi-tenant applications
  • Localization: Built-in support for 8 languages with custom translation capability
  • Webhook integration: Support for async processing with webhooks

Supported Models

Image Models

Model Description
HiDream E1.1 Fast high-quality image generation/editing
Stable Diffusion XL Popular open-source image generation
Ideogram V3 Turbo Best for images with realistic, legible text
Recraft V3 SVG High-quality SVG images, logos, and icons

Video Models

Model Description
Google Veo 3 Fast State-of-the-art video generation from Google
Kling 2.5 Turbo Pro Latest high-quality video generation
Kling 1.6 Pro Professional video generation
Seedance 1 Pro High-quality video with image-to-video support
Luma Ray Flash 2 Fast video generation with camera control
Wan 2.1 Image-to-video with 480p/720p support
MiniMax Video 01 Text and image to video generation

Installation

dotnet add package MarketAlly.Replicate.Maui

Or via Package Manager:

Install-Package MarketAlly.Replicate.Maui

Quick Start

Option 1: .NET MAUI Application (Full Experience)

1. Configure in MauiProgram.cs:

using MarketAlly.Replicate.Maui;

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .UseReplicateMaui(settings =>
        {
            settings.ApiToken = "your-replicate-api-token";
        });

    return builder.Build();
}

2. Add the control to your XAML:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:replicate="clr-namespace:MarketAlly.Replicate.Maui.Controls;assembly=MarketAlly.Replicate.Maui">

    <replicate:ReplicateTransformerView
        x:Name="TransformerView"
        LayoutMode="SideBySide"
        TransformationCompleted="OnTransformationCompleted" />
</ContentPage>

3. Initialize and handle events:

using MarketAlly.Replicate.Maui;
using MarketAlly.Replicate.Maui.Controls;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        // Use a preset model
        TransformerView.SetImagePreset(ModelPresets.HiDreamE1);
    }

    private void OnTransformationCompleted(object sender, TransformationCompletedEventArgs e)
    {
        // e.Result.Output contains the URL to the generated image/video
        Console.WriteLine($"Result: {e.Result.Output}");
    }
}

Option 2: API-Only Usage (Console, ASP.NET Core, Blazor)

using MarketAlly.Replicate.Maui;
using Microsoft.Extensions.Options;

// Create transformer directly
var settings = Options.Create(new ReplicateSettings
{
    ApiToken = "your-replicate-api-token"
});

using var httpClient = new HttpClient();
var transformer = new ReplicateTransformer(httpClient, settings);

// Use a model preset
var preset = ModelPresets.HiDreamE1;
var imageBytes = File.ReadAllBytes("input.jpg");

var result = await transformer.RunPresetAsync(
    preset,
    imageBytes,
    customPrompt: "anime style portrait, studio ghibli inspired"
);

Console.WriteLine($"Status: {result.Status}");
Console.WriteLine($"Output: {result.Output}");

Option 3: Dependency Injection (ASP.NET Core)

// In Program.cs or Startup.cs
services.Configure<ReplicateSettings>(options =>
{
    options.ApiToken = Configuration["Replicate:ApiToken"];
});
services.AddHttpClient<IReplicateTransformer, ReplicateTransformer>();

// In your controller or service
public class ImageController : ControllerBase
{
    private readonly IReplicateTransformer _transformer;

    public ImageController(IReplicateTransformer transformer)
    {
        _transformer = transformer;
    }

    [HttpPost("generate")]
    public async Task<IActionResult> Generate([FromBody] GenerateRequest request)
    {
        var result = await _transformer.RunPresetAsync(
            ModelPresets.StableDiffusionXL,
            Convert.FromBase64String(request.ImageBase64),
            request.Prompt
        );

        return Ok(new { result.Output, result.Status });
    }
}

Using Model Presets

Model presets provide pre-configured settings for popular models:

// Image Models
var hidream = ModelPresets.HiDreamE1;
var sdxl = ModelPresets.StableDiffusionXL;
var ideogram = ModelPresets.IdeogramV3Turbo;
var recraft = ModelPresets.RecraftV3Svg;

// Video Models
var veo = ModelPresets.GoogleVeo3Fast;
var kling = ModelPresets.Kling25TurboPro;
var seedance = ModelPresets.SeedancePro;
var luma = ModelPresets.LumaRayFlash;

// Get all presets
var allPresets = ModelPresets.All;
var imageModels = ModelPresets.ImageModels;
var videoModels = ModelPresets.VideoModels;

// Find by name
var preset = ModelPresets.FindByName("HiDream E1.1");

Custom Parameters

Override default preset parameters:

var customParams = new Dictionary<string, object>
{
    { "guidance_scale", 7.5 },
    { "num_inference_steps", 30 },
    { "seed", 42 }
};

var result = await transformer.RunPresetAsync(
    ModelPresets.StableDiffusionXL,
    imageBytes,
    customPrompt: "cyberpunk cityscape",
    customParameters: customParams
);

MAUI Control Features

Layout Modes

// Image only - no buttons (for custom UI)
TransformerView.LayoutMode = TransformerLayoutMode.ImageOnly;

// Buttons below the image (default)
TransformerView.LayoutMode = TransformerLayoutMode.ButtonsBelow;

// Overlay buttons on the image
TransformerView.LayoutMode = TransformerLayoutMode.ButtonsOverlay;

// Side-by-side source and result
TransformerView.LayoutMode = TransformerLayoutMode.SideBySide;

Overlay Button Position

// Position overlay buttons at top or bottom
TransformerView.OverlayButtonPosition = OverlayButtonPosition.Top;
TransformerView.OverlayButtonPosition = OverlayButtonPosition.Bottom; // default

Localization

Built-in support for 8 languages:

// Enable localization
TransformerView.UseLocalization = true;

// Set language
ReplicateStrings.CurrentCulture = "es"; // Spanish

// Custom translations
ReplicateStrings.RegisterTranslations("es", new Dictionary<string, string>
{
    [ReplicateStrings.Keys.Transform] = "Convertir",
    [ReplicateStrings.Keys.GenerateVideo] = "Crear vídeo"
});

Supported languages: English (en), Spanish (es), French (fr), German (de), Chinese (zh), Japanese (ja), Portuguese (pt), Italian (it)

Button Configuration

Customize button appearance:

// Configure individual buttons
TransformerView.ButtonConfigs.OverlaySelect.Text = "Choose Image";
TransformerView.ButtonConfigs.OverlaySelect.IconText = "📷";
TransformerView.ButtonConfigs.OverlayTransform.BackgroundColor = Colors.Purple;

// Set display mode
TransformerView.ButtonConfigs.DefaultDisplayMode = ButtonDisplayMode.Icon; // Icon only
TransformerView.ButtonConfigs.DefaultDisplayMode = ButtonDisplayMode.Label; // Text only
TransformerView.ButtonConfigs.DefaultDisplayMode = ButtonDisplayMode.Both; // Both (default)

Prediction Tracking

Track prediction status in real-time:

// Enable tracking (enabled by default)
var tracker = new PredictionTracker(transformer);

// Subscribe to events
tracker.PredictionStatusChanged += (s, e) =>
{
    Console.WriteLine($"Prediction {e.Prediction.Id}: {e.PreviousStatus} -> {e.NewStatus}");
};

tracker.PredictionCompleted += (s, e) =>
{
    if (e.Succeeded)
        Console.WriteLine($"Completed: {e.Prediction.Output}");
    else
        Console.WriteLine($"Failed: {e.Prediction.Error}");
};

// Access history
var history = tracker.History;
var pending = tracker.PendingPredictions;

BYOK (Bring Your Own Key)

Support multi-tenant scenarios where users provide their own API keys:

// Inject the factory
public class MyService
{
    private readonly IReplicateTransformerFactory _factory;

    public MyService(IReplicateTransformerFactory factory)
    {
        _factory = factory;
    }

    public async Task<string> GenerateForUser(string userApiKey, byte[] image)
    {
        // Create transformer with user's API key
        var transformer = _factory.CreateWithToken(userApiKey);

        var result = await transformer.RunPresetAsync(
            ModelPresets.HiDreamE1,
            image
        );

        return result.Output;
    }
}

Webhook Support

Use webhooks for long-running predictions:

var options = new PredictionOptions
{
    WebhookUrl = "https://your-server.com/webhook/replicate",
    WebhookEventsFilter = new[] { "completed" },
    WebhookOnly = true // Don't poll, just return immediately
};

var result = await transformer.RunPresetAsync(
    ModelPresets.GoogleVeo3Fast,
    imageBytes,
    options: options
);

// result.Id can be used to track the prediction
// Your webhook will receive the completion notification

Events Reference

ReplicateTransformerView Events

Event Description
ImageSelected Fired when user selects an image
TransformationStarted Fired when transformation begins
TransformationCompleted Fired when transformation succeeds
TransformationError Fired when transformation fails
PredictionTracked Fired when prediction status changes
PredictionCompleted Fired when prediction completes
FileSaved Fired when result is saved to file
FileSaveError Fired when file save fails
StateChanged Fired when control state changes
ImageTapped Fired when image is tapped

IReplicateTransformer Events

Event Description
PredictionCreated Fired immediately when prediction is created (before polling)

Error Handling

try
{
    var result = await transformer.RunPresetAsync(preset, imageBytes);

    if (result.IsFailed)
    {
        Console.WriteLine($"Prediction failed: {result.Error}");
    }
    else if (result.IsCanceled)
    {
        Console.WriteLine("Prediction was canceled");
    }
    else if (result.IsSucceeded)
    {
        Console.WriteLine($"Success: {result.Output}");
    }
}
catch (ReplicateApiException ex)
{
    Console.WriteLine($"API Error {ex.StatusCode}: {ex.Message}");
    Console.WriteLine($"Response: {ex.ResponseBody}");
}
catch (ReplicateTransformationException ex)
{
    Console.WriteLine($"Transformation Error: {ex.Message}");
}

Requirements

  • .NET 9.0 or later
  • For MAUI targets: iOS 15.0+, Android 24+, Windows 10.0.17763+, macOS 15.0+
  • Replicate API token (Get one here)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Links

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues and feature requests, please use the GitHub Issues page.


Made with care by MarketAlly

About

A production-ready .NET library for Replicate AI API integration. Generate AI images and videos using popular models like Stable Diffusion XL, HiDream, Google Veo 3, Kling, Luma Ray, and more.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages