<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Azure - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ freeCodeCamp 是一个免费学习编程的开发者社区，涵盖 Python、HTML、CSS、React、Vue、BootStrap、JSON 教程等，还有活跃的技术论坛和丰富的社区活动，在你学习编程和找工作时为你提供建议和帮助。 ]]>
        </description>
        <link>https://www.freecodecamp.org/chinese/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Azure - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/chinese/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 19:38:00 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/chinese/news/tag/azure/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ 用 Azure AI 解决数独问题 ]]>
                </title>
                <description>
                    <![CDATA[ 这篇文章将带你使用 Azure 表单识别器创建一个数独解题器，Azure 表单识别器是一个由 AI 驱动的文档提取服务。 我们的程序将首先让用户上传一张数独表的图片，接下来我们将从图像中提取数据，然后基于此数据实现数独解题算法。 我们将在后端使用 .NET，在前端使用 Angular，并用 Angular material 来设计程序的 UI 风格。 下面是此软件的一个演示。 准备  * 从 https://nodejs.org/zh-cn/download/  下载并安装最新的 LTS 版本的 Node.js  * 从 https://cli.angular.io/  下载并安装 Angular CLI  * 一个 Azure 订阅账号，你可以在 https://azure.microsoft.com/zh-cn/free/  创建一个免费的 Azure 账号  * 从 https://dotnet.microsoft.com/zh-cn/download/dotnet/5.0  下载并安装 ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/solve-sudoku-using-azure-ai/</link>
                <guid isPermaLink="false">6300954060480505ded7a836</guid>
                
                    <category>
                        <![CDATA[ Azure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ 数独 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ HeZean ]]>
                </dc:creator>
                <pubDate>Fri, 19 Aug 2022 08:00:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2022/08/6065634f9618b008528ab1f6.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p data-test-label="translation-intro">
        <strong>原文：</strong> <a href="https://www.freecodecamp.org/news/solve-sudoku-using-azure-ai/" target="_blank" rel="noopener noreferrer" data-test-label="original-article-link">How to Solve a Sudoku Puzzle Using Azure AI</a>
      </p><!--kg-card-begin: markdown--><p>这篇文章将带你使用 Azure 表单识别器创建一个数独解题器，Azure 表单识别器是一个由 AI 驱动的文档提取服务。</p>
<p>我们的程序将首先让用户上传一张数独表的图片，接下来我们将从图像中提取数据，然后基于此数据实现数独解题算法。</p>
<p>我们将在后端使用 .NET，在前端使用 Angular，并用 Angular material 来设计程序的 UI 风格。</p>
<p>下面是此软件的一个演示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/SudokuSolver.gif" alt="SudokuSolver" width="600" height="400" loading="lazy"></p>
<h2 id="">准备</h2>
<ul>
<li>从 <a href="https://nodejs.org/zh-cn/download/">https://nodejs.org/zh-cn/download/</a> 下载并安装最新的 LTS 版本的 Node.js</li>
<li>从 <a href="https://cli.angular.io/">https://cli.angular.io/</a> 下载并安装 Angular CLI</li>
<li>一个 Azure 订阅账号，你可以在 <a href="https://azure.microsoft.com/zh-cn/free/">https://azure.microsoft.com/zh-cn/free/</a> 创建一个免费的 Azure 账号</li>
<li>从 <a href="https://dotnet.microsoft.com/zh-cn/download/dotnet/5.0">https://dotnet.microsoft.com/zh-cn/download/dotnet/5.0</a> 下载并安装 .NET Core 5.0 SDK</li>
<li>从 <a href="https://visualstudio.microsoft.com/downloads/">https://visualstudio.microsoft.com/downloads/</a> 下载并安装最新版本的 Visual Studio 2019（译者注：已推出了更新版本的 Visual Studio 2022）</li>
</ul>
<h2 id="">源代码</h2>
<p>你可以在 <a href="https://github.com/AnkitSharma-007/Azure-AI-Sudoku-solver">GitHub</a> 上获取源代码。</p>
<h2 id="azure">什么是 Azure 表单识别器认知服务</h2>
<p>得益于 <a href="https://azure.microsoft.com/zh-cn/services/form-recognizer/">Azure 表单识别器</a>认知服务，我们可以使用机器学习技术构建自动数据处理软件。它能从文档中提取文本、键-值对、选择标记、表格和结构。</p>
<p>在 REST API 或客户端库 SDK 的帮助下，我们可以轻松地调用表单识别器模型。</p>
<p>表单识别器认知服务提供了以下功能：</p>
<ul>
<li><strong>预构建模型</strong>：我们可以使用预先建立的模型，从独特的文件类型中提取数据，比如发票、收据、身份证和名片。</li>
<li><strong>自定义模型</strong>：我们可以使用自定义模型从表单中提取文本、键-值对、选择标记和表格数据。但我们需要使用自己的数据来训练自定义模型，使其适合我们的自定义需求。</li>
<li><strong>布局 API</strong>：它允许我们从文件中提取文本、选择标记和表格结构。</li>
</ul>
<p>在这篇文章中，我们将使用布局 API 从用户上传的数独表图片中提取内容。</p>
<h2 id="azure">如何创建 Azure 表单识别器认知服务资源</h2>
<p>登录 Azure 门户，在搜索栏中搜索“认知服务”并点击结果。在下一个屏幕上，点击“创建”按钮。这将打开认知服务市场的页面。在搜索栏中搜索“表单识别器”，并点击搜索结果中的“表单识别器”选项。</p>
<p>这将打开表单识别器 API 页面。点击“创建”按钮来新建一个表单识别器资源。如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/CreateFR.png" alt="CreateFR" width="600" height="400" loading="lazy"></p>
<p>在创建表格识别器的页面中，按照下面的指引填写详细信息。</p>
<ul>
<li><strong>订阅 / Subscription</strong>：从下拉菜单中选择订阅类型。</li>
<li><strong>资源组 / Resource group</strong>：选择一个现有的资源组或新建一个资源组。</li>
<li><strong>地区 / Region</strong>：选择你所在的地区。</li>
<li><strong>名称 / Name</strong>：为你的资源起一个独特的名字。</li>
<li><strong>定价 / Pricing tier</strong>：选择你想要的定价级别。</li>
</ul>
<p>点击“检查并创建”按钮。如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/ConfigureFR.png" alt="ConfigureFR" width="600" height="400" loading="lazy"></p>
<p>在下一个页面，勾选确认使用条款，检查核对你所提供的信息，然后点击“创建”按钮。</p>
<p>在你的资源被成功部署后，点击“转到资源”按钮。点击左边菜单上的“密钥和端点”链接。如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/FRKeys.png" alt="FRKeys" width="600" height="400" loading="lazy"></p>
<p>记下端点和页面上提供的任意一个密钥。我们将在本文的后半部分使用这些来从 .NET 代码中调用表单识别器服务的布局 API。</p>
<h2 id="aspnetcore">如何创建 ASP.NET Core 程序</h2>
<p>打开 Visual Studio 2019（或更新版本），点击“创建一个新项目”，这将打开一个“创建新项目”对话框。选择“ASP.NET Core with Angular”并点击“下一步”。如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/CreateProj.png" alt="CreateProj" width="600" height="400" loading="lazy"></p>
<p>现在你将进入“配置新项目”界面。为该应用程序设置一个名称，比如 <code>ngSudokuSolver</code>，并点击“下一步”。如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/CreateProj_1.png" alt="CreateProj_1" width="600" height="400" loading="lazy"></p>
<p>在附加信息页面，选择目标框架为 .NET 5.0，并将认证类型设置为“无”，如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/CreateProj_2.png" alt="CreateProj_2" width="600" height="400" loading="lazy"></p>
<p>现在，我们创建了一个工程。这个程序的文件夹结构应与下图类似：</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/Sol_Exp.png" alt="Sol_Exp" width="600" height="400" loading="lazy"></p>
<p><code>ClientApp</code> 文件夹中包含我们程序的 Angular 代码。<code>Controllers</code> 文件夹将包含 API 控制器。Angular 组件则位于 <code>ClientApp/src/app</code> 文件夹中。</p>
<p>默认模板包含了一些 Angular 组件。这些组件不会影响我们的应用程序，但为了简单起见，我们将从 <code>ClientApp/src/app</code> 文件夹中删除 <code>fetchdata</code> 和 <code>counter</code> 文件夹。同时，从 <code>app.module.ts</code> 文件中删除对这两个组件的引用。</p>
<h2 id="nuget">如何安装所需的 NuGet 包</h2>
<p>要安装 NuGet 包，请打开 工具 &gt;&gt; NuGet 包管理器 &gt;&gt; 包管理器控制台。这将在 Visual Studio 内打开包管理器控制台。</p>
<p>运行以下命令来安装 <a href="https://www.nuget.org/packages/Polly">Polly</a>。这个库能让你以流畅和线程安全的方式表达弹性和瞬时故障处理策略，如重试、断路、超时、隔板隔离和回退。</p>
<p><code>Install-Package Polly -Version 7.2.1</code></p>
<p>运行以下命令来安装 <a href="https://www.nuget.org/packages/Newtonsoft.Json/">Newtonsoft.Json</a>。</p>
<p><code>Install-Package Newtonsoft.Json -Version 13.0.1</code></p>
<h2 id="retrymessagehandler">如何创建 RetryMessage Handler</h2>
<p>右键单击 <code>ngSudokuSolver</code> 项目，选择 添加 &gt;&gt; 新文件夹。将该文件夹命名为 Models。</p>
<p>接下来，右键单击 Models 文件夹并选择 添加 &gt;&gt; 类 来添加一个新的类文件。把这个类的名字定为 <code>HttpRetryMessageHandler.cs</code>，然后点击“添加”。</p>
<p>将下面的代码放入这个类里面。</p>
<pre><code class="language-C#">using Newtonsoft.Json;
using Polly;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace ngSudokuSolver.Models
{
    public class HttpRetryMessageHandler : DelegatingHandler
    {
        public HttpRetryMessageHandler(HttpClientHandler handler) : base(handler) { }

        protected override Task&lt;HttpResponseMessage&gt; SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken) =&gt;
            Policy
                .Handle&lt;HttpRequestException&gt;()
                .Or&lt;TaskCanceledException&gt;()
                .OrResult&lt;HttpResponseMessage&gt;(x =&gt;
                {
                    string result = x.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    dynamic array = JsonConvert.DeserializeObject(result);

                    if (array["status"] == "running")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                })
                .WaitAndRetryAsync(7, retryAttempt =&gt; TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
                .ExecuteAsync(() =&gt; base.SendAsync(request, cancellationToken));
    }
}
</code></pre>
<p>我们将使用 RetryMessageHandler 来重试对 <code>sendAsync</code> 的调用。如果 HttpResponseMessage 的状态是“运行中”，我们将重试 HTTP 调用。</p>
<p>我们把最大重试次数设置为 7 次。每次重试时，都会增加等待时间，将其翻倍。如果所有重试次数已经用完，而 HttpResponseMessage 还没有成功，我们将返回 false。</p>
<h2 id="formrecognizer">如何加入 FormRecognizer 控制器</h2>
<p>我们现在在程序里加入一个新的控制器。</p>
<p>右键单击 Controllers 文件夹，选择 添加 &gt;&gt; 新项目。这将打开一个“添加新项目”的对话框。</p>
<p>从左侧栏选择 “Visual C#”，然后在模版栏中选择 “API Controller-Empty”，并将其命名为 <code>FormRecognizerController.cs</code>，点击“添加”。如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/AddController.png" alt="AddController" width="600" height="400" loading="lazy"></p>
<p>将以下代码放入该类。</p>
<pre><code class="language-C#">using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ngSudokuSolver.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ngSudokuSolver.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class FormRecognizerController : ControllerBase
    {
        static string endpoint;
        static string apiKey;

        public FormRecognizerController()
        {
            endpoint = "https://sudokusolver.cognitiveservices.azure.com/";
            apiKey = "a9f75796b3ba49bdade48eb3b905cb0e";
        }

        [HttpPost, DisableRequestSizeLimit]
        public async Task&lt;string[][]&gt; Post()
        {
            try
            {
                string[][] sudokuArray = GetNewSudokuArray();

                if (Request.Form.Files.Count &gt; 0)
                {
                    var file = Request.Form.Files[Request.Form.Files.Count - 1];

                    if (file.Length &gt; 0)
                    {
                        var memoryStream = new MemoryStream();
                        file.CopyTo(memoryStream);
                        byte[] imageFileBytes = memoryStream.ToArray();
                        memoryStream.Flush();

                        string SudokuLayoutJSON = await GetSudokuBoardLayout(imageFileBytes);
                        if (SudokuLayoutJSON.Length &gt; 0)
                        {
                            sudokuArray = GetSudokuBoardItems(SudokuLayoutJSON);
                        }
                    }
                }

                return sudokuArray;
            }
            catch
            {
                throw;
            }
        }

        static async Task&lt;string&gt; GetSudokuBoardLayout(byte[] byteData)
        {
            HttpClient client = new();
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
            string uri = endpoint + "formrecognizer/v2.1-preview.3/layout/analyze";
            string LayoutJSON = string.Empty;

            using (ByteArrayContent content = new(byteData))
            {
                HttpResponseMessage response;
                content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                response = await client.PostAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    HttpHeaders headers = response.Headers;

                    if (headers.TryGetValues("Operation-Location", out IEnumerable&lt;string&gt; values))
                    {
                        string OperationLocation = values.First();
                        LayoutJSON = await GetJSON(OperationLocation);
                    }
                }
            }
            return LayoutJSON;
        }

        static async Task&lt;string&gt; GetJSON(string endpoint)
        {
            using var client = new HttpClient(new HttpRetryMessageHandler(new HttpClientHandler()));
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Get;
            request.RequestUri = new Uri(endpoint);

            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);

            var response = await client.SendAsync(request);
            var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();

            return result;
        }

        static string[][] GetSudokuBoardItems(string LayoutData)
        {
            string[][] sudokuArray = GetNewSudokuArray();
            dynamic array = JsonConvert.DeserializeObject(LayoutData);
            int countOfCells = ((JArray)array?.analyzeResult?.pageResults[0]?.tables[0]?.cells).Count;

            for (int i = 0; i &lt; countOfCells; i++)
            {
                int rowIndex = array.analyzeResult.pageResults[0].tables[0].cells[i].rowIndex;
                int columnIndex = array.analyzeResult.pageResults[0].tables[0].cells[i].columnIndex;

                sudokuArray[rowIndex][columnIndex] = array.analyzeResult.pageResults[0].tables[0].cells[i]?.text;
            }
            return sudokuArray;
        }

        static string[][] GetNewSudokuArray()
        {
            string[][] sudokuArray = new string[9][];

            for (int i = 0; i &lt; 9; i++)
            {
                sudokuArray[i] = new string[9];
            }

            return sudokuArray;
        }
    }
}
</code></pre>
<p>在 FormRecognizerController 类的构造函数中，我们初始化了表单识别器 API 的密钥和端点 URL。</p>
<p>上面的 Post 方法将接收请求体中作为文件集合的图像数据，并返回一个二维数组。我们将把图像数据转换为字节数组并调用 <code>GetSudokuBoardLayout</code> 方法。如果我们得到一个成功的响应并且 JSON 结果非空，我们将调用 <code>GetSudokuBoardItems</code> 方法。</p>
<p>在 <code>GetSudokuBoardLayout</code> 方法中，我们将实例化一个新的 HttpClient。我们会在请求头中传递订阅密钥。</p>
<p>当我们调用表单识别器 API 时，Azure 服务将返回状态码 202。这表明该服务已经接受了请求，并将在稍后开始处理。</p>
<p>响应包括一个“Operation-Location”首部。“Operation-Location”字段里的数据就我们将用来获取表单识别结果的 URL，这个 URL 会在 48 小时后过期。</p>
<p>在获取表单识别结果前需要等待一段时间，等待时间的长短与文本的长度相关。</p>
<p>这里就要用到了我们前面配置的 RetryMessageHandler。我们将从“Operation-Location”首部获取 URL，并调用 <code>GetJSON</code> 方法来获取 JSON 结果。</p>
<p>在 <code>GetJSON</code> 方法中，我们创建了一个 HttpClient，并用自定义的 <code>HttpRetryMessageHandler</code> 来初始化它。这个方法将以字符串的形式返回 JSON 响应。</p>
<p><code>GetSudokuBoardItems</code> 方法接受 JSON 字符串。然后它将遍历 JSON 字符串中的 table 属性，以准备二维的 <code>sudokuArray</code>。</p>
<h2 id="">现在，让我们开始实现程序的客户端部分</h2>
<p>客户端的代码位于 ClientApp 文件夹中。我们将使用 Angular CLI 来处理客户端的代码。</p>
<blockquote>
<p>Angular CLI 并非你的唯一选择。本文中使用 Angular CLI 是因为它对用户友好且直接。如果你不想使用 CLI，你可以手动创建组件和服务的文件。</p>
</blockquote>
<p>进入 <code>ngSudokuSolver/ClientApp</code> 文件夹并在此打开一个命令窗口。我们将在这个窗口中执行我们所有的 Angular CLI 命令。</p>
<h2 id="angularmaterial">如何安装 Angular Material</h2>
<p>运行以下命令以将 Angular Material 添加到项目中。</p>
<p><code>ng add @angular/material</code></p>
<p>该命令将为你的项目安装 Angular Material，它会询问以下问题，以确定要包括哪些功能：</p>
<ul>
<li>Choose a prebuilt theme name, or "custom" for a custom theme: <strong>请选择 Indigo/Pink 主题</strong></li>
<li>Set up global Angular Material typography styles? (Y/n): <strong>Y</strong></li>
<li>Set up browser animations for Angular Material? (Y/n): <strong>Y</strong></li>
</ul>
<p>如下图所示：</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/ngMaterial.png" alt="ngMaterial" width="600" height="400" loading="lazy"></p>
<h2 id="angularmaterial">如何为 Angular Material 添加模块</h2>
<p>运行以下命令来创建一个新的模块。</p>
<p><code>ng g m ng-material</code></p>
<p>将下面的代码放入 <code>src\app\ng-material\ng-material.module.ts</code> 文件中。</p>
<pre><code class="language-typescript">import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatInputModule } from '@angular/material/input';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';

const materialModules = [
  MatButtonModule,
  MatCardModule,
  MatInputModule,
  MatToolbarModule,
  MatDividerModule,
  MatIconModule,
];

@NgModule({
  declarations: [],
  imports: [CommonModule, ...materialModules],
  exports: [...materialModules],
})
export class NgMaterialModule {}
</code></pre>
<p>我们正在导入我们将在这个应用程序中使用的 Angular material 组件的所有必要模块。独立的 Angular material 模块将使该应用易于维护。</p>
<p>在 <code>app.module.ts</code> 文件中导入 <code>NgMaterialModule</code>，如下所示：</p>
<pre><code class="language-typescript">import { NgMaterialModule } from './ng-material/ng-material.module';

@NgModule({
	...
	imports: [
		...
		NgMaterialModule,
	],
})
</code></pre>
<h2 id="">如何配置程序的导航栏</h2>
<p>打开 <code>nav-menu.component.html</code>，在里面放入以下代码。</p>
<pre><code class="language-html">&lt;mat-toolbar color="primary" class="mat-elevation-z2"&gt;
  &lt;mat-toolbar-row&gt;
    &lt;div&gt;
      &lt;button mat-button [routerLink]='["/"]'&gt;
        &lt;mat-icon&gt;book&lt;/mat-icon&gt; Sudoku Solver
      &lt;/button&gt;
    &lt;/div&gt;
  &lt;/mat-toolbar-row&gt;
&lt;/mat-toolbar&gt;
</code></pre>
<p>现在，我们成功地在程序中加入了 Angular material 工具栏，和一个链接到程序根路由的按钮。</p>
<h2 id="">如何创建表单识别器服务</h2>
<p>我们将创建一个 Angular 服务，它将调用 Web API 端点并将响应传递给我们的组件。请运行下面的命令。</p>
<p><code>ng g s services\form-recognizer</code></p>
<p>这个命令将创建一个名为 services 的文件夹，然后在里面创建以下两个文件：</p>
<ul>
<li>form-recognizer.service.ts - 服务类文件</li>
<li>form-recognizer.service.spec.ts - 服务的单元测试文件</li>
</ul>
<p>将下面的代码放入 <code>form-recognizer.service.ts</code> 文件中。</p>
<pre><code class="language-typescript">import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class FormRecognizerService {
  baseURL: string;

  constructor(private http: HttpClient) {
    this.baseURL = '/api/FormRecognizer';
  }

  getSudokuTableFromImage(image: FormData) {
    return this.http.post(this.baseURL, image);
  }
}
</code></pre>
<p>我们定义了一个存有 API 的端点 URL 的变量 baseURL。我们会在构造器中初始化 baseURL，并将其赋值为 <code>FormRecognizerController</code> 的端点。</p>
<p><code>getSudokuTableFromImage</code> 方法将向 <code>FormRecognizerController</code> 发送一个 Post 请求并提供 FormData 类型的参数。它将获取一个表示数独表的二维数组。</p>
<h2 id="">如何更新主页组件</h2>
<p>把下面的代码放入 <code>home.component.html</code> 中。</p>
<pre><code class="language-html">&lt;div class="container"&gt;
  &lt;h1 class="display-4"&gt; 用 Azure AI 解决数独问题 &lt;/h1&gt;
  &lt;mat-divider&gt;&lt;/mat-divider&gt;
  &lt;div class="row mt-3"&gt;
    &lt;div class="col-md-6"&gt;
      &lt;mat-card class="mat-elevation-z4"&gt;
        &lt;mat-card-content&gt;
          &lt;table&gt;
            &lt;tr *ngFor="let row of gameBoard"&gt;
              &lt;td *ngFor="let col of gameBoard"&gt;
                {{game[row][col]}}
              &lt;/td&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/mat-card-content&gt;
        &lt;mat-card-actions&gt;
          &lt;button type="button" mat-raised-button color="primary" (click)="SolveSudoku()"&gt; 解数独 &lt;/button&gt;
        &lt;/mat-card-actions&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
    &lt;div class="col-md-6"&gt;
      &lt;div class="image-container"&gt;
        &lt;img class="preview-image" src={{imagePreview}}&gt;
      &lt;/div&gt;
      &lt;input type="file" (change)="uploadImage($event)" /&gt;
      &lt;hr /&gt;
      &lt;button mat-raised-button color="accent" (click)="GetSudokuTable()"&gt;
        &lt;span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"&gt;&lt;/span&gt; 提取数独表
      &lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<p>我们创建了一个 9x9 的数独表格。我们定义了一个支持上传图片的文件上传控件。上传图片后，<code>&lt;img&gt;</code> 元素中将显示图片的预览。</p>
<p>点击“提取数独表”按钮将从图像中获取数独的内容，并将这些数字填入表格中。点击“解数独”将解决数独，并将结果更新到表格中。</p>
<p>把以下代码放入 <code>home.component.ts</code> 中。</p>
<pre><code class="language-typescript">import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { FormRecognizerService } from '../services/form-recognizer.service';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnDestroy {
  gameBoard = [0, 1, 2, 3, 4, 5, 6, 7, 8];
  loading = false;
  imageFile;
  imagePreview;
  maxFileSize: number;
  isValidFile = true;
  status: string;
  DefaultStatus: string;
  imageData = new FormData();
  game = new Array(9);
  private unsubscribe$ = new Subject();

  constructor(private formRecognizerService: FormRecognizerService) {
    this.DefaultStatus = '允许上传的最大图像大小为 4 MB';
    this.status = this.DefaultStatus;
    this.maxFileSize = 4 * 1024 * 1024; // 4MB

    for (var i = 0; i &lt; this.game.length; i++) {
      this.game[i] = new Array(9);
    }
  }

  uploadImage(event) {
    this.imageFile = event.target.files[0];
    if (this.imageFile.size &gt; this.maxFileSize) {
      this.status = `文件大小为 ${this.imageFile.size} 比特，超出所允许的大小上限 ${this.maxFileSize} 比特。`;
      this.isValidFile = false;
    } else if (this.imageFile.type.indexOf('image') == -1) {
      this.status = '请上传有效的图片文件';
      this.isValidFile = false;
    } else {
      const reader = new FileReader();
      reader.readAsDataURL(event.target.files[0]);
      reader.onload = () =&gt; {
        this.imagePreview = reader.result;
      };
      this.status = this.DefaultStatus;
      this.isValidFile = true;
    }
  }

  GetSudokuTable() {
    if (this.isValidFile) {
      this.loading = true;
      this.imageData.append('imageFile', this.imageFile);

      this.formRecognizerService
        .getSudokuTableFromImage(this.imageData)
        .pipe(takeUntil(this.unsubscribe$))
        .subscribe(
          (result: any) =&gt; {
            this.game = result;
            this.loading = false;
          },
          () =&gt; {
            console.error();
            this.loading = false;
          }
        );
    }
  }

  SolveSudoku() {
    this.sudokuSolver(this.game);
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  private sudokuSolver(data) {
    for (let i = 0; i &lt; 9; i++) {
      for (let j = 0; j &lt; 9; j++) {
        if (data[i][j] == '') {
          for (let k = 1; k &lt;= 9; k++) {
            if (this.isSudokuValid(data, i, j, k)) {
              data[i][j] = `${k}`;
              if (this.sudokuSolver(data)) {
                return true;
              } else {
                data[i][j] = '';
              }
            }
          }
          return false;
        }
      }
    }
    return true;
  }

  private isSudokuValid(board, row, col, k) {
    for (let i = 0; i &lt; 9; i++) {
      const m = 3 * Math.floor(row / 3) + Math.floor(i / 3);
      const n = 3 * Math.floor(col / 3) + (i % 3);
      if (board[row][i] == k || board[i][col] == k || board[m][n] == k) {
        return false;
      }
    }
    return true;
  }
}
</code></pre>
<p>我们在 <code>HomeComponent</code> 的构造器中注入 formRecognizerService，并设置提示信息和允许的图像的最大尺寸。我们还将初始化一个二维数组来保存数独的值。</p>
<p>上传图片时将调用 <code>uploadImage</code> 方法。我们将检查上传的文件是否是一个有效的图像，并且在允许的大小限制之内。我们将使用一个 FileReader 对象来处理图像数据。readAsDataURL 方法将读取上传文件的内容。</p>
<p>当读取操作成功完成后，reader.onload 事件将会被触发。imagePreview 的值将被设置为 fileReader 对象的 ArrayBuffer 类型的返回值。</p>
<p>在 <code>GetSudokuTable</code> 方法中，我们将把图像文件附加到一个 FormData 类型的变量中。我们将调用服务的 <code>getSudokuTableFromImage</code>，并将结果绑定到游戏数组中。</p>
<p><code>sudokuSolver</code> 方法将接受数独表作为入参。然后我们使用回溯算法来解出这道数独。</p>
<h2 id="">运行演示程序</h2>
<p>按 F5 键来启动该程序。上传一张数独表的图片。点击“提取数独表”按钮，你会看到左边的表格中出现了从图像中提取出来的内容。如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/ExecDemo1.png" alt="ExecDemo1" width="600" height="400" loading="lazy"></p>
<p>点击“解数独”按钮。你可以在界面上看到数独的答案。如下图所示。</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/ExecDemo2.png" alt="ExecDemo2" width="600" height="400" loading="lazy"></p>
<h2 id=""><strong>总结</strong></h2>
<p>我们用 Angular 和 Azure 表单识别器服务创建了一个数独解题器。这个程序可以从用户上传的数独表的图片中提取数据。我们接着用回溯法解决数独问题。另外，我们使用了 Angular material 来设计程序的 UI 风格。</p>
<p>你可以从 <a href="https://github.com/AnkitSharma-007/Azure-AI-Sudoku-solver">GitHub</a> 上获取源代码，随便看看或把玩一下以加深你的理解。</p>
<h2 id="">拓展阅读</h2>
<ul>
<li><a href="https://ankitsharmablogs.com/optical-character-reader-using-angular-and-azure-computer-vision/">Optical Character Reader Using Angular And Azure Computer Vision（使用 Angular 和 Azure 计算机视觉的光学字符阅读器）</a></li>
<li><a href="https://ankitsharmablogs.com/multi-language-translator-using-blazor-and-azure-cognitive-services/">Multi-Language Translator Using Blazor And Azure Cognitive Services（使用 Blazor 和 Azure 认知服务的多语言翻译器）</a></li>
<li><a href="https://ankitsharmablogs.com/facebook-authentication-and-authorization-in-server-side-blazor-app/">Facebook Authentication And Authorization In Server-Side Blazor App（在服务器端 Blazor 应用中进行 Facebook 认证和授权）</a></li>
<li><a href="https://ankitsharmablogs.com/continuous-deployment-for-angular-app-using-heroku-and-github/">Continuous Deployment For Angular App Using Heroku And GitHub（使用 Heroku 和 GitHub 为 Angular 应用程序进行持续部署）</a></li>
<li><a href="https://ankitsharmablogs.com/going-serverless-with-blazor/">Going Serverless With Blazor（利用 Blazor 实现无服务器化）</a></li>
</ul>
<p>如果你喜欢这篇文章，请把它分享给你的朋友。你也可以在<a href="https://twitter.com/ankitsharma_007">推特</a>和<a href="https://www.linkedin.com/in/ankitsharma-007/">领英</a>上与我联系。</p>
<p>原文发表于 <a href="https://ankitsharmablogs.com/">https://ankitsharmablogs.com/</a>。</p>
<!--kg-card-end: markdown--> ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
