CodeGym /Javaコース /Python SELF JA /AI APIとの連携

AI APIとの連携

Python SELF JA
レベル 24 , レッスン 4
使用可能

10.1 ChatGPT

ちょっと待って、何話してたっけ? そうだ、我々はAIによって作られた世界に生きているんだよね。では、ちょっとそれを使ってみよう。もちろん、ChatGPTから始めよう。

OpenAI API (ChatGPT) の使用例

OpenAI APIを使用するには、プラットフォームに登録して、APIキーを取得し、そのキーを使ってリクエストを認証する必要があるよ。

まずは、openaiライブラリをインストールしよう。これは公式のクライアントなんだ。


pip install openai

次に、何らかのリクエストを送信してみよう:


import openai

# あなたのOpenAI APIキー
api_key = 'YOUR_OPENAI_API_KEY'

# 認証
openai.api_key = api_key

# ChatGPTモデルへのリクエスト
response = openai.Completion.create(
    engine="text-davinci-003",
    prompt="宇宙についての面白い事実を教えて。",
    max_tokens=500
)

# レスポンスを印刷
print(response.choices[0].text.strip())

公式サイトで登録してキーを取得する必要があるよ。もし新しいユーザー(電話番号がデータベースにない場合)なら、$20のボーナスをもらえるんだ。

10.2 Google Cloud Vision API

Google Cloud Vision API では、物体認識、テキスト認識、顔認識などの画像解析機能が使用できるよ。Google Bard APIはまだ一般公開されていなくて、Google Cloud Platformを通じて認証が必要だよ。

ステップ1. まずはgoogle-cloud-visionライブラリをインストールしよう。


pip install google-cloud-vision

ステップ2. サービスアカウントキーを使用して認証を設定しよう。

画像解析のコード例:


from google.cloud import vision
import io

# クライアントの初期化
client = vision.ImageAnnotatorClient()

# 画像のロード
file_name = 'path/to/your/image.jpg'
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = vision.Image(content=content)

# オブジェクトの検出
response = client.object_localization(image=image)
objects = response.localized_object_annotations

# 検出されたオブジェクトの出力
for object_ in objects:
    print(f'Object name: {object_.name}')
    print(f'Score: {object_.score}') 

このコードは画像を認識して、検出されたオブジェクトのリストを出力するよ。これをプロジェクトに組み込んで、すごいウェブサービスやアプリを作ることもできるよ。

10.3 Microsoft Text Analytics API

Azure Cognitive Servicesは、テキストの言語判定、感情分析、キーフレーズ抽出、エンティティ認識などのAPIを提供しているよ。

テキストの感情分析は、テキストの感情的なトーン(ポジティブ、ネガティブ、またはニュートラル)を判定するプロセスだよ。顧客のフィードバックの分析や、SNSのモニタリング、特定のイベントや商品の反応を評価するのに役立つんだ。

ライブラリのインストールと認証

ステップ1. Azureライブラリをインストールしよう:


pip install azure-ai-textanalytics

ステップ2. APIキーと(endpoint)を使って認証を設定しよう。

感情分析のコード例:


from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# クライアントの初期化
endpoint = "YOUR_AZURE_ENDPOINT"
api_key = "YOUR_AZURE_API_KEY"
credential = AzureKeyCredential(api_key)
client = TextAnalyticsClient(endpoint=endpoint, credential=credential)

# 分析するテキスト
documents = ["I love programming in Python!", "I'm feeling very happy today!"]

# 感情の分析
response = client.analyze_sentiment(documents=documents)

# 結果の出力
for doc in response:
    print(f"Sentiment: {doc.sentiment}")
    print(f"Confidence Scores: {doc.confidence_scores}")

10.4 DeepAI (Text Summarization API)

DeepAIは、テキストの要約を含む様々な機械学習タスクのAPIを提供しているよ。

テキストの要約は、元のテキストの重要なアイデアや主要な内容を保持しながら、長い文章を短くまとめるプロセスだよ。長文の文書を素早く把握したり、自動的に注釈を作成したり、大量のテキスト情報を処理するのに役立つんだ。

ライブラリのインストールと認証

ステップ1. requestsライブラリをインストールしよう:


pip install requests

ステップ2. APIキーを使って認証しよう。

テキスト要約のコード例:


import requests

# あなたのDeepAI APIキー
api_key = 'YOUR_DEEPAI_API_KEY'

# 要約するテキスト
text = "Artificial intelligence (AI) is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans and animals. Leading AI textbooks define the field as the study of 'intelligent agents': any device that perceives its environment and takes actions that maximize its chance of successfully achieving its goals."

# APIへのリクエスト
response = requests.post(
    "https://api.deepai.org/api/summarization",
    data={'text': text},
    headers={'api-key': api_key}
)

# レスポンスの取得
data = response.json()

# 要約の出力
print(data['output'])

出力の例

上記のコードを正しいAPIキーで実行すると、こんな出力が得られるよ:


Artificial intelligence (AI) is the intelligence shown by machines, unlike natural intelligence in humans and 
animals. AI studies 'intelligent agents': devices that perceive their environment and act to achieve their 
goals.

この要約では、元のテキストから重要なポイントを抽出して、より短いバージョンにしているよ。正確な結果は、DeepAIのアルゴリズムやモデルのバージョンによって異なるかもしれないから注意してね。

1
Опрос
ネットワークの操作,  24 уровень,  4 лекция
недоступен
ネットワークの操作
ネットワークの操作
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION