Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat 4461 - Kotlin function for deepgramTopicDetection added #163

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions kotlin/deepgram_topic_detection/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# 🧹 Deepgram Topic Detection

A Cloud Function for topic detection using [Deepgram](https://deepgram.com/)

_Example input:_

```json
{
"fileUrl": "https://static.deepgram.com/examples/interview_speech-analytics.wav"
}
```

_Example output:_

```json
{ "success": true, "deepgramData": {} }
```

_Example error output:_

```json
{ "success": false, "message": "Please provide a valid file URL." }
```

## 📝 Environment Variables

**DEEPGRAM_API_KEY** - Your Deepgram secret API key.
Details are under link: [Deepgram_getting_started](https://developers.deepgram.com/documentation/getting-started/)

## 🚀 Deployment

1. Clone this repository, and enter this function folder:

```
$ git clone https://github.com/open-runtimes/examples.git && cd examples
$ cd kotlin/deepgram_topic_detection
```

2. Build the code:

```bash
docker run -e INTERNAL_RUNTIME_ENTRYPOINT=src/Index.kt --rm --interactive --tty --volume $PWD:/usr/code openruntimes/kotlin:v2-1.6 sh /usr/local/src/build.sh
```

3. Spin-up open-runtime:

```bash
docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/kotlin:v2-1.6 sh /usr/local/src/start.sh
```

4. Run the curl function to send request.

```bash
curl --location --request POST 'http://localhost:3000/' \
--header 'X-Internal-Challenge: secret-key' \
--header 'Content-Type: application/json' \
--data-raw '{"payload": "{\"fileUrl\": \"https://static.deepgram.com/examples/interview_speech-analytics.wav\"}",
"variables": {"DEEPGRAM_API_KEY":"<YOUR_API_KEY>"}}
'
```

Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Kotlin runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/kotlin-1.6).

## 📝 Notes

- This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions).
3 changes: 3 additions & 0 deletions kotlin/deepgram_topic_detection/deps.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dependencies {
implementation 'com.google.code.gson:gson:2.9.0'
}
86 changes: 86 additions & 0 deletions kotlin/deepgram_topic_detection/src/Index.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import io.openruntimes.kotlin.RuntimeRequest
import io.openruntimes.kotlin.RuntimeResponse
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL


val HTTP_BAD_REQEST = 400
val DEEPGRAM_TOPIC_DETECTION_API_END_POINT = "https://api.deepgram.com/v1/listen?detect_topics=true&punctuate=true"
val gson = Gson()

fun getErrorResponseWithMessage(res: RuntimeResponse, message: String? = "Some error occurred"): RuntimeResponse {
return res.json(
data = mapOf(
"success" to false,
"message" to message
),
statusCode = HTTP_BAD_REQEST
)
}

@Throws(Exception::class)
suspend fun main(req: RuntimeRequest, res: RuntimeResponse): RuntimeResponse {

val deepgramApiKey = req.variables["DEEPGRAM_API_KEY"]
if (deepgramApiKey == null || deepgramApiKey.trim().isEmpty()) {
return getErrorResponseWithMessage(res, "Deepgram API key must be set to use this function.")
}

val payloadMap = Gson().fromJson<Map<String, String>>(
req.payload.ifBlank { "{}" },
Map::class.java
)
val fileUrl = payloadMap["fileUrl"] ?: ""

if (fileUrl.isEmpty() || fileUrl.trim().isEmpty()) {
return getErrorResponseWithMessage(res, "Please provide a valid file URL.")
}

val url = URL(DEEPGRAM_TOPIC_DETECTION_API_END_POINT)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection

conn.requestMethod = "POST"
conn.addRequestProperty("Content-Type", "application/json")
conn.addRequestProperty("Authorization", "Token $deepgramApiKey")

conn.doOutput = true

//prepare request body
val requestBody ="{\"url\":\""+fileUrl+"\"}"

val response = StringBuilder()

try {
val os: OutputStream = conn.getOutputStream()
val input: ByteArray = requestBody.toByteArray(Charsets.UTF_8)
os.write(input, 0, input.size)

val br = BufferedReader(InputStreamReader(conn.getInputStream(), "utf-8"))
var responseLine: String? = null
while (br.readLine().also { responseLine = it } != null) {
response.append(responseLine!!.trim { it <= ' ' })
}

br.close()
conn.disconnect()
}
catch (e: Exception){
return getErrorResponseWithMessage(res, e.message)
}


val deepgramResponse = response.toString()
return res.json(
data = mapOf(
"success" to true,
"deepgramData" to deepgramResponse
),
statusCode = 200
)
}