顯示具有 AWS 標籤的文章。 顯示所有文章
顯示具有 AWS 標籤的文章。 顯示所有文章

7/26/2017

聊天機器人 - 快速製作在LINE上的人臉辨識應用

名人以及圖片分析 在和LINE聊天機器人之對話中


 聊天機器人(chatbot)作為人機介面,提供人類各種整合性服務是最容易產生的應用。而人臉辨識,一直都是人工智慧與數據分析的整合課題。因此,把LINE聊天機器人加上照片或人臉辨識的功能,似乎也很有趣。
用LINE QR 加小姍為好友 可以測試人臉辨識

以前,在做關於影像的實驗性質的程式時,通常會先考慮opencv。雖然opencv確實是個好工具,但是如果你的目標不是改善演算法,或甚至做出更先進的人臉辨識方式,那麼opencv會過於複雜。

在2016年底,AWS發表另一個雲端服務:Rekognition。這個服務提供了API用以辨識影像,並順便提供了幾個在應用上的api:「比較人臉」「辨別名人」「識別限制級圖案」。(文件請參考這裡)

這些api要運用的最簡單方式之一,就是使用AWS Lambda來驅動AWS內自己的API,再透過API Gateway跟外界 - 也就是chatbot整合。換言之,這仍然符合公有雲廠商(無論是AWS, google還是azure)的所謂serverless的未來方向。雖然這些公有雲廠商,其實只是為了讓客戶更難離開公有雲環境,但不可否認的是,這些api的確有用而且在初期成本也不高。

快速製作在LINE上的人臉辨識,需要幾個步驟:


(1) 對serverless的設計概念有些瞭解


請參考這裡這裡


(2) 對Line聊天機器人申請和製作,以及對AWS Lambda先有基本的瞭解。


可參考這裡這裡


(3) 在LINE webhook的event中處理image id。


在webhook的lambda程式中,特別挑出image的id。LINE的訊息傳遞給chatbot時,有分不同的type,要處理的是image type。LINE並不會真的傳圖片檔案到webhook中,他傳遞的是圖片id,透過這個id,可以用一個URL拿到圖片:


https://api.line.me/v2/bot/message/<id>/content

要取得這個圖片,當然要有Line token


(4) 讀取圖片URL並且以取得bytes


以python為例,首先以requests讀取URL,記得stream必須設為True,因為接下來需要將資料(影像的byte)直接讀取成bytearray。參考程式如下


    imageUrl = 'https://api.line.me/v2/bot/message/{}/content'.format(imageId)
    r = requests.get(imageUrl, headers=headers, stream=True)
    bArray = None
    with r.raw as data:
        f = data.read()

        bArray = bytearray(f)


(5) 使用各種AWS的Rekognition服務。

取得bytearray之後,剩下的事情就很簡單了。
以python為例,可以使用boto3 (最好是1.4.4版本)。先取得rekognition的client物件,直接使用裡面的方法(例如以下範例)。將Image參數都設定成{ 'Bytes': your_byte_array} 就可以取得分析的結果。


    rclient = boto3.client('rekognition')
    response = rclient.recognize_celebrities(
        Image = { 'Bytes':bArray }
    )

要注意的是,分析結果response是一個含有各種標籤與技術數值(例如信心程度)的dictionary物件,所有的標籤都還是英文,必須得自己轉換成中文才行。

範例中的「名人辨識」(celebrities)所查到的名字都是英文。可以利用wiki 英文api搜尋這個英文字,找到對應的中文網頁,在取得中文字。

wiki的英文api可參考這裡

(6) 存取S3之考量


如果看過AWS document應該會發現,使用recognize都可以設定image來源是S3。那麼範例為何不存取S3? 

事實上,的確可以將LINE的影像,先存在S3,然後再進行分析。然而,這樣會多了「存入」S3和取出S3的時間。並且,S3也是要收費的!影像如果只「分析一次」,那麼存在S3其實很不划算,存在Rekognition裡面更是貴。如果會反覆利用,那麼恐怕還是得存在S3中。



目前結果分享


用LINE將小姍加入好友,就可以試用一下目前LINE與AWS人臉辨識整合。


加小姍為好友 ID-> @opn2514f

加小姍為好友 Add Friend


下圖是辨識川普不同的表情,會被辨識出不同的年紀,和不同的心情。




7/12/2017

Serverless design for IoT - An example leverage AWS and GrovePi



AWS announced IOT service in about 2015 and gradually release other relative service (for example: IoT Button) for those who need to tackle with the problem on huge amount of increasing response of "The Things". And it is of course the area which cloud provider what to provide a optional solution.

To demonstrate the benefits of leveraging the serverless design and also utilize the power of AWS cloud. I build an example project combines Serverless design, AWS IoT, Respberry Pi, Grove Sensor system and GrovePI. It will provide in door air quality (office) for me if I want to know that before entering office. So that I can have an excuse to work from somewhere else? :)

In this example, a GrovePi mounts in Raspberry Pi (B+) to control Grove's Air Quality Sensor, HCHO sensor and dust sensor. As a software engineer, I assembled all these inside a paper box. See picture below.

RPi and GrovePi are inside the box. 3 sensors are out there.




Reminder: to use AWS service, the most important things is to read official document. AWS has many different services and there are too many out-of-date articles in somebody's blog. It doesn't mean that authors were wrong, it is just out-of-date. Of course, it is the same in Raspberry Pi and all other 3rd party open source library, try to read official document (or official wiki/blog) to have overall view.

The full implementation and design concerns 


(please check all the project detail in github)

(1) Grove's 3 sensors + GrovePi + Raspberry Pi

   The hardware parts. Check GrovePi's official web site to know how to put them together.

    GrovePi might be the easiest way to program Grove's system from Raspberry Pi, if you have more then 2 device in a machine. However, if you have only one sensor, then just use RPi's GPIO.

(2) AWS IoT service

   Although we didn't program anything in side the hardware, we still need to setup things in AWS IoT service. And of course, it will be better to read at least the tutorial.

Screenshot of AWS IoT Tutorial
   AWS IoT pricing model is counting by message (512bytes). At this moment, about $5 per million message. Which means about $5 per 500MB! This is much more expensive than own a EC2 service to serve device message. However, if you don't need to keep all monitoring data transit in AWS every few seconds and you need only monitoring state changes (maybe a few times per day) then a "Device Shadows" is the best for you.

   In this example, we register a "Thing" named: InDoorSensor1 and the most important thing is to have default Shadow Object as below:
{
  "desired": {
    "welcome": "aws-iot",
    "air quality": 43,
    "action": "wait"
  },
  "reported": {
    "welcome": "aws-iot",
    "action": "wait",
    "air quality": 43
  }
}

   The device will keep sync the Shadow in AWS and if the desired state change to "do", it will (a) do a one time air sensor data collection and then (b) update air quality in Shadow object (c) change to "wait" state. In sort, the Shadow and Device will sync the state (wait or do) and the state's sync is the major function provide from AWS.


(3) AWS IoT Python SDK + GrovePi Python library

AWS provides a few SDK for device, in this project, we use Python to do AWS Cloud access (no matter notification or change Shadow state)

In the Raspberry PI B+, you need to:

    (a) install AWSIoTPythonSDK
    # pip install AWSIoTPythonSDK  (also see here)

    (b) consider the protocol (MQTT vs Websocket). In some environment, the MQTT port might be block. AWS SDK provides MQTT via WebSocket which of course allow broker use port 443.

    (c) certificates: please do read AWS IoT Certificate document if you didn't have experience before

If you use Raspberry PI version B+ 2 or 3, then it will be easy to install nodejs/npm and all other fancy stuff.


(4) IoT Shadow


    The Shadow means an identify object of IoT device. This allows client to change the state of a object and then sync to IoT device. In certain scenario, it allows programmer no need to take care of network error handling or any off line case. However, you still need to fully understand what means exactly the "desired" and "reported" state.
   It is possible to edit Shadow state from AWS admin console direct for testing purpose. (you won't want to do so if you have thousands IoT device).



(5) Lambda, API Gateway


    Supposedly, an application will NOT access specific IoT device, it normally access a service and that service provides information or allow meaningful user actions.
    In this case, a lambda service is simple a python program which can (1) retrieve current state and also current air quality value (2) update state to "do". And as always, the Lambda is behind an API Gateway and which means, potentially, all other application could use this API to access necessary (filtered) information.

see the activity hand draw:



Next Project

Hopefully, I can have more budget to purchase Raspberry PI 3 and also CO2 sensor and then also gather data to draw graphic in D3. Also, I am thinking to use LINE to send air quality information to my colleague or neighborhood. 



6/20/2017

Serverless design for LINE AI Chatbot


Chatbot is one of the interesting application in AI area, it creates opportunities for enterprise to serve customers only with very low cost or even generate new revenue.
In past few years, major Instant Messaging providers allow developers to hook their service. Means as long as you have existing simple message process and response system, you can quickly interact with all kind of message channel.

Normally, a software developer will start from build a system in a server box, no matter Linux or Windows. Recently, the server might be a VM in public cloud, no matter AWS, Azure, Linode or DigitalOcean. However, a serverless design model might be a better choice.

Why Serverless?


Firstly, a serverless system will be easy to scale in/out. It doesn't mean you can't scale in/out in traditional VM in public cloud or your own datacenter. It just means that all the Lambda, no matter which provider, is actually decouple from it development environment. Supposedly, you start from one Lambda function to a few thousands same Lambda function without consider "traditional question", for example: should I shutdown VM when not in peak our, should I do some script to check if current VMs are closed to overloading?

Secondly, a serverless system will be easy to plug-in which means during the design phase, developer will be forced to think de-couple functions in small modules (bricks). Developer will also be forced NOT to rely on specific environment, even though docker is one of the solution but purely Lambda function will create much better environment-free structure.

Furthermore, it will also help to define boundary of sub system and help the future maintenance.

The Design Concerns

(1) IM independent

LINE occupies a huge market in Taiwan, about more than 90% of mobile user has LINE account. The most incredible thing is many elder people who never touch Internet before have LINE accounts! However, this design won't use any LINE specific methods. We've try the same engine in Yahoo Messenger and it also works.

(2) AWS Lambda

-- (2.1) try NOT to use context

AWS Lambda has a standard invoke parameter (event, context), The event is actually the user input when invoke Lambda function. The context is what developer might need to understand the 'environment context'. The major design concern here is try NOT to use context when possible. Because this will make you hard to move out your lambda to other public cloud environment. If you really need to have ARN or identity, try to limit environment in just one Lambda.

-- (2.2) async invoke

AWS Lambda could be invoked in 3 types: Event, RequestResponse, DryRun. The "Event" is actually asynchronous call. For any IM message receiver Lambda, you should  keep that Lambda as simple as possible to response IM webhook. Put other things via "Event" Lambda. Because most of IM provider (LINE, fb) ask a very short timeout in IM webhook. DO NOT just put http webhook and response to IM a synchronous call stack

Of course, see detail from AWS document: here.

-- (2.3) timeout/memory

AWS lambda allow to config timeout and memory size. AWS CloudWatch could see a Lambda's resource consuming. It is fine to use larger memory or setup a longer running time but developer should know WHY.

-- (2.4) quick testing

It is necessary to have your own developer server for test your Lambda function and trigger a deployment script to upload to AWS. If you didn't actually use "context", it will be very simple to have a quick test in every Lambda handler.

# in the end of your Lambda python script.
if __name__ == '__main__':

    event = {'param1':test'}
    lambda_handler(event,None)


Of course developers need other framework (unittest).

-- (2.5) deployment

As always, from a developer should have a semi-automatic way to do deployment. This is a very simple deployment script to (a) zip python files (b) upload to S3 (c) create lambda function (d) config function using S3 zip file.

(a) zip lottery.zip -r lambda_lottery.py lottery60.py
(b) aws --profile ailine s3 cp lottery.zip s3://bucket/
(c) aws --profile ailine lambda create-function --function-name lottery --runtime py
thon3.6 --role "arn:aws:" --handler lambda_lott
ery.lambda_handler --timeout 10 --code "S3Bucket=bucket,S3Key=lottery.zip"
(d) aws --profile ailine lambda update-function-code --function-name lottery --s3-bu
cket bucket --s3-key lottery.zip

-- (2.6) scheduled (cron) Lambda

Chatbot might need to do scheduled task to response to user, maybe send a regular morning call. To trigger a scheduled Lambda might be one of the major cloud-provider-dependent thing we have in Chatbot design.


(3) AWS API Gateway

AWS API Gateway is another major cloud-provider-dependent things, however, it is not hard to use other provider or have our own lab testing environment. The major concerns of API Gateway are (a) should convert IM provider's http request to a given format: which becomes a Lambda input. (b) security concerns: how to make sure only IM provider's system could access this API Gateway

(4) AWS dynamodb

Chatbot uses dynamodb to store use information and also message log. It is also pretty easy to use local JSON formate nosql.

(5) AWS elasticsearch

Chatbot leverages AWS elasticsearch to store knowledge base. It is easy to setup a developer's elasticsearch server to do lab test before deployment. The real concerns in public cloud might be the future budget:)

(6) AWS S3

Chatbot still need some static content (html or js) and S3 is the most easy way to provide public static content. It is also the place to upload latest Lambda code.


The Implementation


See: github repository 

Take a look?

This chatbot could understand and speak only Tradition Chinese, since she is a Taiwanese robot:). You need to have LINE account to chat with her.

聊天機器人小姍的Line QR 
加小姍為好友 Add Friend 









12/28/2016

數據分析從零開始 - (4) 檔案儲存



數據分析的各階段,都有可能需要儲存檔案。而資料的來源,也有可能是已經存在某處的檔案。

(非檔案儲存?參考註1)

越重要的資料,就得更重視儲存的方式。而越是大量複雜的資料,就勢必要對資料存儲做好預先的規劃。

雲端儲存 - 巨量資料


近年來流行的Cloud Storage,通常是將資料以網路上傳(註2)至某個雲端服務公司。最典型的例子是Amazon提供的S3服務。AWS S3因為使用者眾,以至於其的S3 rest http介面,甚至演變成某種標準。許多類似的服務,或者儲存廠商,會以「相符S3 rest api標準」當作重要的功能或賣點!(註3)

顯而易見,雲端儲存具有管理上的優點。理論上,不用擔心備份,擴充,網路,電力,硬體更換...等等營運上的問題。

然而,巨量資料雲端儲存也有幾個顯而易見的缺點

1. 錢:雲端儲存的費用並不便宜。單以S3為例,2016年的每1T資料光是「存著」的費用,一年就高達276美金,相當於8832台幣。這還未計算上傳下載等操作費用。倘若要進行「長期保存」其費用相當驚人。也因此雲端儲存商針對長期保存的檔案也提供比較便宜的方案。然而,仍然是某種成本。然而,自行巨量儲存也要考慮費用,特別是

2. 營運:單純僅只使用雲端儲存,對整體營運的好處有限。並且,企業還是需要自行考慮檔案的有效使用問題。

3. 移轉:儲存到雲端之後,一旦量變大,很難轉換營運商。



雲端儲存 - 少量資料

至於極少量資料,例如10G之內。無論是企業或者是個人,都可以取得幾乎免費的儲存空間。

但也因為是免費空間,不太可能保證資料不會遺失。可是非常適用於新創公司,或者SOHO族。

最好是利用兩個以上的雲端儲存服務,儲存重要的檔案。

例如:利用googledrive + yandex.disk 儲存重要的檔案。這樣幾乎可以確保檔案不會因為單一基礎建設有問題,而導致重要檔案遺失。(註4)

實際作法:

(1) 尋找適當的工具或API,用以一次性整合這兩個雲端儲存

(2) 設定自動化方式,或者撰寫自動化程式

(3) 定時執行自動化備份,同時備份兩份到不同的雲端服務

Yandex disk的範例程式(參考這裡)



自行儲存 - 巨量資料


企業組織非常有可能需要自行處理檔案儲存。無論是因為技術因素或者法律因素。

傳統上儲存會用硬體商的解決方案,近年來多了分散式檔案系統可以考慮。

自行儲存,一樣要考慮錢(費用),營運。

1. 錢(費用)

    - 硬體費用:必須考慮長期硬體維護的費用
    - 軟體費用:授權或者購買維護
    - 人的費用:必須使用假設的最大值!

2. 營運

    - 如何讓其他系統使用
    - 有問題的時候怎麼辦
    - 備份與災難復原 


傳統巨量檔案資料,是購買netapp之類的硬體解決方案,配合網路架構,讓企業的巨量資料有集中管理的地方。2000年之後,分散式檔案系統因為效率和成本的關係,慢慢變成另一個可行的選項。

早期使用分散式檔案系統管理者,要跨越比較高的技術門檻,這幾年分散式檔案系統日漸成熟,管理也越趨方便。常見的有:(這頁wiki上有詳盡的清單。)

(1) glusterfs
(2) ceph
(3) HDFS
(4) mooseFs
(5) mogilefs
(6) GridFS
(7) Lustrefs


這些分散式檔案系統各具特色,大部分都可以無償取得使用權。然而,有些需要額外的知識或技能才有辦法長期維護。

因此,如果可預期的資料量,以及資料存取技術與成本,小於硬碟技術的成長。使用分散式檔案系統不見得有利。

硬碟的技術符合約略的摩爾定律。在1996年,每1G的硬碟約127美金,2006年,每1G的硬碟價格為0.3美金,但是在2016年,每1G的硬碟價格已經小於0.03美金。(參考這裡

除了價格逐年降低之外,存取速度也是逐年增長。如果預期資料成長量並不高,其實單就更換更換同價格的硬體設備搞不好也就夠了。

然而,巨量資料的增長往往遠超過預期,尤其近年來大資料分析蔚為風潮的情況下,盡可能保留資料便於未來使用成為企業組織對資訊科技的期待。也因此,使用分散式檔案儲存的組織越來越多。

選用分散式檔案系統,必須考慮:

(1) 使用目的和環境條件
(2) 營運計畫
(3) 實際測試


考慮雖然需要詳盡,但是這些「考慮」都是為了配合實際運作。因此,按照上述的考量,擬定可以「每日」有進展的「逐步」前進的計畫,是讓分散式系統成功運作的最好作法。

舉個例子:

(1) 使用目的和環境條件:要能夠簡單擴增(scale-out),並且能利用現有已經存在的NAS/SAN,而且非常容易營運與維護。檔案不需要striping,存取效能一般即可。

(2) 營運計劃摘要:一開始預計使用12台機器,共48顆硬碟。未來一年可能擴增到20台機器,80顆以上硬碟。總資料量可能成長為120TB。僅有一位開發維運人員(devops)。

(3)實際測試:實際分別以4台VM測試過glusterfs, mogilefs, ceph, Lustrefs。其中以mogilefs最為簡單使用。





自行儲存 - 少量資料


少量檔案的儲存,仍然附著在其他系統上。例如email上的附件,版本控制系統,wiki上的附件等等。

大部分的組織,很少著重於少量資料的整體計畫。大多數僅只為「安全性」的規範。例如客戶資料不得外洩之類。實務上,完全依賴個人行為。

現在,大部分的作業系統,都已經可以對其下的檔案做全文檢索(例如mac finder),而也都支援某種程度的備份功能。




摘要



巨量資料少量資料
雲端儲存 錢, 營運, 移轉考慮 
(1) 自動化
自行儲存(1) 傳統NAS 
(2)分散式檔案系統
考慮 
(1) 傳統備份 
(2) 全文檢索 





註1:非檔案儲存有傳統的RDB(例如Mysql, Oracle), Document DB(例如Lotus Notes), 有比較新潮的nosql (HDFS, mongodb, couchbase)。 這目前不在本文的討論範圍

註2:通常是指http。不過由於ftp在2000年之前應用範圍真的太廣,所以還是有不少雲端公司會額外提供ftp介面。

註3:參考這裡 -> http://www.s3-client.com/s3-compatible-storage-solutions.html

註4:為何選擇這兩者?google當然是不用說,因為它的基礎建設相當完整。而yandex則號稱為俄羅斯的google,很明顯由於是俄羅斯最大search engine,大概不會和google採用重複的基礎建設,因此選用兩個截然不同的廠商,可以降低風險。

9/05/2016

人工智慧的淺顯應用 - 製作Facebook或Line聊天機器人





聊天機器人(chatbot)並不是什麼新鮮事,早在1950年間圖靈(註一)在提出關於人工智慧判別方式時,就提到利用文字訊息 - 因要把人和機器分開 - 來和兩個對象聊天,其中一個對象是人,另一個對象是電腦,如果一個正常人在聊天的過程無法區分這兩者誰是電腦,誰是人,則可判別這電腦程式,是真正擁有智慧。

要達到這個目的難上加難,在wiki上可以看到目前僅有在2014年一個名為Eugene Goostman的聊天程式通過這個測試。

目前可取得的人工智慧演算法或相關技術都沒有太驚人的發展。然而,由於網路上的資料取得越來越容易,電腦執行速度越來越快,以致於不需要有驚人的技術能力,也不需要有對人工智慧會不會變成奴役人類的電影劇情的深思,就可以開發出有意義的應用。


Facebook聊天機器人也是其中之一。

商家,企業,甚至某些個人都擁有FB page (粉絲頁 專頁),而從2015年開始,facebook開始出現具有固定反應或者訊息回應的聊天程式。不過台灣似乎比較少見非特定用途的聊天機器人,因此我們就做了一個在粉絲頁上。參考下圖:


https://www.facebook.com/sandy4ai/ 具有人工智慧聊天的粉絲頁

這個聊天機器人會回應你的訊息,根據她內建的知識庫和基本的語意分析,會回應你訊息。當然,她也會慢慢學習對話,這個聊天程式並不會需要額外的facebook權限,因此她沒有太多額外的功能。下圖是聊天實況範例:



和具有人工智慧聊天的粉絲頁聊天


Line在今年(2016)也開放bot api,作法和Facebook幾乎很雷同。不過雖然都是webhook,他們的api實際傳遞內容當然完全不一樣。

Facebook/Line 聊天機器人的可能應用:


1. 基本客戶問題:

企業組織在網路上最常「被」查。查詢營業時間,查詢電話,查詢服務項目等等。在台灣,這幾年用facebook來做生意來越頻繁,而聊天機器可以提供24x7的基本回答問題服務。

2. 促銷活動:

聊天機器人在某些權限下,可以主動傳遞訊息,或者貼文給facebook使用者。這和一般廣告貼文有些許不同,因為貼文之後,使用者可以持續和貼文者 - 也就是聊天機器人互動。

3. 例行客戶服務:

預約預定,提醒預約,服務調查,生日賀卡貼文等等。




如何製作Facebook臉書聊天機器人:



1.摘要步驟

  (1) 到AWS開設帳號。 開發過程會用到Lambda, API Gateway, elasticsearch, s3 cloudwatch 等服務。

  (2) 到facebook建立facebook app。(簡稱 fb app)

  (3) 新增並撰寫基本的Lambda 以回應 之後fb app webhook時的GET驗證。

  (4) 新增撰寫基本的Lambda 以用在 接下fb app message hook回應

  (5) 新增 API Gateway 的GET/POST,對應到Lambda

  (6) 設定fb app 的webhook 對應到API Gateway的URL
  
  (7) 讓fb app的設定頁verify(基本上就是http  GET) API  Gateway

  (8) 讓fb app設定頁訂閱message 並記得在lambda程式回覆訊息時使用page token

  (9) 此時可以進行知識庫的連結,在AWS建立elasticsearch並且匯入經過程式處理的資料,這裡我們以台灣e院資料為範例。

   (10) 修改lambda程式,讓使用者的訊息,在elasticsearch查訊相關訊息,並且回復給原送訊息者

   (11) 至此完成,其結果大致如下圖:



2. 詳細步驟:

    ....<待續>...


如何製作Line聊天機器人:


1.摘要步驟

  (1) 到AWS開設帳號。 開發過程會用到Lambda, API Gateway, elasticsearch, s3 cloudwatch 等服務。

  (2) 到line developer建立帳號以及channel。

  (3) 新增並撰寫基本的Lambda 和 api gateway 用以回應之後在line的channel上link時的驗證。Line的api基本上只用到POST

  (4) 將自己的line帳號 加入剛剛自己增加的channel。就是設好友的意思,這樣才能測試

  (5) 將line channel所需要的api key, secret以及token設定在lambda 要傳回給line bot api的地方。

  (6) 此時可以進行知識庫的連結,在AWS建立elasticsearch並且匯入經過程式處理的資料,這裡我們以台灣e院資料為範例。

   (7) 修改lambda程式,讓使用者的訊息,在elasticsearch查訊相關訊息,並且回復給原送訊息者

   (8) 至此完成,其結果大致如下圖:


2. 詳細步驟:


    ....<待續>...



參考: https://www.facebook.com/sandy4ai/ 

 註一:Turing 就是電影模仿遊戲的主角
 註二:詳細步驟還沒有時間寫...反正不見得有人需要:)