Back to "AI-Powered Alt Text Generation with mostlylucid.llmlltText"

This is a viewer only at the moment see the article on how this works.

To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk

This is a preview from the server running through my markdig pipeline

Accessibility AI ASP.NET Florence-2 Image Processing NuGet

AI-Powered Alt Text Generation with mostlylucid.llmlltText

Tuesday, 25 November 2025

अपने साइटों पर छवियों के लिए nice, वर्णनात्मक alt पाठ या उन से jsut निष्कर्षित पाठ प्राप्त करना चाहते हैं mostlylucid.llmalttext माइक्रोसॉफ्ट का उपयोग करता है

नोट: मुझे इस डक को अब अद्यतन करने की जरूरत है नूगेट पैकेज बाहर है. अगर आप देखो यहाँ आप एक अच्छा डेमो साइट ठीक कर देंगे जिसे आप डाउनलोड और उपयोग कर सकते हैं

न्यूगेटGenericName लाइसेंस

परिचय

ऑल्ट पाठ महत्वपूर्ण है. स्क्रीन पाठक इस पर निर्भर करते हैं।

यह पैकेज माइक्रोसॉफ्ट के उपयोग से उस समस्या को हल करता है

स्रोत कोड: github.comM SK1scottgal/mostlylucid.nugetpackages

समस्या

हर <img> टैग में अर्थपूर्ण alt पाठ होना चाहिए

  • मैनुअल लेखन कंटायर है - सैकड़ों छवियों का मतलब काम के घंटे है
  • एआई APIs लागत पैसे - ओपनएआई विज़न
  • गोपनीयता संबंधी चिंताएं - आप बाहरी APIs में छवि भेजना नहीं चाहते
  • असंगत गुण - भिन्न लोग alt पाठ अलग-अलग लिखते हैं

क्या यदि आप उच्च गुणवत्ता के alt पाठ स्वचालित रूप से उत्पन्न कर सकते हैं

यह कैसे काम करता है

पैकेज माइक्रोसॉफ्ट का उपयोग करता है

flowchart TB
    subgraph Input[Image Sources]
        A[File Path]
        B[URL]
        C[Stream]
        D[Byte Array]
    end

    subgraph Processing[Florence-2 Pipeline]
        E[Image Preprocessing]
        F[Vision Encoder]
        G[Language Decoder]
    end

    subgraph Output[Results]
        H[Alt Text]
        I[OCR Text]
        J[Content Type]
    end

    A --> E
    B --> E
    C --> E
    D --> E
    E --> F
    F --> G
    G --> H
    G --> I
    G --> J

    style A stroke:#10b981,stroke-width:2px
    style B stroke:#10b981,stroke-width:2px
    style C stroke:#10b981,stroke-width:2px
    style D stroke:#10b981,stroke-width:2px
    style F stroke:#6366f1,stroke-width:2px
    style G stroke:#6366f1,stroke-width:2px
    style H stroke:#ec4899,stroke-width:2px
    style I stroke:#ec4899,stroke-width:2px
    style J stroke:#ec4899,stroke-width:2px

प्रमुख विशेषताएँ

  • स्थानीय निष्पादन - कोई API कॉल नहीं
  • ~800MB मॉडल एक बार डाउनलोड करता है
  • बहुविध कार्य प्रकार - संक्षिप्त शीर्षक
  • सामग्री वर्गीकरण पता है कि यह क्या करता है

त्वरित प्रारंभ

संस्थापन

dotnet add package Mostlylucid.LlmAltText

पंजीकरण सेवाएँ

// Program.cs
builder.Services.AddAltTextGeneration();

कि यह है, पहली रन फ्लोरेंस मॉडल डाउनलोड करता है।

ऑल्ट पाठ उत्पन्न करें

public class ImageController : ControllerBase
{
    private readonly IImageAnalysisService _imageAnalysis;

    public ImageController(IImageAnalysisService imageAnalysis)
    {
        _imageAnalysis = imageAnalysis;
    }

    [HttpPost("analyze")]
    public async Task<IActionResult> Analyze(IFormFile image)
    {
        using var stream = image.OpenReadStream();
        var altText = await _imageAnalysis.GenerateAltTextAsync(stream);

        return Ok(new { altText });
    }
}

बहु आगत स्रोत

सेवा कहीं से भी छवियों को स्वीकार करती है

फ़ाइल पथ से

var altText = await _imageAnalysis.GenerateAltTextFromFileAsync("/images/photo.jpg");

यूआरएल से

var altText = await _imageAnalysis.GenerateAltTextFromUrlAsync(
    "https://example.com/image.png");

स्ट्रीम से

using var stream = file.OpenReadStream();
var altText = await _imageAnalysis.GenerateAltTextAsync(stream);

बाइट एरे से

var bytes = await httpClient.GetByteArrayAsync(imageUrl);
var altText = await _imageAnalysis.GenerateAltTextAsync(bytes);

कार्य प्रकार: नियंत्रण विवरण स्तर

फ्लोरेंस-2 तीन कैप्सन मोड समर्थित करता है

// Brief - "A dog sitting on grass"
var brief = await _imageAnalysis.GenerateAltTextAsync(stream, "CAPTION");

// Detailed - "A golden retriever sitting on green grass in a park"
stream.Position = 0;
var detailed = await _imageAnalysis.GenerateAltTextAsync(stream, "DETAILED_CAPTION");

// Most detailed (default) - Full accessibility description
stream.Position = 0;
var full = await _imageAnalysis.GenerateAltTextAsync(stream, "MORE_DETAILED_CAPTION");
// "A happy golden retriever with light fur sitting on lush green grass
//  in a sunny park, with trees visible in the background."

प्रत्येक को कब प्रयोग करना है

कार्य प्रकार
CAPTION थम्बनेल
DETAILED_CAPTION सामाजिक मीडिया
MORE_DETAILED_CAPTION पूर्ण अभिगमता

ओसीआर पाठ निष्कर्षण

फ्लोरेंस-2 छवियों से पाठ भी निकाल सकता है।

// Extract text only
var extractedText = await _imageAnalysis.ExtractTextAsync(stream);

// Get both alt text and extracted text
var (altText, ocrText) = await _imageAnalysis.AnalyzeImageAsync(stream);

Console.WriteLine($"Alt: {altText}");
Console.WriteLine($"OCR: {ocrText}");

सामग्री प्रकार वर्गीकरण

सभी छवियाँ एक ही नहीं हैं।

var result = await _imageAnalysis.AnalyzeWithClassificationAsync(stream);

Console.WriteLine($"Type: {result.ContentType}");        // e.g., "Photograph"
Console.WriteLine($"Confidence: {result.ContentTypeConfidence:P0}"); // e.g., "87%"
Console.WriteLine($"Has Text: {result.HasSignificantText}");

विभिन्न सामग्री प्रकारों को संभालना

var result = await _imageAnalysis.AnalyzeWithClassificationAsync(stream);

switch (result.ContentType)
{
    case ImageContentType.Document:
        // Documents - prioritize extracted text
        return result.ExtractedText;

    case ImageContentType.Screenshot:
        // Screenshots - combine description with UI text
        return result.HasSignificantText
            ? $"{result.AltText}. Text visible: {result.ExtractedText}"
            : result.AltText;

    case ImageContentType.Chart:
        // Charts - describe the visualization plus data
        return $"{result.AltText}. Data: {result.ExtractedText}";

    case ImageContentType.Photograph:
    default:
        // Photos - just the description
        return result.AltText;
}

सामग्री क़िस्म संदर्भ

प्रकार वर्णन
Photograph वास्तविक
Document पाठ
Screenshot सॉफ्टवेयर कैप्चर
Chart डेटा दृश्यीकरण
Illustration ड्राउन्स सामग्री
Diagram तकनीकी रेखांकन
Unknown अवर्गीकृत

स्वतः Alt पाठ टैगHelper

यहाँ's जहाँ यह दिलचस्प हो जाता है. TagHelper स्वचालित रूप से किसी भी के लिए alt पाठ उत्पन्न करता है <img> रेंडर समय में एक टैग गुम है -

सेटअप

// Program.cs
builder.Services.AddAltTextGeneration(options =>
{
    options.EnableTagHelper = true;
    options.EnableDatabase = true;  // Cache results
    options.DbProvider = AltTextDbProvider.Sqlite;
    options.SqliteDbPath = "./alttext.db";
});

var app = builder.Build();
await app.Services.MigrateAltTextDatabaseAsync();

टैगHelper में पंजीकृत करें _ViewImports.cshtml:

@addTagHelper *, Mostlylucid.LlmAltText

यह कैसे काम करता है

flowchart LR
    subgraph Razor[Razor View Rendering]
        A[img tag found]
        B{Has alt attribute?}
        C[Skip - use existing]
        D{In cache?}
        E[Return cached]
        F[Fetch image]
        G[Generate alt text]
        H[Cache result]
        I[Render with alt]
    end

    A --> B
    B -->|Yes| C
    B -->|No| D
    D -->|Yes| E
    D -->|No| F
    F --> G
    G --> H
    H --> I
    E --> I

    style A stroke:#10b981,stroke-width:2px
    style B stroke:#6366f1,stroke-width:2px
    style G stroke:#ec4899,stroke-width:2px
    style I stroke:#8b5cf6,stroke-width:2px

क्या प्रक्रमित किया जाता है

<!-- NO ALT - Will be processed -->
<img src="https://example.com/photo.jpg" />

<!-- HAS ALT - Skipped (respects your text) -->
<img src="https://example.com/photo.jpg" alt="My custom description" />

<!-- EMPTY ALT - Skipped (decorative image per a11y standards) -->
<img src="https://example.com/decorative.jpg" alt="" />

<!-- EXPLICIT SKIP - Skipped -->
<img src="https://example.com/photo.jpg" data-skip-alt="true" />

<!-- DATA URI - Skipped (can't fetch) -->
<img src="data:image/png;base64,..." />

<!-- RELATIVE PATH - Skipped (needs absolute URL) -->
<img src="/images/photo.jpg" />

डोमेन प्रतिबंध

सुरक्षा के लिए आप यह प्रतिबंधित कर सकते हैं कि कौन सी डोमेन टैग हेल्पर से ले जाएगा

options.AllowedImageDomains = new List<string>
{
    "mycdn.example.com",
    "images.mysite.org",
    "cdn.githubusercontent.com"
};

डाटाबेस कैशिंग

कैशिंग के बिना, प्रत्येक पृष्ठ रेंडर अल्ट पाठ को पुनर्जीवित करेगा. किMSC2 slow and wastefulM SK3 डाटाबेस कैश परिणामों को छवि यूआरएल द्वारा कुंजीकृत भंडारित करता है

SQLite (Development)

builder.Services.AddAltTextGeneration(options =>
{
    options.EnableDatabase = true;
    options.DbProvider = AltTextDbProvider.Sqlite;
    options.SqliteDbPath = "./alttext.db";
    options.CacheDurationMinutes = 60;
});

PostgreSQL (Production)

builder.Services.AddAltTextGeneration(options =>
{
    options.EnableDatabase = true;
    options.DbProvider = AltTextDbProvider.PostgreSql;
    options.ConnectionString = Configuration.GetConnectionString("AltTextDb");
});

कॉन्फ़िगरेशन संदर्भ

builder.Services.AddAltTextGeneration(options =>
{
    // Model location (~800MB downloaded here)
    options.ModelPath = "./models";

    // Default task type for alt text generation
    options.DefaultTaskType = "MORE_DETAILED_CAPTION";

    // Maximum word count for alt text
    options.MaxWords = 90;

    // Enable detailed logging
    options.EnableDiagnosticLogging = true;

    // TagHelper settings
    options.EnableTagHelper = true;
    options.EnableDatabase = true;
    options.AutoMigrateDatabase = true;

    // Database provider
    options.DbProvider = AltTextDbProvider.Sqlite;
    options.SqliteDbPath = "alttext.db";
    // or
    options.DbProvider = AltTextDbProvider.PostgreSql;
    options.ConnectionString = "Host=localhost;Database=alttext;...";

    // Security
    options.AllowedImageDomains = new List<string> { "cdn.example.com" };
    options.SkipSrcPrefixes = new List<string> { "data:", "blob:" };

    // Caching
    options.CacheDurationMinutes = 60;
});

वास्तविक-विश्व उदाहरण: बैच प्रक्रमण

यहाँ छवि प्रक्रमण करने के लिए कैसे मैं यह प्रयोग करता हूँ जब ब्लॉग पोस्ट आयात करता है

public class ImageProcessor
{
    private readonly IImageAnalysisService _imageAnalysis;
    private readonly ILogger<ImageProcessor> _logger;

    public ImageProcessor(
        IImageAnalysisService imageAnalysis,
        ILogger<ImageProcessor> logger)
    {
        _imageAnalysis = imageAnalysis;
        _logger = logger;
    }

    public async Task ProcessMarkdownImagesAsync(string markdownPath)
    {
        var imageDir = Path.Combine(Path.GetDirectoryName(markdownPath)!, "images");
        if (!Directory.Exists(imageDir)) return;

        var images = Directory.GetFiles(imageDir, "*.*")
            .Where(f => IsImageFile(f));

        foreach (var imagePath in images)
        {
            try
            {
                var result = await _imageAnalysis
                    .AnalyzeWithClassificationFromFileAsync(imagePath);

                _logger.LogInformation(
                    "Processed {File}: {Type} ({Confidence:P0})",
                    Path.GetFileName(imagePath),
                    result.ContentType,
                    result.ContentTypeConfidence);

                // Store alt text for later use
                await SaveAltTextAsync(imagePath, result.AltText);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Failed to process {File}", imagePath);
            }
        }
    }

    private static bool IsImageFile(string path)
    {
        var ext = Path.GetExtension(path).ToLowerInvariant();
        return ext is ".jpg" or ".jpeg" or ".png" or ".gif" or ".webp" or ".bmp";
    }
}

निष्पादन विचार

क्या उम्मीद है

| मीट्रिक | विशिष्ट मान M| |--------|--------------| | पहली बार चलाएँ | | | धीमी |~800 | MB मॉडल डाउनलोड मॉडल लोड प्रतिमा प्रसंस्करण स्मृति उपयोग डिस्क स्थान मॉडल के लिए

उत्पादन के लिए सुझाव

// 1. Register as Singleton (model load is expensive)
builder.Services.AddAltTextGeneration(); // Already singleton internally

// 2. Check readiness before processing
if (!_imageAnalysis.IsReady)
{
    return StatusCode(503, "AI model still initializing");
}

// 3. Use cancellation tokens for timeouts
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var altText = await _imageAnalysis.GenerateAltTextFromUrlAsync(url, cts.Token);

// 4. Process in batches, not parallel (memory constraints)
foreach (var image in images)
{
    await ProcessImageAsync(image); // Sequential is safer
}

ओपन टेलीमीटरी एकीकरण

पैकेज में बनाया गया है

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing =>
    {
        tracing.AddSource("Mostlylucid.LlmAltText");
    });

अनुक्रमित क्रियाकलाप

  • llmalttext.generate_alt_text
  • llmalttext.extract_text
  • llmalttext.analyze_image
  • llmalttext.classify_content_type

स्वास्थ्य जांच

मॉडल स्थिति को मॉनिटर करने के लिए एक स्वास्थ्य जांच जोड़ें

public class AltTextHealthCheck : IHealthCheck
{
    private readonly IImageAnalysisService _service;

    public AltTextHealthCheck(IImageAnalysisService service)
        => _service = service;

    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        return Task.FromResult(_service.IsReady
            ? HealthCheckResult.Healthy("Florence-2 model ready")
            : HealthCheckResult.Unhealthy("Model not initialized"));
    }
}

// Registration
builder.Services.AddHealthChecks()
    .AddCheck<AltTextHealthCheck>("alttext");

त्रुटिमोचन

मॉडल डाउनलोड असफल

Error: Failed to download model files

समाधान

  • इंटरनेट कनेक्शन जाँचें
  • फायरवॉल को सत्यापित करें जिससे Hugging Face डाउनलोड किया जा सकता है
  • सुनिश्चित करें कि ~800MB डिस्क जगह उपलब्ध है
  • पर लिखने की अनुमति जाँचें ModelPath

सेवा तैयार नहीं है

_imageAnalysis.IsReady // Returns false

समाधान

  • मॉडल आरंभीकरण के लिए प्रतीक्षा करें (1-3 सेकंड
  • आरंभीकरण त्रुटि के लिए लॉग जाँचें
  • पर्याप्त स्मृति को सत्यापित करें

खराब गुणवत्ता Alt पाठ

समाधान

  • उपयोग करें MORE_DETAILED_CAPTION डिफ़ॉल्ट
  • सुनिश्चित करें कि इनपुट छवियाँ साफ हैं
  • छवि जाँचें नहीं है

टैगHelper कार्य नहीं कर रहा है

समाधान

  • सत्यापित करें EnableTagHelper = true
  • जाँचें @addTagHelper में _ViewImports.cshtml
  • पूर्ण यूआरएल का उपयोग करें (relative paths are skipped
  • जाँचें AllowedImageDomains कॉन्फ़िगरेशन

सुलभता सर्वोत्तम प्रथाएं

Generated alt text is a starting point. For best results

  1. आउटपुट की समीक्षा करें - AI नहीं है
  2. इसे संक्षिप्त रखें अधिकतम शब्द
  3. वर्णनात्मक होना - विषयों को शामिल करें
  4. अतिरिक्तता से बचें - donM SK1t start with "Image of..."
  5. उद्देश्य पर विचार करें - alt पाठ पृष्ठ पर छवि का कार्य करेगा
  6. सजावटी के लिए खाली alt का उपयोग करें - सेट alt="" शुद्ध सजावटी चित्रों के लिए
  7. दृश्यात्मक पाठ शामिल करें - यदि छवि में पाठ है तो यह शामिल करें

निष्कर्ष

Mostlylucid.LlmAltText आपके .NET अनुप्रयोगों में लागत या बाहरी APIs के गोपनीयता चिंताओं के बिना AI लाता है <img> टैग स्वचालित alt पाठ प्राप्त करें.

पैकेज अनलिसीन है (सार्वजनिक डोमेन

संसाधन

logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.