2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Amazon Bedrock でマルチモーダルAI分析アプリを作成

Posted at

はじめに

最近こちらの本を購入し、Amazon Bedrock の学習に励んでおります。まだ読み始めたばかりですが、とてもおすすめです。

そういえば、マルチモーダル生成AIアプリを作成したことがなかったので、以下の Git コードを元に(ありがとうございます) Streamlit でアプリを作成してみました。

ドキュメント

サンプルコード

import streamlit as st
import base64
import json
import boto3

def main():
    st.title("マルチモーダルAI分析アプリ")
    
    # サイドバーでプロンプトのテンプレートを選択
    prompt_template = st.sidebar.selectbox(
        "プロンプトテンプレートを選択",
        ["画像の説明", "画像の分析", "カスタム"],
        index=0
    )
    
    # テンプレートに基づいてデフォルトのプロンプトを設定
    default_prompts = {
        "画像の説明": "この画像は何?日本語で説明して",
        "画像の分析": "この画像を詳しく分析して、以下の点について日本語で説明してください:\n1. 主な被写体\n2. 色使いや構図\n3. 画像から感じる雰囲気や印象",
        "カスタム": ""
    }
    
    # プロンプト入力エリア
    user_prompt = st.text_area(
        "プロンプトを入力してください",
        value=default_prompts[prompt_template],
        height=150
    )
    
    # ファイルアップローダーの作成
    uploaded_file = st.file_uploader("画像をアップロードしてください", type=['png', 'jpg', 'jpeg'])
    
    if uploaded_file is not None:
        # 画像の表示
        st.image(uploaded_file, caption='アップロードされた画像', use_column_width=True)
        
        # 詳細設定の展開オプション
        with st.expander("詳細設定"):
            max_tokens = st.slider("最大トークン数", 
                                 min_value=1000, 
                                 max_value=4096, 
                                 value=4096, 
                                 step=100)
            temperature = st.slider("温度 (創造性)", 
                                  min_value=0.0, 
                                  max_value=1.0, 
                                  value=0.7, 
                                  step=0.1)
        
        # 分析ボタン
        if st.button('分析開始'):
            if not user_prompt.strip():
                st.warning("プロンプトを入力してください")
                return
                
            with st.spinner('分析中...'):
                try:
                    # 画像データの変換
                    image_data = base64.b64encode(uploaded_file.getvalue()).decode("utf-8")
                    
                    # Bedrockクライアントの作成
                    bedrock_runtime = boto3.client("bedrock-runtime")
                    
                    # プロンプトの設定
                    prompt_config = {
                        "anthropic_version": "bedrock-2023-05-31",
                        "max_tokens": max_tokens,
                        "temperature": temperature,
                        "messages": [
                            {
                                "role": "user",
                                "content": [
                                    {
                                        "type": "image",
                                        "source": {
                                            "type": "base64",
                                            "media_type": f"image/{uploaded_file.type.split('/')[-1]}",
                                            "data": image_data,
                                        },
                                    },
                                    {"type": "text", "text": user_prompt},
                                ],
                            }
                        ],
                    }
                    
                    # Bedrock API呼び出し
                    response = bedrock_runtime.invoke_model(
                        body=json.dumps(prompt_config),
                        modelId="anthropic.claude-3-5-sonnet-20240620-v1:0",
                        accept="application/json",
                        contentType="application/json"
                    )
                    
                    # レスポンスの処理
                    response_body = json.loads(response.get("body").read())
                    results = response_body.get("content")[0].get("text")
                    
                    # 結果の表示
                    st.success("分析が完了しました!")
                    st.write("### 分析結果")
                    st.write(results)
                    
                except Exception as e:
                    st.error(f"エラーが発生しました: {str(e)}")

if __name__ == "__main__":
    main()

content配列の中に複数の要素を含めることができ、画像はtype": "image"として、テキストはtype": "text"として渡しているんですね。

実行結果

画像は前の記事で利用したこちらの記事で作成したものを利用しました。

スクリーンショット 2025-02-07 20.36.40.png
スクリーンショット 2025-02-07 20.36.59.png
スクリーンショット 2025-02-07 20.41.13.png
スクリーンショット 2025-02-07 20.43.10.png

おーいいい感じです。

2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?