整合多個沉浸式閱讀程式資源

在概觀 ,您已瞭解沉浸式閱讀程式是什麼,以及如何實作經過實證的技術,以改善語言學習者、新興讀者和具有學習差異的學生閱讀理解。 在快速入門 ,您已瞭解如何搭配單一資源使用 沉浸式閱讀程式。 本教學課程涵蓋如何在相同的應用程式中整合多個沉浸式閱讀程式資源。 在本教學課程中,您會了解如何:

  • 在現有的資源群組下建立多個沉浸式閱讀程式資源
  • 使用多個資源啟動沉浸式閱讀程式

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

必要條件

  • 請遵循快速入門 來建立 Web 應用程式,以使用 NodeJS 啟動沉浸式閱讀程式。 在本快速入門中,您會設定單一沉浸式閱讀程式資源。 我們將在本教學課程中建置此基礎。

建立沉浸式閱讀程式資源

請遵循 這些指示 來建立每個沉浸式閱讀程式資源。 Create-ImmersiveReaderResource 腳本具有 ResourceNameResourceSubdomainResourceLocation 作為參數。 對於要建立的每個資源而言,這些應該是唯一的。 其餘參數應該與您設定第一個沉浸式閱讀程式資源時所使用的參數相同。 如此一來,每個資源都可以連結至相同的 Azure 資源群組和 Microsoft Entra 應用程式。

下列範例示範如何建立兩個資源,一個在 WestUS 中,另一個在 EastUS。 請注意 、 ResourceSubdomainResourceLocation 的唯一 ResourceName 值。

Create-ImmersiveReaderResource
  -SubscriptionName <SUBSCRIPTION_NAME> `
  -ResourceName Resource_name_wus `
  -ResourceSubdomain resource-subdomain-wus `
  -ResourceSKU <RESOURCE_SKU> `
  -ResourceLocation westus `
  -ResourceGroupName <RESOURCE_GROUP_NAME> `
  -ResourceGroupLocation <RESOURCE_GROUP_LOCATION> `
  -AADAppDisplayName <AAD_APP_DISPLAY_NAME> `
  -AADAppIdentifierUri <AAD_APP_IDENTIFIER_URI> `
  -AADAppClientSecret <AAD_APP_CLIENT_SECRET>

Create-ImmersiveReaderResource
  -SubscriptionName <SUBSCRIPTION_NAME> `
  -ResourceName Resource_name_eus `
  -ResourceSubdomain resource-subdomain-eus `
  -ResourceSKU <RESOURCE_SKU> `
  -ResourceLocation eastus `
  -ResourceGroupName <RESOURCE_GROUP_NAME> `
  -ResourceGroupLocation <RESOURCE_GROUP_LOCATION> `
  -AADAppDisplayName <AAD_APP_DISPLAY_NAME> `
  -AADAppIdentifierUri <AAD_APP_IDENTIFIER_URI> `
  -AADAppClientSecret <AAD_APP_CLIENT_SECRET>

將資源新增至環境組態

在快速入門中,您已建立包含 、 ClientIdClientSecretSubdomain 參數的環境組態檔 TenantId 。 由於所有資源都使用相同的 Microsoft Entra 應用程式,因此我們可以針對 TenantIdClientIdClientSecret 使用相同的值。 唯一需要進行的變更是列出每個資源的每個子域。

新的 .env 檔案現在看起來應該如下所示:

TENANT_ID={YOUR_TENANT_ID}
CLIENT_ID={YOUR_CLIENT_ID}
CLIENT_SECRET={YOUR_CLIENT_SECRET}
SUBDOMAIN_WUS={YOUR_WESTUS_SUBDOMAIN}
SUBDOMAIN_EUS={YOUR_EASTUS_SUBDOMAIN}

請務必不要將此檔案認可至原始檔控制,因為它包含不應公開的秘密。

接下來,我們將修改我們建立的 routes\index.js 檔案,以支援我們的多個資源。 以下列程式碼取代其內容。

如同先前,此程式碼會建立 API 端點,以使用您的服務主體密碼取得 Microsoft Entra 驗證權杖。 這次,它可讓使用者指定資源位置,並將它當做查詢參數傳入。 然後,它會傳回物件,其中包含標記和對應的子域。

var express = require('express');
var router = express.Router();
var request = require('request');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/GetTokenAndSubdomain', function(req, res) {
    try {
        request.post({
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            url: `https://login.windows.net/${process.env.TENANT_ID}/oauth2/token`,
            form: {
                grant_type: 'client_credentials',
                client_id: process.env.CLIENT_ID,
                client_secret: process.env.CLIENT_SECRET,
                resource: 'https://cognitiveservices.azure.com/'
            }
        },
        function(err, resp, tokenResult) {
            if (err) {
                console.log(err);
                return res.status(500).send('CogSvcs IssueToken error');
            }

            var tokenResultParsed = JSON.parse(tokenResult);

            if (tokenResultParsed.error) {
                console.log(tokenResult);
                return res.send({error :  "Unable to acquire Azure AD token. Check the debugger for more information."})
            }

            var token = tokenResultParsed.access_token;

            var subdomain = "";
            var region = req.query && req.query.region;
            switch (region) {
                case "eus":
                    subdomain = process.env.SUBDOMAIN_EUS
                    break;
                case "wus":
                default:
                    subdomain = process.env.SUBDOMAIN_WUS
            }

            return res.send({token, subdomain});
        });
    } catch (err) {
        console.log(err);
        return res.status(500).send('CogSvcs IssueToken error');
    }
});

module.exports = router;

getimmersivereaderlaunchparams API 端點應受到某種形式的驗證保護,以防止 未經授權的使用者取得權杖以用於您的沉浸式閱讀程式服務和計費;該工作超出本教學課程的範圍。

使用範例內容啟動沉浸式閱讀程式

  1. 開啟 views\index.pug ,並以下列程式碼取代其內容。 此程式碼會以一些範例內容填入頁面,並新增兩個按鈕來啟動沉浸式閱讀程式。 一個用於啟動 EastUS 資源的沉浸式閱讀程式,另一個用於啟動 WestUS 資源。

    doctype html
    html
        head
            title Immersive Reader Quickstart Node.js
    
            link(rel='stylesheet', href='https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css')
    
            // A polyfill for Promise is needed for IE11 support.
            script(src='https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.min.js')
    
            script(src='https://ircdname.azureedge.net/immersivereadersdk/immersive-reader-sdk.1.2.0.js')
            script(src='https://code.jquery.com/jquery-3.3.1.min.js')
    
            style(type="text/css").
                .immersive-reader-button {
                background-color: white;
                margin-top: 5px;
                border: 1px solid black;
                float: right;
                }
        body
            div(class="container")
                button(class="immersive-reader-button" data-button-style="icon" data-locale="en" onclick='handleLaunchImmersiveReader("wus")') WestUS Immersive Reader
                button(class="immersive-reader-button" data-button-style="icon" data-locale="en" onclick='handleLaunchImmersiveReader("eus")') EastUS Immersive Reader
    
                h1(id="ir-title") About Immersive Reader
                div(id="ir-content" lang="en-us")
                p Immersive Reader is a tool that implements proven techniques to improve reading comprehension for emerging readers, language learners, and people with learning differences. The Immersive Reader is designed to make reading more accessible for everyone. The Immersive Reader
    
                    ul
                        li Shows content in a minimal reading view
                        li Displays pictures of commonly used words
                        li Highlights nouns, verbs, adjectives, and adverbs
                        li Reads your content out loud to you
                        li Translates your content into another language
                        li Breaks down words into syllables
    
                h3 The Immersive Reader is available in many languages.
    
                p(lang="es-es") El Lector inmersivo está disponible en varios idiomas.
                p(lang="zh-cn") 沉浸式阅读器支持许多语言
                p(lang="de-de") Der plastische Reader ist in vielen Sprachen verfügbar.
                p(lang="ar-eg" dir="rtl" style="text-align:right") يتوفر \"القارئ الشامل\" في العديد من اللغات.
    
    script(type="text/javascript").
    function getTokenAndSubdomainAsync(region) {
            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: "/GetTokenAndSubdomain",
                    type: "GET",
                    data: {
                        region: region
                    },
                    success: function (data) {
                        if (data.error) {
                            reject(data.error);
                        } else {
                            resolve(data);
                        }
                    },
                    error: function (err) {
                        reject(err);
                    }
                });
            });
        }
    
        function handleLaunchImmersiveReader(region) {
            getTokenAndSubdomainAsync(region)
                .then(function (response) {
                    const token = response["token"];
                    const subdomain = response["subdomain"];
                    // Learn more about chunk usage and supported MIME types https://learn.microsoft.com/azure/ai-services/immersive-reader/reference#chunk
                    const data = {
                        title: $("#ir-title").text(),
                        chunks: [{
                            content: $("#ir-content").html(),
                            mimeType: "text/html"
                        }]
                    };
                    // Learn more about options https://learn.microsoft.com/azure/ai-services/immersive-reader/reference#options
                    const options = {
                        "onExit": exitCallback,
                        "uiZIndex": 2000
                    };
                    ImmersiveReader.launchAsync(token, subdomain, data, options)
                        .catch(function (error) {
                            alert("Error in launching the Immersive Reader. Check the console.");
                            console.log(error);
                        });
                })
                .catch(function (error) {
                    alert("Error in getting the Immersive Reader token and subdomain. Check the console.");
                    console.log(error);
                });
        }
    
        function exitCallback() {
            console.log("This is the callback function. It is executed when the Immersive Reader closes.");
        }
    
  2. 我們的 Web 應用程式現已就緒。 執行下列命令以啟動應用程式:

    npm start
    
  3. 請開啟瀏覽器,然後瀏覽至 http://localhost:3000。 您應該會在頁面上看到上述內容。 選取 [EastUS 沉浸式閱讀程式] 按鈕或 [WestUS 沉浸式閱讀程式] 按鈕,以使用這些個別的資源來啟動沈浸式閱讀程式。

下一步