创建脏话过滤器服务¶
作为一家书店的老板,您希望在客户提交新的负面评价评论时在 Slack 通道中收到即时通知。通过利用 Knative Function,您可以设置一个无服务器函数,其中包含一个简单的脏话过滤器服务,以判断文本是否包含任何仇恨/侮辱性言论。
如果您遇到任何问题,请查看此处的解决方案。
我们将学习哪些 Knative 特性?¶
- 使用 Knative Function 部署您的服务是多么容易,并且让 Knative Serving 管理它,这使您能够将您的服务自动缩放到零,并根据需要进行扩展。
最终的可交付成果是什么样的?¶
一个运行的无服务器 Knative Function,其中包含一个 Python 应用程序,它接收新的评论评论作为 CloudEvent 并返回结果,该结果告诉您您的输入文本是否包含任何不恰当的语言。结果作为 CloudEvent 返回。
信息
我们使用 profanity_check
库来检测文本中的脏话。这是一个开源库。请查看此处的免责声明。结果可能并非 100% 准确。
函数的输出将仅来自
- 好
- 坏
实施¶
该过程很简单
- 首先利用
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 检测文本中的不当语言。
接下来,我们将学习如何使用 Knative Sequence 连接两个 ML 工作流,并确保它们按照您想要的顺序执行。