使用 AWS SDK for Kotlin 调用 Amazon Comprehend:六个 NLP 检测与文档分类实战示例
示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载导读本文以 kotlin/services/comprehend 目录下的官方代码示例为主体系统讲解如何用 AWS SDK for Kotlin 调用 Amazon Comprehend 的自然语言处理NLP能力涵盖命名实体识别DetectEntities、关键短语提取DetectKeyPhrases、语言检测DetectLanguage、情感分析DetectSentiment、语法解析DetectSyntax以及自定义文档分类器的训练DocumentClassifierDemo。读完本文你将掌握 Comprehend 五大实时分析 API 的 Kotlin 调用范式、ComprehendClient的创建与资源管理方式以及训练自定义文档分类器所需的 IAM 角色、S3 数据与完整参数配置并了解如何通过 JUnit 5 验证这些代码。Amazon Comprehend 与 SDK for Kotlin 概览Amazon Comprehend 是 AWS 提供的自然语言处理服务使用 NLP 从文档内容中提取洞察且无需任何特殊预处理——直接传入纯文本即可获得结构化分析结果。在 kotlin/services/comprehend 目录中官方通过六个独立示例演示了该服务与 AWS SDK for Kotlin 的集成方式DetectEntities—— 从指定文本中识别命名实体人名、地名、组织、日期等DetectKeyPhrases—— 检测文本中的关键短语DetectLanguage—— 检测文本的主导语言DetectSentiment—— 检测文本的情感倾向正面、负面、中性、混合DetectSyntax—— 检测文本的语法结构词性标注DocumentClassifierDemo—— 训练一个自定义文档分类器这些示例均位于 kotlin/services/comprehend/src/main/kotlin/com/kotlin/comprehend 下每个文件都是一个带suspend fun main的可独立运行程序。示例文本统一采用一段关于西雅图及 Amazon 公司的英文介绍便于读者直观对比不同 API 的返回差异。环境准备与项目配置前置条件运行这些示例前需要完成两项基础配置详见 kotlin/README.mdAWS 账户与凭证拥有一个 AWS 账户并按 AWS SDK for Kotlin Developer Guide 配置默认凭证与默认 AWS 区域Gradle 开发环境使用 Gradle 构建 AWS SDK for Kotlin 项目参考 Get started with the AWS SDK for Kotlin。Gradle 依赖声明以 build.gradle.kts 为例项目通过 BOMBill of Materials统一管理 AWS SDK 版本dependencies { implementation(platform(aws.sdk.kotlin:bom:1.5.63)) implementation(aws.sdk.kotlin:comprehend) implementation(aws.sdk.kotlin:secretsmanager) implementation(aws.smithy.kotlin:http-client-engine-okhttp) implementation(aws.smithy.kotlin:http-client-engine-crt) implementation(com.google.code.gson:gson:2.10) testImplementation(org.junit.jupiter:junit-jupiter:5.9.0) implementation(org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4) implementation(org.slf4j:slf4j-api:2.0.15) implementation(org.slf4j:slf4j-simple:2.0.15) }其中关键点说明aws.sdk.kotlin:comprehend提供 Comprehend 客户端与请求模型aws.sdk.kotlin:secretsmanager仅在 JUnit 测试中用于从 AWS Secrets Manager 读取测试配置kotlinx-coroutines-core必不可少——SDK for Kotlin 的所有 API 均为挂起函数suspend必须运行在协程上下文中项目要求 Java 17sourceCompatibility JavaVersion.VERSION_17并启用 ktlint 代码风格检查测试使用 JUnit 5useJUnitPlatform()与 ComprehendKotlinTest.kt 中的org.junit.jupiter注解一致。客户端创建模式ComprehendClient六个示例在客户端创建上遵循完全一致的范式可归纳为两种写法挂起函数内的显式main调用DetectEntities、DetectKeyPhrases、DetectSentiment、DetectSyntax 等ComprehendClient.fromEnvironment { region us-east-1 }.use { comClient - // 调用各检测 API }测试类中的常规构造ComprehendKotlinTest.ktval secretClient SecretsManagerClient { region us-east-1 }两种方式的核心语义相同fromEnvironment从环境变量/凭证链自动加载 AWS 凭证无需在代码中硬编码 Access Key显式指定region us-east-1而 kotlin/README.md 亦提醒示例代码并未在全部 AWS 区域测试部分服务仅特定区域可用.use { }是 Kotlin 的Closeable扩展确保客户端在使用完毕后自动关闭底层 HTTP 连接避免资源泄漏。所有检测 API 均为suspend挂起函数因此调用点必须位于协程作用域内示例中直接放在suspend fun main中。五大实时分析 API 实战Comprehend 的实时分析 API 均以构建请求 → 调用客户端 → 遍历响应三步完成。以下逐一展开。DetectEntities命名实体识别DetectEntities.kt 演示如何从文本中提取命名实体suspend fun detectAllEntities(textVal: String) { val request DetectEntitiesRequest { text textVal languageCode LanguageCode.fromValue(en) } ComprehendClient.fromEnvironment { region us-east-1 }.use { comClient - val response comClient.detectEntities(request) response.entities?.forEach { entity - println(Entity text is ${entity.text}) } } }实现要点DetectEntitiesRequest中text为必填的待分析文本languageCode用LanguageCode.fromValue(en)指定文本语言为英语响应response.entities是一个实体列表每个entity除text实体文本外通常还携带type实体类型如 PERSON、LOCATION、ORGANIZATION、DATE与score置信度分数示例中仅打印text字段。DetectKeyPhrases关键短语检测DetectKeyPhrases.kt 与实体识别结构几乎一致仅请求模型与响应字段不同suspend fun detectAllKeyPhrases(textVal: String) { val request DetectKeyPhrasesRequest { text textVal languageCode LanguageCode.fromValue(en) } ComprehendClient.fromEnvironment { region us-east-1 }.use { comClient - val response comClient.detectKeyPhrases(request) response.keyPhrases?.forEach { phrase - println(Key phrase text is ${phrase.text}) } } }关键短语是文本中承载主要信息量的词组如示例文本中的 Seattle、Jeff Bezos、Starbucks and Boeing。response.keyPhrases中每个phrase同样包含text、score以及可选的beginOffset/endOffset在原文本中的起止位置。DetectLanguage语言检测DetectLanguage.kt 与前两者最大的不同是无需指定languageCode——语言检测的输入语言本就是未知的这正是该 API 的意义所在。示例输入为法语文本suspend fun detectTheDominantLanguage(textVal: String) { val request DetectDominantLanguageRequest { text textVal } ComprehendClient.fromEnvironment { region us-east-1 }.use { comClient - val response comClient.detectDominantLanguage(request) response.languages?.forEach { lang - println(Language is ${lang.languageCode}) } } }示例中main传入Il pleut aujourdhui à Seattle法语而响应response.languages会按置信度排序返回多个候选语言及其scorelanguageCode为 ISO 639-1 标准代码如fr、en。若文本为多语言混合可结合languageCode与score字段进一步决策。DetectSentiment情感分析DetectSentiment.kt 返回文本的整体情感倾向及其细粒度评分suspend fun detectSentiments(textVal: String) { val request DetectSentimentRequest { text textVal languageCode LanguageCode.fromValue(en) } ComprehendClient.fromEnvironment { region us-east-1 }.use { comClient - val resp comClient.detectSentiment(request) println(The Neutral value is ${resp.sentimentScore?.neutral}) } }实现要点resp.sentiment字段给出总体情感标签Positive / Negative / Neutral / Mixedresp.sentimentScore是一个四元评分结构包含positive、negative、neutral、mixed四个 0~1 之间的浮点值四者之和为 1示例仅打印neutral值作为演示实际应用中可据此量化情感强度例如当positive大于阈值时判定为正面内容。DetectSyntax语法解析DetectSyntax.kt 对文本进行词性标注与句法分析suspend fun detectAllSyntax(textVal: String) { val request DetectSyntaxRequest { text textVal languageCode SyntaxLanguageCode.fromValue(en) } ComprehendClient.fromEnvironment { region us-east-1 }.use { comClient - val response comClient.detectSyntax(request) response.syntaxTokens?.forEach { token - println(Language is ${token.text}) println(Part of speech is ${token.partOfSpeech}) } } }注意此处与前几个 API 的类型差异DetectSyntaxRequest的languageCode使用专门的SyntaxLanguageCode枚举而非LanguageCode因为语法分析支持的语言集合与通用分析不同。响应response.syntaxTokens将文本拆分为词元列表每个token包含text词元文本partOfSpeech词性标注如 NOUN、VERB、ADJ、DET 等beginOffset/endOffset词元在原文中的位置tokenId词元序号。DocumentClassifierDemo训练自定义文档分类器与前五个即时分析 API 不同DocumentClassifierDemo.kt 演示的是创建异步训练任务用于训练一个自定义文档分类模型。由于训练是耗时操作该示例需要三个命令行参数Usage: dataAccessRoleArn s3Uri documentClassifierName Where: dataAccessRoleArn - The ARN value of the role used for this operation. s3Uri - The Amazon S3 bucket that contains the CSV file. documentClassifierName - The name of the document classifier.入口函数先校验参数数量不足 3 个时打印用法说明并以exitProcess(0)退出再调用核心函数suspend fun createDocumentClassifier( dataAccessRoleArnVal: String, s3UriVal: String, documentClassifierNameVal: String, ) { val config DocumentClassifierInputDataConfig { s3Uri s3UriVal } val request CreateDocumentClassifierRequest { documentClassifierName documentClassifierNameVal dataAccessRoleArn dataAccessRoleArnVal languageCode LanguageCode.fromValue(en) inputDataConfig config } ComprehendClient.fromEnvironment { region us-east-1 }.use { comClient - val resp comClient.createDocumentClassifier(request) val documentClassifierArn resp.documentClassifierArn println(Document Classifier ARN is $documentClassifierArn) } }三个参数的核心作用dataAccessRoleArnIAM 角色的 ARN。该角色必须被授予对指定 S3 桶的读取权限并且其信任策略允许 Comprehend 服务代入AssumeRole。这是训练任务能够读取训练数据的权限基础属最小权限原则least privilege的典型落地场景s3Uri指向 S3 桶中 CSV 训练数据的 URI。CSV 需按 Comprehend 规定的格式组织第一列为文本第二列为类别标签documentClassifierName分类器名称用于后续查询或删除该训练任务。请求模型CreateDocumentClassifierRequest的关键字段除上述三者外还通过DocumentClassifierInputDataConfig此处仅设置s3Uri指定输入数据来源并固定languageCode en。调用成功后返回documentClassifierArn——该 ARN 是后续使用classifyDocument或classifyDocumentWithModel进行推理的关键引用。由于训练本身是异步的创建请求返回后模型仍需一段时间取决于数据量才能进入可用状态。测试验证ComprehendKotlinTest仓库为上述六个示例配套了 JUnit 5 集成测试 ComprehendKotlinTest.kt其设计思路值得借鉴测试数据来源测试所需的dataAccessRoleArn、s3Uri、documentClassifierName并非硬编码而是通过BeforeAll中的setup()从 AWS Secrets Manager 读取private suspend fun getSecretValues(): String { val secretClient SecretsManagerClient { region us-east-1 } val secretName test/comprehend val valueRequest GetSecretValueRequest { secretId secretName } val valueResponse secretClient.getSecretValue(valueRequest) return valueResponse.secretString.toString() }该函数读取名为test/comprehend的密钥secret随后用 Gson 将 JSON 反序列化到内部类SecretValues字段dataAccessRoleArn、s3Uri、documentClassifier。测试编排五个检测类测试分别用TestOrder(1)至Order(5)标注执行顺序并调用runBlocking将挂起函数包入协程detectEntitiesTest→detectAllEntities(text)detectKeyPhrasesTest→detectAllKeyPhrases(text)detectLanguageTest→detectTheDominantLanguage(frText)注意这里专门使用法语文本验证语言检测detectSentimentTest→detectSentiments(text)detectSyntaxTest→detectAllSyntax(text)每个测试成功后在日志中输出 Test N passed 字样。运行方式可参考 kotlin/README.md 的说明既可从 IDE如 IntelliJ直接运行 JUnit 测试也可在命令行执行gradle test。运行成本提醒该 README 与测试文件均明确提示——运行这些代码可能产生 AWS 账户费用运行测试亦然。因为每个测试都会真实调用 Comprehend API按文本量计费而创建文档分类器的训练任务费用更高属典型的有偿资源调用。运行示例与注意事项汇总运行方式按前置条件配置 AWS 凭证与默认区域使用 Gradle 构建并运行某个示例的main函数例如直接运行 DetectSentiment.kt运行 DocumentClassifierDemo.kt 时需附带三个参数dataAccessRoleArn、s3Uri、documentClassifierName运行测试前确保 AWS Secrets Manager 中存在名为test/comprehend的密钥且包含dataAccessRoleArn、s3Uri、documentClassifier三个字段。官方提醒与最佳实践kotlin/services/comprehend/README.md 明确列出的注意事项应视为运行前提费用运行示例与测试都可能产生 AWS 账户费用请参考 AWS Pricing 与 Free Tier最小权限建议为代码授予最小权限least privilege仅授予执行任务所需的最低权限详见 Grant least privilege区域可用性示例未在所有 AWS 区域测试部分服务仅特定区域可用详见 AWS Regional Services。进一步学习路径官方 Comprehend 开发指南与 API 参考详见 Amazon Comprehend Developer Guide 与 Amazon Comprehend API ReferenceSDK for Kotlin 的 Comprehend 客户端类型与模型定义可参考 SDK for Kotlin Amazon Comprehend reference若希望了解 Comprehend 在真实应用中的集成方式kotlin/README.md 还提及了一个结合 Amazon SQS 与 Amazon Comprehend 的 React Spring REST 应用教程位于kotlin/usecases其中使用 Comprehend 检测消息的语言代码可作为阅读本示例后的进阶实践。总结通过 kotlin/services/comprehend 的六个示例可以完整掌握 AWS SDK for Kotlin 调用 Amazon Comprehend 的两大类能力一是detectEntities、detectKeyPhrases、detectDominantLanguage、detectSentiment、detectSyntax五个实时分析 API 的构建请求-调用-遍历响应标准范式二是通过createDocumentClassifier创建自定义分类器训练任务的参数体系。所有代码遵循统一的客户端管理模式ComprehendClient.fromEnvironment { region us-east-1 }.use { }与挂起函数调用约定配合 build.gradle.kts 中的 BOM 依赖声明与 JUnit 5 测试配置读者可直接复用到自己的 Kotlin 服务端项目中。Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.SPDX-License-Identifier: Apache-2.0赞分享示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载相关推荐使用 AWS SDK for Kotlin 调用 Amazon Textract文档文本检测与分析的完整实战指南使用 AWS SDK for Kotlin 调用 Amazon Textract文档文本检测与分析的完整实战指南 Amazon Textract 是 AWS示例工程教程后端使用 AWS SDK for Java 2.x 调用 Amazon Comprehend文本分析实战指南使用 AWS SDK for Java 2.x 调用 Amazon Comprehend文本分析实战指南 Amazon Comprehend 是基于自然语言处示例工程教程后端使用 AWS SDK for Kotlin 操作 Amazon RDS完整示例与源码级实战指南使用 AWS SDK for Kotlin 操作 Amazon RDS完整示例与源码级实战指南 本篇技术指南以 aws doc sdk examples 仓库示例工程教程后端创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考