Skip to content

Commit

Permalink
update: ktor 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
cssxsh committed Jul 15, 2022
1 parent 7433cc8 commit 60af97e
Show file tree
Hide file tree
Showing 15 changed files with 215 additions and 221 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package xyz.cssxsh.baidu.aip

import io.ktor.client.call.*
import io.ktor.client.request.*
import xyz.cssxsh.baidu.oauth.*
import xyz.cssxsh.baidu.oauth.data.*
Expand All @@ -14,7 +15,7 @@ internal suspend fun BaiduAuthClient<*>.getClientCredentialsToken(): AuthorizeAc
parameter("grant_type", GrantType.CLIENT_CREDENTIALS)
parameter("client_id", appKey)
parameter("client_secret", secretKey)
}
}.body()
}

/**
Expand All @@ -26,5 +27,5 @@ internal suspend fun BaiduAuthClient<*>.getRefreshToken(): AuthorizeAccessToken
parameter("refresh_token", refreshToken())
parameter("client_id", appKey)
parameter("client_secret", secretKey)
}
}.body()
}
103 changes: 48 additions & 55 deletions baidu-aip/src/main/kotlin/xyz/cssxsh/baidu/aip/AipContentCensor.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package xyz.cssxsh.baidu.aip

import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.http.*
Expand All @@ -19,41 +20,37 @@ public open class AipContentCensor(override val client: AipClient) : AipApplicat

public suspend fun image(url: String, gif: Boolean = false): CensorResult.Image {
return client.useHttpClient { http ->
http.post(IMAGE_CENSOR) {
http.submitForm(Parameters.build {
append("imgUrl", url)
append("imgType", if (gif) "1" else "0")
}) {
url(IMAGE_CENSOR)
parameter("access_token", client.accessToken())

body = FormDataContent(Parameters.build {
append("imgUrl", url)
append("imgType", if (gif) "1" else "0")
})
}
}.body()
}
}

public suspend fun image(bytes: ByteArray, gif: Boolean = false): CensorResult.Image {
@OptIn(InternalAPI::class)
val base64 = bytes.encodeBase64()
return client.useHttpClient { http ->
http.post(IMAGE_CENSOR) {
http.submitForm(Parameters.build {
append("image", base64)
append("imgType", if (gif) "1" else "0")
}) {
url(IMAGE_CENSOR)
parameter("access_token", client.accessToken())

body = FormDataContent(Parameters.build {
append("image", base64)
append("imgType", if (gif) "1" else "0")
})
}
}.body()
}
}

public suspend fun text(plain: String): CensorResult.Text {
return client.useHttpClient { http ->
http.post(TEXT_CENSOR) {
http.submitForm(Parameters.build {
append("text", plain)
}) {
url(TEXT_CENSOR)
parameter("access_token", client.accessToken())

body = FormDataContent(Parameters.build {
append("text", plain)
})
}
}.body()
}
}

Expand All @@ -64,54 +61,50 @@ public open class AipContentCensor(override val client: AipClient) : AipApplicat
public suspend fun video(name: String, urls: List<String>, extension: VideoExtension? = null): CensorResult.Video {
check(urls.isNotEmpty()) { "Video urls is not empty." }
return client.useHttpClient { http ->
http.post(VIDEO_CENSOR) {
parameter("access_token", client.accessToken())

body = FormDataContent(Parameters.build {
append("name", name)
for ((index, item) in urls.withIndex()) {
if (index == 0) {
append("videoUrl", item)
} else {
append("videoUrl${index + 1}", item)
}
http.submitForm(Parameters.build {
append("name", name)
for ((index, item) in urls.withIndex()) {
if (index == 0) {
append("videoUrl", item)
} else {
append("videoUrl${index + 1}", item)
}
append("extId", extension?.id ?: urls.first())
append("extInfo", extension?.info.toString())
})
}
}
append("extId", extension?.id ?: urls.first())
append("extInfo", extension?.info.toString())
}) {
url(VIDEO_CENSOR)
parameter("access_token", client.accessToken())
}.body()
}
}

public suspend fun voice(url: String, format: String, rawText: Boolean, split: Boolean): CensorResult.Voice {
return client.useHttpClient { http ->
http.post(VOICE_CENSOR) {
http.submitForm(Parameters.build {
append("url", url)
append("fmt", format)
append("rawText", "$rawText")
append("split", "$split")
}) {
url(VOICE_CENSOR)
parameter("access_token", client.accessToken())

body = FormDataContent(Parameters.build {
append("url", url)
append("fmt", format)
append("rawText", "$rawText")
append("split", "$split")
})
}
}.body()
}
}

public suspend fun voice(bytes: ByteArray, format: String, rawText: Boolean, split: Boolean): CensorResult.Voice {
@OptIn(InternalAPI::class)
val base64 = bytes.encodeBase64()
return client.useHttpClient { http ->
http.post(VOICE_CENSOR) {
http.submitForm(Parameters.build {
append("base64", base64)
append("fmt", format)
append("rawText", "$rawText")
append("split", "$split")
}) {
url(VOICE_CENSOR)
parameter("access_token", client.accessToken())

body = FormDataContent(Parameters.build {
append("base64", base64)
append("fmt", format)
append("rawText", "$rawText")
append("split", "$split")
})
}
}.body()
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package xyz.cssxsh.baidu.aip

import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import xyz.cssxsh.baidu.aip.nlp.*
Expand All @@ -23,9 +24,9 @@ public class AipNaturalLanguageProcessing(override val client: AipClient) : AipA
parameter("charset", "UTF-8")
parameter("access_token", client.accessToken())

body = mapOf("text" to text)
setBody(mapOf("text" to text))
contentType(ContentType.Application.Json)
}
}.body()
}
}

Expand All @@ -35,9 +36,9 @@ public class AipNaturalLanguageProcessing(override val client: AipClient) : AipA
parameter("charset", "UTF-8")
parameter("access_token", client.accessToken())

body = SimilarityResult.Words(first, second)
setBody(SimilarityResult.Words(first, second))
contentType(ContentType.Application.Json)
}
}.body()
}
}

Expand All @@ -47,9 +48,9 @@ public class AipNaturalLanguageProcessing(override val client: AipClient) : AipA
parameter("charset", "UTF-8")
parameter("access_token", client.accessToken())

body = mapOf("text" to text)
setBody(mapOf("text" to text))
contentType(ContentType.Application.Json)
}
}.body()
}
}

Expand All @@ -59,9 +60,9 @@ public class AipNaturalLanguageProcessing(override val client: AipClient) : AipA
parameter("charset", "UTF-8")
parameter("access_token", client.accessToken())

body = mapOf("text" to text)
setBody(mapOf("text" to text))
contentType(ContentType.Application.Json)
}
}.body()
}
}

Expand All @@ -71,9 +72,9 @@ public class AipNaturalLanguageProcessing(override val client: AipClient) : AipA
parameter("charset", "UTF-8")
parameter("access_token", client.accessToken())

body = SimnetResult.Texts(first, second)
setBody(SimnetResult.Texts(first, second))
contentType(ContentType.Application.Json)
}
}.body()
}
}
}
32 changes: 14 additions & 18 deletions baidu-aip/src/main/kotlin/xyz/cssxsh/baidu/aip/AipTextToSpeech.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package xyz.cssxsh.baidu.aip

import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.client.statement.*
import io.ktor.http.*
import xyz.cssxsh.baidu.aip.tts.*
import java.util.*
Expand All @@ -22,24 +20,22 @@ public open class AipTextToSpeech(override val client: AipClient) : AipApplicati

public suspend fun handle(text: String, option: SpeechOption = default.copy()): ByteArray {
return client.useHttpClient { http ->
http.post<HttpStatement>(API) {
body = FormDataContent(Parameters.build {
append("tex", text.encodeURLQueryComponent(charset = charset("GBK")))
append("tok", client.accessToken())
append("cuid", cuid)
append("ctp", "1")
append("lan", "zh")
append("spd", option.speed.toString())
append("pit", option.pitch.toString())
append("vol", option.volume.toString())
append("per", option.person.toString())
append("aue", option.format.toString())
})
}.execute { response ->
http.prepareForm(API, Parameters.build {
append("tex", text.encodeURLQueryComponent(charset = charset("GBK")))
append("tok", client.accessToken())
append("cuid", cuid)
append("ctp", "1")
append("lan", "zh")
append("spd", option.speed.toString())
append("pit", option.pitch.toString())
append("vol", option.volume.toString())
append("per", option.person.toString())
append("aue", option.format.toString())
}).execute { response ->
val type = requireNotNull(response.contentType()) { "ContentType is null." }
when {
type.match(ContentType.Audio.Any) -> response.receive()
type.match(ContentType.Application.Json) -> throw SpeechException(response, response.receive())
type.match(ContentType.Audio.Any) -> response.body()
type.match(ContentType.Application.Json) -> throw SpeechException(response, response.body())
else -> throw IllegalStateException("ContentType: $type not is audio.")
}
}
Expand Down
29 changes: 14 additions & 15 deletions baidu-aip/src/main/kotlin/xyz/cssxsh/baidu/aip/AipTranslator.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package xyz.cssxsh.baidu.aip

import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.http.*
Expand All @@ -21,14 +22,14 @@ public open class AipTranslator(override val client: AipClient) : AipApplication
http.post(TEXT_TRANSLATION) {
parameter("access_token", client.accessToken())

body = buildJsonObject {
setBody(buildJsonObject {
put("from", from ?: "auto")
put("to", to)
put("query", plain)
put("termIds", terms?.joinToString(separator = ","))
}
})
contentType(ContentType.Application.Json.withCharset(Charsets.UTF_8))
}
}.body()
}
}

Expand All @@ -37,29 +38,27 @@ public open class AipTranslator(override val client: AipClient) : AipApplication
http.post(TEXT_TRANSLATION_WITH_DICT) {
parameter("access_token", client.accessToken())

body = buildJsonObject {
setBody(buildJsonObject {
put("from", from ?: "auto")
put("to", to)
put("query", plain)
put("termIds", terms?.joinToString(separator = ","))
}
})
contentType(ContentType.Application.Json.withCharset(Charsets.UTF_8))
}
}.body()
}
}

public suspend fun picture(to: String, from: String, bytes: ByteArray): TranslateResult.Picture {
return client.useHttpClient { http ->
http.post(PICTURE_TRANSLATION) {
http.submitFormWithBinaryData(PICTURE_TRANSLATION, formData {
append(key = "to", value = to)
append(key = "from", value = from)
append(key = "v", value = 3)
append(key = "file", value = bytes)
}) {
parameter("access_token", client.accessToken())

body = MultiPartFormDataContent(formData {
append(key = "to", value = to)
append(key = "from", value = from)
append(key = "v", value = 3)
append(key = "file", value = bytes)
})
}
}.body()
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package xyz.cssxsh.baidu.aip.tts

import io.ktor.client.features.*
import io.ktor.client.plugins.*
import io.ktor.client.statement.*

public class SpeechException(response: HttpResponse, public val error: SpeechErrorInfo) :
Expand Down
9 changes: 5 additions & 4 deletions baidu-api/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ mavenCentralPublish {
}

dependencies {
api("io.ktor:ktor-client:1.6.7")
api("io.ktor:ktor-client-serialization:1.6.7")
api("io.ktor:ktor-client-encoding:1.6.7")
api("io.ktor:ktor-client-okhttp:1.6.7")
api("io.ktor:ktor-client-okhttp:2.0.3")
api("io.ktor:ktor-client-encoding:2.0.3")
api("io.ktor:ktor-client-content-negotiation:2.0.3")
api("io.ktor:ktor-serialization-kotlinx-json:2.0.3")
api("com.squareup.okhttp3:okhttp:4.10.0")
testImplementation(kotlin("test"))
}

Expand Down
Loading

0 comments on commit 60af97e

Please sign in to comment.