Skip to content

Commit

Permalink
Merge pull request open-runtimes#66 from vzsky/main
Browse files Browse the repository at this point in the history
Add Compress Image for Ruby
  • Loading branch information
Meldiron committed Jan 22, 2023
2 parents 30054ba + de62760 commit 2fc1b1d
Show file tree
Hide file tree
Showing 4 changed files with 191 additions and 2 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ Example functions to show off what you can achieve with Open Runtimes.
| Send SMS with Twilio | | [](/deno/send_sms_with_twilio) | [](/node/send_sms_with_twilio) | | | [](/ruby/send-sms-with-twilio) | |
| Translate text with Google | | [](/deno/translate_text_with_google) | [](/node/translate_text_with_google) | | | [](/ruby/translate-text-with-google) | |
| Object Detection |[](/dart/object_detection) | [](/deno/object_detection) | [](/node/object_detection) | [](/php/object_detection) | [](/python/object-detection) | | |
| Generate Giphy GIF | [](/dart/generate_giphy_gif) | [](/deno/generate-giphy-gif) | [](/node/generate_giphy_gif) | [](/php/generate_giphy_gif) | [](/python/generate-giphy-gif) | | |
| Get COVID-19 Stats | | | [](/node/get_covid_stats) | | | | [](/swift/get-covid-stats) |
| Generate Giphy GIF | [](/dart/generate_giphy_gif) | [](/deno/generate-giphy-gif) | [](/node/generate_giphy_gif) | | [](/python/generate-giphy-gif) | | |
| Get COVID-19 Stats | | | | | | | [](/swift/get-covid-stats) |
| Compresss Imagse | | | | | |[](/ruby/compress-image)| |
| Send a HTTP Request | | | | | | [](/ruby/send-http-request) | |
| Wipe Appwrite Bucket | | | [](/node/wipe_appwrite_bucket) | | | | |
| Detect Language with Deepgram | | | | | [](/python/deepgram-language-detection) | | |
Expand Down
4 changes: 4 additions & 0 deletions ruby/compress-image/Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
source "https://rubygems.org"
gem "base64"
gem "tinify"
gem "kraken-io"
65 changes: 65 additions & 0 deletions ruby/compress-image/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Compress .png Images

A Ruby Cloud Function that compresses png images.


`image` and `provider` are recieved from the payload, where `image` is a base64 encoded string and `provider` is either [`tinypng`](https://tinypng.com) or [`krakenio`](https://kraken.io)

_Example input:_

```json
{
"image": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAf0lEQVR4nO2Wuw2AMAxEbw1gpMwDDMBcGQpooDKydGVAoXCK6J7k6qyc83MCCFGP/Yz+CkDF4KHmjgowbQF0CKFrCDUiwztqxabHCL0/xwcNhoI2UdsjC8g0mQvaSs1zwkg0uQAsAEaGm9/UPCeU7eMj6loTEpf6ZOQWMxd98gAhZnS6XEZcNQAAAABJRU5ErkJggg==",
"provider": "tinypng",
}
```

> `krakenio` is also a supported provider
_Example output:_

```json
{
"success": true,
"image": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAG1BMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACUUeIgAAAACHRSTlMA8712Sxr5g97cFtUAAAA9SURBVCjPY6Aa6AADfAIcDSA8KoBTgLGVgSFCAEmAqZmBwUIBSYClzTQ4wwE52Cs6OtpR4oFFUciBerEKAP58HnyLtZsYAAAAAElFTkSuQmCC"
}
```

## 📝 Variables

> only selected provider's api keys are neccessary, ie. kraken's api keys are not neccessary when choosing tinypng as the provider.
- **TINYPNG_API** - API key for tinypng service
- **KRAKENIO_KEY** - API key for kraken-io service
- **KRAKENIO_SECRET** - API Secret for kraken-io service

## 🚀 Deployment

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

```
$ git clone https://github.com/open-runtimes/examples.git && cd examples
$ cd ruby/compress-image
```

2. Enter this function folder and build the code:
```
docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/ruby:v2-3.1 sh /usr/local/src/build.sh
```
As a result, a `code.tar.gz` file will be generated.
3. Start the Open Runtime:
```
docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.rb --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/ruby:v2-3.1 sh /usr/local/src/start.sh
```

4. Execute function:

```shell
curl http:https://localhost:3000/ -d '{"variables":{"TINYPNG_API":"[YOUR_API_KEY]"},"payload":"{\"provider\":\"tinypng\",\"image\":\"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAf0lEQVR4nO2Wuw2AMAxEbw1gpMwDDMBcGQpooDKydGVAoXCK6J7k6qyc83MCCFGP/Yz+CkDF4KHmjgowbQF0CKFrCDUiwztqxabHCL0/xwcNhoI2UdsjC8g0mQvaSs1zwkg0uQAsAEaGm9/UPCeU7eMj6loTEpf6ZOQWMxd98gAhZnS6XEZcNQAAAABJRU5ErkJggg==\"}"}' -H "X-Internal-Challenge: secret-key" -H "Content-Type: application/json"
```

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 Python runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/ruby-3.1).

## 📝 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).
- This example is compatible with Ruby 3.1. Other versions may work but are not guaranteed to work as they haven't been tested.
119 changes: 119 additions & 0 deletions ruby/compress-image/index.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
require "json"
require "base64"
require "tinify"
require "kraken-io"

class NotImageException < StandardError; end
class ApiError < StandardError; end
class NoApiError < StandardError; end

$invalidPayload = {
success: false, message: "Invalid Payload"
}
$notImage = {
success: false, message: "Input file is not an image."
}
$invalidApi = {
success: false, message: "Invalid API."
}
$noApi = {
success: false, message: "no API key was provided."
}

def tinypng(req, image)
# Get api key
if !req.variables['TINYPNG_API']
raise NoApiError
end

Tinify.key = req.variables['TINYPNG_API']
buffer = Base64.decode64(image)
result = Tinify.from_buffer(buffer).to_buffer

Base64.encode64(result)
end

def krakenio(req, image)
if !req.variables['KRAKENIO_KEY'] or !req.variables['KRAKENIO_SECRET']
raise NoApiError
end

buffer = Base64.decode64(image)
dir = Dir.mktmpdir("kraken_temp")

File.open("#{dir}/file.png", 'wb') do |f|
f.write(buffer)
end

kraken = Kraken::API.new(
:api_key => req.variables['KRAKENIO_KEY'],
:api_secret => req.variables['KRAKENIO_SECRET']
)

data = kraken.upload("#{dir}/file.png")

File.delete("#{dir}/file.png") if File.exist?("#{dir}/file.png")

if data.success
img = URI.open(data.kraked_url)
Base64.encode64(img.read)
else
if data.message.include? 'Unknown API Key'
raise ApiError
end
raise NotImageException
end
end

def main(req, res)
# Input validation
provider = nil
image = nil
begin
payload = JSON.parse(req.payload)
provider = payload["provider"]
image = payload["image"]
rescue Exception => err
return res.json($invalidPayload)
end

if provider.nil? or provider.empty? or image.nil? or image.empty?
return res.json($invalidPayload)
end

if provider == 'tinypng'
begin
base64 = tinypng(req, image)
return res.json({
success: true,
image: base64.gsub("\n",'')
})
rescue Tinify::ClientError
return res.json($notImage)
rescue Tinify::AccountError
return res.json($invalidApi)
rescue NoApiError
return res.json($noApi)
end
end

if provider == 'krakenio'
begin
base64 = krakenio(req, image)
return res.json({
success: true,
image: base64.gsub("\n",'')
})
rescue ApiError
return res.json($invalidApi)
rescue NotImageException
return res.json($notImage)
rescue NoApiError
return res.json($noApi)
end
end

res.json({
success: false, message: "Unsupported Providers."
})
end

0 comments on commit 2fc1b1d

Please sign in to comment.