# 以 mostlucid.llmllt 文本生成的 Alt 动力化平价文本

想要获得您网站上图像的精美@, @ 描述性平方文字或 Jsut 从中提取文本\ ?} @ `mostlylucid.llmalttext` 使用微软 @'s Florence-2 视觉语言模型生成高端 @ -}Q-_ 全本地在您的机器上运行

> 注意M:我需要更新这个文件 现在 [篮子软件包 ](https://www.nuget.org/packages/Mostlylucid.LlmAltText)外端的@. @}如果您查看 [在这里](https://github.com/scottgal/mostlylucid.nugetpackages/tree/main/Mostlylucid.AltText.Demo) 您将罚款一个nifty 演示站点, 您可以下载并使用@ . @ I'# 将会更新此网站, 在未来几天里提供详细信息@.}

<datetime class="hidden">2025-11-25T14:00</datetime>

<!-- category -- ASP.NET, Accessibility, AI, NuGet, Florence-2, Image Processing -->
[![Nuget 元数](https://img.shields.io/nuget/v/mostlylucid.llmaltText.svg)](https://www.nuget.org/packages/mostlylucid.llmalttext) [![驾照@: @unlisense](https://img.shields.io/badge/license-Unlicense-blue.svg)](http://unlicense.org/)

# 一. 导言导言 导言 导言 导言

Alt text matters @.屏幕阅读器取决于它%,SEO排名因数(以 @MS K2)和它的#'s 来方便访问的正确方法@.,但为数百张图像写好的alt 文本@? that's 其中我们大部分人没有达到”.}

此软件包使用 微软 @ ' @s Florence@ MS K1# 视觉语言模型 @ MPK2} 完全在本地运行, 在您的机器上 {,} no API 键不需要\ .} 来解决问题

**源代码@: @%** [GithubMS K0com/Scottgal}/}大多是平庸的 .Nnuget packages](https://github.com/scottgal/mostlylucid.nugetpackages/tree/main/Mostlylucid.LlmAltText)

[TOC]

# 问题

每个 `<img>` 标签应该有有意义的alt text@. @ but in actually\ :

- **手工写作很烦人** 数以百计的图像表示工作时间。
- **AIAPPs AIIPS成本费用** @ - @ OpenAI Vision@, @Claude @,#等等,.}加起来很快。
- **隐私关注** - 您可能不想将图像发送到外部 API
- **质量不一致** @- 不同的人写替代文字的方式不同

如果您能自动生成高Q-质量等量文本\ , 完全在您自己的硬件中运行\ MPK2

# 如何运作

该软件包通过 ONNX 运行时间=.} 使用微软@'s Florence-2模型

```mermaid
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
```

**密钥特性 @:**

- **当地执行** @-@ no API calls,}不收费 ,没有隐私问题
- **~800MB模型** @- 下载过一次\, 永远缓存
- **多重任务类型** @-_简略字幕@,}详细描述,}OCR
- **内容分类** @-_知道它是否具有相片@'}图片: ,_ 圖表 @MS K3_ 螢幕截图 @,_ 等等 @MSC5#

# 快速启动

## 安装装置

```bash
dotnet add package Mostlylucid.LlmAltText
```

## 登记册服务

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

第一次下载佛罗伦萨--2 模型= @(~800MB_),}然后你准备去.*

## 生成 Alt 文本

```csharp
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 });
    }
}
```

# 多种投入来源

服务接受来自以下任何地方的图像: @-文件@, URLs% , 串流\,或位数阵列{.}

## 从文件路径

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

## 发自 URL

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

## 来自溪流

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

## 来自字节数组

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

# 任务类型 @:}控制详细级别

Florence -2 支援三个标题模式@. 选择基于您的需要 @:

```csharp
// 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` | 缩略图 MS K1 装饰性图像, 快速提示|
| `DETAILED_CAPTION` 基本无障碍环境 @|
| `MORE_DETAILED_CAPTION` @| @ 完全无障碍@,_ 屏幕阅读器 @ ( @ recommend@ MS K3} @ MPK4#

# OCR 文字采掘

Florence@-2 也可以从图像中提取用于截图的文本 @-}%,}文档=,}和图表_.}

```csharp
// 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}");
```

# 分类

并非所有图像都是相同的 @. 照片需要描述性alt text@; 文档需要文本内容. 分类功能帮助您正确处理每一个#:}

```csharp
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}");
```

## 处理不同内容类型

```csharp
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;
}
```

## 内容类型

@|_ type @ |} 描述 *| 示例@|
|------|-------------|---------|
| `Photograph` @| @Real@- @world 照片:#| @people_,}图片来源: @MSC5 @
| `Document` |+Text@-#Heavy内容 @|_PDFs,}表格$,+文章=|{
| `Screenshot` @| 軟體捕捉 *{|}_UI,網站 <, applications\ |
| `Chart` | 数据可视化
| `Illustration` | 画内容 @| Artwork @MS K2 卡通卡,图标@|
| `Diagram` @|_ 技术图纸 @ |_ 滚动画 @ I,_ UML,_ 图表@|}
| `Unknown` -=YTET -伊甸园字幕组=- 翻译:

# Auto Alt 文本标记辅助工具

这里% ' @ {} 引人注意 MS K1} 标签帮助器自动生成任何其它文字的替代文本@ action: check `<img>` Q-}在交接时间丢失一个标记@ .

## 设置设置设置

```csharp
// 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();
```

注册标签帮助者 `_ViewImports.cshtml`:

```cshtml
@addTagHelper *, Mostlylucid.LlmAltText
```

## 如何运作

```mermaid
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
```

## 正在处理的东西

```html
<!-- 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" />
```

## 域限制

对于security , 您可以限制 TagHelper 从 MS K1}获取的域名@ title: group

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

# 数据库缓存

数据库缓存结果由图像 URL\ .按键

## SQLite *(* 开发=)*

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

## PostgreSQL @ (} production *) 后加星数QL@ MSk0_ procution* msk1

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

# 配置引用

```csharp
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;
});
```

# Real-世界示例 :批处理

@'_%s 在导入博客posts@:}时, 我如何使用它处理图像 ?

```csharp
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";
    }
}
```

# 业绩考量

## 要期待什么

|Metric |典型值{|
|--------|--------------|
| 第一次运行 @| 慢速 *(~800MB 模式下载@) _|
-=YTET -伊甸园字幕组=- 翻译:
|+Per-+图像处理 @|+#500-2000+|{
@|_记忆使用@|}2_GB_+}推荐的{|}
|+磁盘空间 @|+#~800_MB 模型@|}

## 生产小费

```csharp
// 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
}
```

# 开放遥测集成

软件包包括已建的“ - @ in tracking”\ :

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

**追踪活动+:**

- `llmalttext.generate_alt_text`
- `llmalttext.extract_text`
- `llmalttext.analyze_image`
- `llmalttext.classify_content_type`

# 健康检查

添加健康检查以监测模型状态@: @%

```csharp
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
```

**解决方案#:**

- 检查互联网连接
- 校验防火墙允许 Huggging Face 下载
- 确保提供 ~800MB 磁盘空间
- 检查在 `ModelPath`

## 未就绪服务

```csharp
_imageAnalysis.IsReady // Returns false
```

**解决方案#:**

- 等待模型初始化@(1-3秒 @)
- 检查初始化错误的日志
- 校验足够的内存@(2 @GB}%+)#

## 低质量平文本

**解决方案#:**

- 使用 `MORE_DETAILED_CAPTION` @(_default )#
- 确保输入图像清晰
- 检查图像为 @ '# 不是太小或模糊

## 标签帮助器不工作

**解决方案#:**

- 核查校验 `EnableTagHelper = true`
- 检查支票 `@addTagHelper` 内 `_ViewImports.cshtml`
- 使用绝对 URL *\ ( reslimate 路径被跳过* )\
- 检查支票 `AllowedImageDomains` 配置配置

# 无障碍获取最佳做法

生成的alt 文本是一个起点@ . @ for the best results_ : @

1. **审查产出** @-_AI is'}不完美 ,}校验准确性
2. **保持简洁** 最大单词数
3. **叙述性说明** @- @ 包括主题@ , @ actions @ MS K2 concern
4. **避免冗余** @-_don'}先用@"_BARBAR_..."的影像开始
5. **考虑目的** @- @ adt text 应该为页面上的图像服务@'_%s角色
6. **使用空 alt 用于装饰** @-_ 设置 `alt=""` 纯装饰图像
7. **包含可见文字** @ - @ {如果图像包含文本 ,} 包括它

# 结论结论

`Mostlylucid.LlmAltText` 标签帮助器让您的应用程序和你的应用程序变得特别容易-, `<img>` 获得自动alt text@. @%

软件包是 Unlicense @ ( @ public 域@ MS K1} 所以想用它做什么都行\ .

## 资源资源资源 资源和资源资源资源

- **Nuget:** [最优lucid.LlmAltText](https://www.nuget.org/packages/Mostlylucid.LlmAltText)
- **资料来源::** [GithubMS K0com/Scottgal}/}大多是平庸的 .Nnuget packages](https://github.com/scottgal/mostlylucid.nugetpackages/tree/main/Mostlylucid.LlmAltText)
- **问题 @:** [吉特胡布问题](https://github.com/scottgal/mostlylucidweb/issues)
- **佛罗伦萨-2:** [微软' 愿景语言模式](https://huggingface.co/microsoft/Florence-2-base)