建立不良文字過濾服務¶
身為書店老闆,您的目標是在顧客提交新的負面評論時,立即在 Slack 頻道中收到通知。透過利用 Knative Function,您可以設定一個包含簡單不良文字過濾服務的無伺服器函式,以判斷文字是否包含任何仇恨/侮辱性言論。
如果您遇到任何困難,請在此處查看解決方案。
我們將學習哪些 Knative 功能?¶
- 使用 Knative Function 部署服務的簡易性,並使其由 Knative Serving 管理,這讓您能夠將服務自動縮放至零,並向上擴展以處理需求。
最終交付成果是什麼樣子?¶
一個正在執行的無伺服器 Knative Function,其中包含一個 Python 應用程式,該應用程式接收新的評論作為 CloudEvent,並傳回結果,告知您的輸入文字是否包含任何不當語言。結果將以 CloudEvent 的形式傳回。
資訊
我們使用 profanity_check
函式庫來偵測文字中的不良文字。這是一個開放原始碼函式庫。請在此處查看免責聲明。結果可能不是 100% 準確。
函式的輸出只會來自
- good
- bad
實作¶
此過程很簡單
- 首先,使用
func create
命令來產生您的程式碼範本。 - 接下來,將您獨特的程式碼併入此範本中。
- 最後,執行
func deploy
,將您的應用程式無縫部署到 Kubernetes 叢集。
此工作流程確保從 Knative Functions 生態系統中的開發到部署的順利轉換。
步驟 1:建立 Knative Function 範本¶
func deploy -b=s2i -v
驗證
檔案樹狀結構會如下所示
/start/bad-word-filter
├── func.yaml
├── .funcignore
├── .gitignore
├── requirements.txt
├── app.sh
├── test_func.py
├── README.md
└── Procfile
└── func.py
步驟 2:將產生的程式碼替換為不良文字過濾邏輯¶
bad-word-filter/func.py
是包含函式程式碼的檔案。您可以將產生的程式碼替換為不良文字過濾邏輯。您可以使用以下程式碼作為起點
bad-word-filter/func.py
from parliament import Context
from profanity_check import predict
from cloudevents.http import CloudEvent
# The function to convert the bad word filter result into a CloudEvent
def create_cloud_event(inputText, data):
attributes = {
"type": "new-review-comment",
"source": "book-review-broker",
"datacontenttype": "application/json",
"badwordfilter": data,
}
# Put the bad word filter result into a dictionary
data = {"reviewText": inputText, "badWordResult": data}
# Create a CloudEvent object
event = CloudEvent(attributes, data)
return event
def inappropriate_language_filter(text):
profanity_result = predict([text["reviewText"]])
result = "good"
if profanity_result[0] == 1:
result = "bad"
profanity_event = create_cloud_event(text["reviewText"], result)
return profanity_event
def main(context: Context):
"""
Function template
The context parameter contains the Flask request object and any
CloudEvent received with the request.
"""
print("Received CloudEvent: ", context.cloud_event)
# Add your business logic here
return inappropriate_language_filter(context.cloud_event.data)
步驟 3:設定相依性¶
bad-word-filter/requirements.txt
的內容
bad-word-filter/requirements.txt
parliament-functions==0.1.0
alt-profanity-check==1.4.1.post1
cloudevents==1.10.1
步驟 4:將函式部署到叢集¶
注意
執行下列命令時,請輸入 /bad-word-filter
。
func deploy -b=s2i -v
驗證
預期會看到以下訊息
Function deployed in namespace "default" and exposed at URL:
http://bad-word-filter.default.svc.cluster.local
驗證¶
func invoke -f=cloudevent --data='{"reviewText":"I love Knative so much"}' -v
驗證
預期會收到 CloudEvent 回應
Context Attributes,
specversion: 1.0
type: new-review-comment
source: book-review-broker
id: ebbcd761-3a78-4c44-92e3-de575d1f2d38
time: 2024-05-27T04:44:07.549303Z
datacontenttype: application/json
Extensions,
badwordfilter: good
Data,
{
"reviewText": "I love Knative so much",
"badWordResult": "good"
}
如果您看到回應,則表示函式已成功執行。
下一步¶
在本教學課程中,您學習了如何使用 Knative 建立一個無伺服器函式,以針對簡單服務來偵測文字中不適當的語言。
接下來,我們將學習如何使用 Knative Sequence 來連接 2 個 ML 工作流程,並確保它們按您想要的順序執行。