クラウドAI開発講座進捗報告- 2週目
これの続き
やったこと
1. Azureのイメージをつかむ
紹介してもらった2つの動画を見た。
-
AzureのAI機能
- APIでなげるだけで使えるので組み込みやすそう
-
Azureでのbot開発方法
- デバックが簡単にできるのはすごい
2. ローカル環境構築
Bot Framework と Cognitive Services を使えるようにする。細かな手順はドキュメントに書かれているので省略
- Bot Framework
紹介されてたサイトではC#で環境構築してたが正直C#授業でちょっと触っただけなのでpythonで環境構築することにした。
Microsoftさんのドキュメントを参考にした。
いくつかpipするだけだから環境構築はpython最強だと思う。
Emulatorでとりあえず動くところまで確認した。
- Cognitive Services
これもpythonから呼び出せるようにする。
Microsoftさんのドキュメントを参考にした。
なんか最初に見た記事が異なるバージョンだったのでちょっと苦戦。
3. とりあえず一回なんか作ってみる
環境構築が正しくできているかの確認も含めてとりあえずbot作りました。
作ったbotはメッセージを受け取ってazureの感情分析結果に応じて固定メッセージを返すだけのbotです。
ネットワーク系のめんどくさい処理はサンプルプログラムでやってくれているので、ActivityHandlerを継承したクラスで処理書けばいいだけなので思ったより簡単そう。以下にコード。
from botbuilder.core import ActivityHandler, TurnContext
from botbuilder.schema import ChannelAccount
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential
import keys#鍵とかはいってる
class MyBot(ActivityHandler):
def __init__(self):
self.cog = CognitiveService()
super().__init__()
async def on_message_activity(self, turn_context: TurnContext):
message = turn_context.activity.text
claster = await self.cog.classtaring_sentiment_of_text(message)
if claster == "positive":
await self.send_message(turn_context,"よかったね")
elif claster == "negative":
await self.send_message(turn_context,"残念")
else:
await self.send_message(turn_context,"ふーん")
async def on_members_added_activity(
self,
members_added: ChannelAccount,
turn_context: TurnContext
):
for member_added in members_added:
if member_added.id != turn_context.activity.recipient.id:
await turn_context.send_activity("Hello and welcome!")
async def send_message(self,turn_context,s):
await turn_context.send_activity(s)
class CognitiveService():
def __init__(self):
try:
ta_credential = AzureKeyCredential(keys.cog_key)
self.text_analytics = TextAnalyticsClient(
endpoint=keys.cog_endpoint, credential=ta_credential)
except:
print("Authentication Error")
async def classtaring_sentiment_of_text(self,sentence):
doc = [sentence]
response = self.text_analytics.analyze_sentiment(documents=doc)
return response[0].sentiment
ちょっとめんどくさそうなのがCognitiveServicesの方で、APIを使う方法とライブラリを使う方法の2つがあるらしく、やや複雑。ライブラリで全部できたらいいなという感じである。
感想
日本語ドキュメントが充実しててさすがMicrosoftってなった。
ドキュメントの内容もしっかりしてる上にバージョンで切り替えれる。
ただ、紹介された記事がほとんどc#だったんだけどC#だといいことがあるのだろうか。pythonで進めちゃっていいんでしょうか、、、
来週の予定
bot作る。先にデプロイできるか試しといたほうがいいのかな、、、