2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Microsoft Fabric で健康管理】Power Apps × Microsoft Fabric × Azure Open AI (AOAI) で摂取カロリーを記録・可視化する

Last updated at Posted at 2024-06-09

はじめに

カロリーはだいたいの数値が出れば OK → GPT モデルの出番ということでこんなのを作ります。

image.png

image.png

image.png

コンポーネント

  • Azure Open AI : GPT-4o モデルのAPIを提供
  • カメラアプリ: Power Apps で作成。写真の解析を AOAI にリクエスト→ Fabric に送信まで行う
  • Microsoft Fabric
    • Real-time Intelligence : 送信されたデータをリアルタイム分析用データベース(KQL データベース)に格納
    • Power BI : データベースへのクエリの発行、可視化の提供

参考にしたもの

手順

  1. Fabric の準備
  2. Power Apps カスタムコネクタ(AOAI)の作成
  3. Power Apps カスタムコネクタ(Fabricデータ送信)の作成
  4. Power Apps カメラアプリの作成
  5. データ変換とPower BI による可視化

前提条件

  • GPT-4o デプロイが利用可能な Azure Open AI Service が必要です
  • プレミアムコネクタが利用可能なPower Apps ライセンス(開発者ライセンスなど)
  • Microsoft Fabric 容量(試用版など)
  • (共有する場合)Power BI Pro

Fabric の準備

1 . チュートリアルのワークスペース作成手順 などを参考にワークスペースを作成
image.png

2 . チュートリアルのイベントハウス作成手順を参考にKQL データベースを作成します。
image.png

3 . イベントストリームを作成。名前は任意
image.png

4 . ソースにカスタムアプリを追加(名前は任意)
image.png

5 . キー情報を記録します
image.png

6 . サービスバス名はサンプルコードから取得します
image.png

7 . 以下のコードにより、tokenなどを取得します

python
#%%

import time
import urllib.parse
import hmac
import hashlib
import base64

sb_name='<記録した情報(サービスバス名)に置き換え>'
eh_name='<記録した情報(Event hub name)に置き換え>'
sas_name='<記録した情報(Shared access key Name)に置き換え>'
sas_key='<記録した情報(primary key)に置き換え>'


def get_auth_token(sb_name, eh_name, sas_name, sas_key):
    """
    Returns an authorization token dictionary 
    for making calls to Event Hubs REST API.
    """

    uri_str = f"https://{sb_name}.servicebus.windows.net/{eh_name}/" 
    uri = urllib.parse.quote_plus(uri_str)
    sas = sas_key.encode('utf-8')
    expiryNum = 60*60*24*365*3
    expiry = str(int(time.time() + expiryNum))
    string_to_sign = (uri + '\n' + expiry).encode('utf-8')
    signed_hmac_sha256 = hmac.HMAC(sas, string_to_sign, hashlib.sha256)
    signature = urllib.parse.quote(base64.b64encode(signed_hmac_sha256.digest()))
    return  {
             "uri": uri_str,
             "sb_name": sb_name,
             "eh_name": eh_name,
             "token":'SharedAccessSignature sr={}&sig={}&se={}&skn={}' \
                     .format(uri, signature, expiry, sas_name)
            }
# %%

result = get_auth_token(sb_name,eh_name,sas_name,sas_key)
print (f"result: {result}")


image.png

Power Apps カスタムコネクタ(AOAI)の作成

1 . AOAIリソースで各種情報をメモ
image.png

2 . デプロイの名前もメモしておきます
image.png

3 . https://make.powerapps.com/ にアクセスして、すべて見るに移動
image.png

4 . カスタムコネクタを選択
image.png

5 . 一から作成を選択。名前は任意
image.png

6 . ホスト名など入力。ベースURLは/openai/ 固定
image.png

7 . セキュリティ

補足:chat completion API docs 参考箇所
image.png

8 . 認証タイプとキーのラベルを設定
image.png

補足:chat completion API docs 参考箇所
image.png

9 . 新しいアクションを選択
image.png

10 . 全般はこのように入力。※説明はdocsから適宜もってきました
image.png

11 . サンプルからのインポートを選択してインポート
image.png
補足:chat completion API docs 参考箇所
image.png
image.png

12 . 応答も入れます※docs そのままだとjsonと認識してくれないので改良
image.png

json
{
  "id": "chatcmpl-6v7mkQj980V1yBec6ETrKPRqFjNw9",
  "object": "chat.completion",
  "created": 1679072642,
  "model": "gpt-35-turbo",
  "usage": {
    "prompt_tokens": 58,
    "completion_tokens": 68,
    "total_tokens": 126
  },
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Yes, other Azure AI services also support customer managed keys.\r\n                    Azure AI services offer multiple options for customers to manage keys, such as\r\n                    using Azure Key Vault, customer-managed keys in Azure Key Vault or\r\n                    customer-managed keys through Azure Storage service. This helps customers ensure\r\n                    that their data is secure and access to their services is controlled."
      },
      "finish_reason": "stop",
      "index": 0
    }
  ]
}

補足:chat completion API docs 参考箇所
image.png

13 . 作成します
image.png

14 . テストのために新しい接続を作成します。ポップアップでは、冒頭でメモした、AOAI リソースのAPIキーを入力します。なお、画面遷移してしまうので、URLもメモっておくとよいです

image.png

15 . テスト用の情報を入力。未加工の本文にして、サンプルからのインポートで使った本文を入れるとよいです。
image.png

16 . テストを実行すると、解析結果が返ってきます。AOAI用のカスタムアプリはこれでOK
image.png

参考のswaggerはこちら

image.png


swagger: '2.0'
info:
  title: 置き換えてください
  description: ''
  version: '1.0'
host: 置換えてください.openai.azure.com
basePath: /openai/
schemes:
  - https
consumes: []
produces: []
paths:
  /deployments/{deployment-id}/chat/completions:
    post:
      responses:
        default:
          description: default
          schema:
            type: object
            properties:
              id:
                type: string
                description: id
              object:
                type: string
                description: object
              created:
                type: integer
                format: int32
                description: created
              model:
                type: string
                description: model
              usage:
                type: object
                properties:
                  prompt_tokens:
                    type: integer
                    format: int32
                    description: prompt_tokens
                  completion_tokens:
                    type: integer
                    format: int32
                    description: completion_tokens
                  total_tokens:
                    type: integer
                    format: int32
                    description: total_tokens
                description: usage
              choices:
                type: array
                items:
                  type: object
                  properties:
                    message:
                      type: object
                      properties:
                        role:
                          type: string
                          description: role
                        content:
                          type: string
                          description: content
                      description: message
                    finish_reason:
                      type: string
                      description: finish_reason
                    index:
                      type: integer
                      format: int32
                      description: index
                description: choices
      summary: Chat-completions
      operationId: Chat-completions
      description: GPT-35-Turbo と GPT-4 モデルを使用して、チャット メッセージの入力候補を作成します。
      parameters:
        - name: deployment-id
          in: path
          required: true
          type: string
        - name: api-version
          in: query
          required: false
          type: string
        - name: body
          in: body
          required: false
          schema:
            type: object
            properties:
              messages:
                type: array
                items:
                  type: object
                  properties:
                    role:
                      type: string
                      description: role
                    content:
                      type: array
                      items:
                        type: object
                        properties:
                          type:
                            type: string
                            description: type
                          text:
                            type: string
                            description: text
                          image_url:
                            type: object
                            properties:
                              url:
                                type: string
                                description: url
                              detail:
                                type: string
                                description: detail
                            description: image_url
                      description: content
                description: messages
definitions: {}
parameters: {}
responses: {}
securityDefinitions:
  API KEY:
    type: apiKey
    in: header
    name: api-key
security:
  - API KEY: []
tags: []


Power Apps カスタムコネクタ(Fabricデータ送信)の作成

1 . 同様にFabric 用のカスタムコネクタも作ります。ホストやベースURLを入力※メモで記録したURIから値をもってきます
image.png

2 . セキュリティは以下のようにします
image.png

3 . 全般は任意
image.png

4 . URLと本文を入力します
image.png


<メモしたURI部>messages?timeout=60&api-version=2014-01

json

{
  "image": "test2",
  "result": ""
}

5 . 作成後、テスト画面に移動します。キーにはメモしたtoken部を利用ください。うまくいかない場合はアクションを削除して再度作成してください。

image.png

test用

{
  "image": "test2",
  "result": "[]"
}


6 . 成功すると、Fabric のイベントストリームでデータが表示されます
image.png

参考のswaggerはこちら

yaml
swagger: '2.0'
info:
  title: 置き換えてください
  description: ''
  version: '1.0'
host:  置き換えてください
basePath:  置き換えてください
schemes:
  - https
consumes: []
produces: []
paths:
  /messages:
    post:
      responses:
        default:
          description: default
          schema: {}
      summary: send-message
      description: send-message
      operationId: Send-message
      parameters:
        - name: timeout
          in: query
          required: false
          type: integer
        - name: api-version
          in: query
          required: false
          type: string
        - name: body
          in: body
          required: false
          schema:
            type: object
            properties:
              image:
                type: string
                description: image
              result:
                type: string
                description: result
definitions: {}
parameters: {}
responses: {}
securityDefinitions:
  SAS:
    type: apiKey
    in: header
    name: Authorization
security:
  - SAS: []
tags: []



Power Apps カメラアプリの作成

1 . キャンバスアプリではじめます
image.png

2 . スマホレイアウトの空のキャンバスを選択
image.png

3 . データを追加から、カスタムコネクタ2点を追加
image.png

4 . 画像の追加コントロールを追加して調整
image.png

5 . ALTキー押しながらクリックして画像を読み込ませておくとよいでしょう。
image.png

6 . ボタンを追加して、OnSelect に以下コマンドをコネクタ名だけ変更して追加。いわゆるシステムプロンプトなどは適宜調整してください。私はテキスト入力コントロールを追加してカロリーをn倍するなどの調整ができるように使っています
image.png


Set( ImageJSON, JSON( UploadedImage1.Image, JSONFormat.IncludeBinaryData ) );
ClearCollect(aoaiCollection, 
'<コネクタ名に置き換えてください>'.Chatcompletions("<デプロイ名に置換えてください>",
    {
        'api-version':"2024-02-01",
        max_tokens:800,
        messages:[
        {role:"system",content:[{type:"text",text:"あなたは画像からjson形式のデータを生成するAIです。json形式のデータのみを応答します。コードスニペットやデータ以外の情報を応答に含めてはいけません"}]},
        {role:"user",
            content:[
                {type:"text",text:"画像の中の料理のそれぞれの日本語料理名と日本語での説明、摂取カロリーを推定して。回答はシステムに取り込むため、以下のjson形式にしてください。
                [{food:"",kcal:0.0,description:""}]
                "},
                {type: "image_url",image_url:
                    {url:Substitute(ImageJSON,"""",""),detail: "auto"}
                }
            ]
        }
    ]
}).choices);
Set(resultText,Substitute(Substitute(First(aoaiCollection).message.content,"```",""),"json",""));


7 . 推論結果を確認するためのラベルを追加します。
image.png

8 . ALTキーを押しながら解析ボタンを押すとラベルに結果が表示されます。
image.png

9 . ボタンを追加して、OnSelect にFabricに送信する以下コマンドをコネクタ名だけ変更して追加。
image.png


<コネクタ名に置き換えてください>.Send-messages(
    {
        'api-version':"2014-01",
        image:Substitute(ImageJSON,"""",""),
        result: resultText,
        timeout:60}
        );
Notify(
    "Fabric にデータ送信しました",
    NotificationType.Success
);

10 . ALTキーを押しながら送信ボタンを押して、Fabric 側でも確認ができます。
image.png

これでアプリが完成しました

データ変換とPower BI による可視化

1 . Fabric イベントストリームで、あて先をKQLデータベースで選択
image.png

2 . Direct Ingestionを設定します
image.png

3 . 送信先のテーブル名を入力します
image.png

4 . データが表示されたら終了
image.png

5 . 接続が構成されます
image.png

6 . イベントハウスに移動してテーブルを見つけたら、右クリックから100行選択をクリック
image.png

7 . 自動でクエリ結果が表示されるのでKQL クエリセットとして保存
image.png

8 . KQLを置き換えます。テーブル名は適宜変更してください。クエリ結果が表示されたらPower BI レポートを構築を選択
image.png

kql

['input-food']
| extend ingest_datetime = ingestion_time()
| mv-expand result
| project 
    ingest_datetime_JST = datetime_add('hour',9,ingest_datetime),
    image,
    food = tostring(result.food),
    decription=tostring(result.description),
    kcal = todecimal(result.kcal)


9 . 簡単に折れ線だけ作成してみます。が、作りにくいので、一旦保存して移動
image.png

10 . ワークスペース設定を変えておきます。(画像表示のためなので必須ではありません。)
image.png

11 . データモデルを開きます
image.png

12 . image 列はカテゴリを画像のURLに変えておきます
image.png

13 . レポートを開き、テーブルを追加して微調整したら完成です。
image.png

参考

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?