diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..2ef0d18 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,29 @@ +name: Ruby + +on: + push: + branches: + - main + + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + name: Ruby ${{ matrix.ruby }} + strategy: + matrix: + ruby: + - '3.2.1' + + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Run the default task + run: bundle exec rake + env: + API_KEY: ${{ secrets.API_KEY }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..726ddde --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ + +# rspec failure tracking +.rspec_status +*.gem +.env diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..34c5164 --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..055f08a --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,32 @@ +AllCops: + SuggestExtensions: false + TargetRubyVersion: 3.2.1 + +Style/StringLiterals: + Enabled: true + EnforcedStyle: double_quotes + +Style/StringLiteralsInInterpolation: + Enabled: true + EnforcedStyle: double_quotes + +Layout/LineLength: + Enabled: false + +Metrics/BlockLength: + Enabled: false + +Metrics/MethodLength: + Enabled: false + +Metrics/ModuleLength: + Enabled: false + +Metrics/AbcSize: + Enabled: false + +Metrics/CyclomaticComplexity: + Enabled: false + +Metrics/PerceivedComplexity: + Enabled: false diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..be94e6f --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.2.2 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..12b45c6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +## [Unreleased] + +## [0.1.0] - 2024-05-28 + +- Initial release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..1e1ba89 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at obiefernandez@gmail.com. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, +available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..c6cbe45 --- /dev/null +++ b/Gemfile @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# Specify your gem's dependencies in stability.gemspec +gemspec + + +group :development do + gem "dotenv", ">= 2" + gem "pry", ">= 0.14" + gem "rake", "~> 13.0" + gem "rspec", "~> 3.0" + gem "rubocop", "~> 1.21" + gem "solargraph-rails", "~> 0.2.0.pre" + gem "sorbet" + gem "tapioca", require: false +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..0fb5110 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,173 @@ +PATH + remote: . + specs: + stability (0.1.0) + dotenv (>= 2) + faraday (>= 1) + faraday-multipart (>= 1) + +GEM + remote: https://rubygems.org/ + specs: + activesupport (7.1.3.3) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + minitest (>= 5.1) + mutex_m + tzinfo (~> 2.0) + ast (2.4.2) + backport (1.2.0) + base64 (0.2.0) + benchmark (0.3.0) + bigdecimal (3.1.8) + coderay (1.1.3) + concurrent-ruby (1.2.3) + connection_pool (2.4.1) + diff-lcs (1.5.1) + dotenv (3.1.2) + drb (2.2.1) + e2mmap (0.1.0) + erubi (1.12.0) + faraday (2.9.0) + faraday-net_http (>= 2.0, < 3.2) + faraday-multipart (1.0.4) + multipart-post (~> 2) + faraday-net_http (3.1.0) + net-http + i18n (1.14.5) + concurrent-ruby (~> 1.0) + jaro_winkler (1.5.6) + json (2.7.2) + kramdown (2.4.0) + rexml + kramdown-parser-gfm (1.1.0) + kramdown (~> 2.0) + language_server-protocol (3.17.0.3) + method_source (1.1.0) + minitest (5.23.1) + multipart-post (2.4.1) + mutex_m (0.2.0) + net-http (0.4.1) + uri + netrc (0.11.0) + nokogiri (1.16.5-arm64-darwin) + racc (~> 1.4) + parallel (1.24.0) + parser (3.3.1.0) + ast (~> 2.4.1) + racc + prism (0.29.0) + pry (0.14.2) + coderay (~> 1.1) + method_source (~> 1.0) + racc (1.8.0) + rainbow (3.1.1) + rake (13.2.1) + rbi (0.1.13) + prism (>= 0.18.0, < 1.0.0) + sorbet-runtime (>= 0.5.9204) + rbs (2.8.4) + regexp_parser (2.9.2) + reverse_markdown (2.1.1) + nokogiri + rexml (3.2.8) + strscan (>= 3.0.9) + rspec (3.13.0) + rspec-core (~> 3.13.0) + rspec-expectations (~> 3.13.0) + rspec-mocks (~> 3.13.0) + rspec-core (3.13.0) + rspec-support (~> 3.13.0) + rspec-expectations (3.13.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-mocks (3.13.1) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-support (3.13.1) + rubocop (1.64.0) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.31.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.31.3) + parser (>= 3.3.1.0) + ruby-progressbar (1.13.0) + solargraph (0.50.0) + backport (~> 1.2) + benchmark + bundler (~> 2.0) + diff-lcs (~> 1.4) + e2mmap + jaro_winkler (~> 1.5) + kramdown (~> 2.3) + kramdown-parser-gfm (~> 1.1) + parser (~> 3.0) + rbs (~> 2.0) + reverse_markdown (~> 2.0) + rubocop (~> 1.38) + thor (~> 1.0) + tilt (~> 2.0) + yard (~> 0.9, >= 0.9.24) + solargraph-rails (0.2.2.pre.4) + activesupport + solargraph (>= 0.41.1) + sorbet (0.5.11391) + sorbet-static (= 0.5.11391) + sorbet-runtime (0.5.11391) + sorbet-static (0.5.11391-universal-darwin) + sorbet-static-and-runtime (0.5.11391) + sorbet (= 0.5.11391) + sorbet-runtime (= 0.5.11391) + spoom (1.3.2) + erubi (>= 1.10.0) + prism (>= 0.19.0) + sorbet-static-and-runtime (>= 0.5.10187) + thor (>= 0.19.2) + strscan (3.1.0) + tapioca (0.14.2) + bundler (>= 2.2.25) + netrc (>= 0.11.0) + parallel (>= 1.21.0) + rbi (>= 0.1.4, < 0.2) + sorbet-static-and-runtime (>= 0.5.11087) + spoom (>= 1.2.0) + thor (>= 1.2.0) + yard-sorbet + thor (1.3.1) + tilt (2.3.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (2.5.0) + uri (0.13.0) + yard (0.9.36) + yard-sorbet (0.8.1) + sorbet-runtime (>= 0.5) + yard (>= 0.9) + +PLATFORMS + arm64-darwin-21 + +DEPENDENCIES + dotenv (>= 2) + pry (>= 0.14) + rake (~> 13.0) + rspec (~> 3.0) + rubocop (~> 1.21) + solargraph-rails (~> 0.2.0.pre) + sorbet + stability! + tapioca + +BUNDLED WITH + 2.4.18 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..115b2c2 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Obie Fernandez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d8c44f1 --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# Stability + +Provides easy access to the Stable Image REST API provided by [stability.ai](https://platform.stability.ai/docs/api-reference). +This library is maintained by Obie Fernandez and the team at [Olympia](https://olympia.chat), the world's premier Ruby on Rails-based AI platform, +offering AI-powered teams for solopreneurs and small businesses. You can support this project by being a customer of Olympia, or buying Obie's book +[Patterns of Application Development Using AI](https://leanpub.com/patterns-of-application-development-using-ai) + +## Installation + +Install the gem and add to the application's Gemfile by executing: + + $ bundle add stability + +If bundler is not being used to manage dependencies, install the gem by executing: + + $ gem install stability + +## Usage + +TODO: Write usage instructions here + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. + +To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/OlympiaAI/stability. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/OlympiaAI/stability/blob/main/CODE_OF_CONDUCT.md). + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). + +## Code of Conduct + +Everyone interacting in our codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/OlympiaAI/stability/blob/main/CODE_OF_CONDUCT.md). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..cca7175 --- /dev/null +++ b/Rakefile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "rspec/core/rake_task" + +RSpec::Core::RakeTask.new(:spec) + +require "rubocop/rake_task" + +RuboCop::RakeTask.new + +task default: %i[spec rubocop] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..a133142 --- /dev/null +++ b/bin/console @@ -0,0 +1,12 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "dotenv/load" +require "bundler/setup" +require "stability" + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +require "irb" +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/lib/stability.rb b/lib/stability.rb new file mode 100644 index 0000000..24940e8 --- /dev/null +++ b/lib/stability.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +require_relative "stability/http" +require_relative "stability/client" +require_relative "stability/version" + +module Stability + class Error < StandardError; end + class ConfigurationError < Error; end + + class Configuration + attr_writer :api_key + attr_accessor :api_version, :extra_headers, :faraday_config, :log_errors, :request_timeout, :uri_base + + DEFAULT_API_VERSION = "v2beta" + DEFAULT_REQUEST_TIMEOUT = 120 + DEFAULT_URI_BASE = "https://api.stability.ai" + + def initialize + self.api_key = nil + self.api_version = DEFAULT_API_VERSION + self.extra_headers = {} + self.log_errors = false + self.request_timeout = DEFAULT_REQUEST_TIMEOUT + self.uri_base = DEFAULT_URI_BASE + end + + def api_key + return @api_key if @api_key + + raise ConfigurationError, "Stability AI api key missing!" + end + + def faraday(&block) + self.faraday_config = block + end + end + + class << self + attr_writer :configuration + end + + def self.configuration + @configuration ||= Stability::Configuration.new + end + + def self.configure + yield(configuration) + end +end diff --git a/lib/stability/client.rb b/lib/stability/client.rb new file mode 100644 index 0000000..e23314f --- /dev/null +++ b/lib/stability/client.rb @@ -0,0 +1,103 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/blank" +require "active_support/core_ext/hash/indifferent_access" + +require_relative "http" + +module Stability + class ServerError < StandardError; end + + class Client + include Stability::HTTP + + # Initializes the client with optional configurations. + def initialize(api_key: nil, request_timeout: nil, uri_base: nil, extra_headers: {}) + Stability.configuration.api_key = api_key if api_key + Stability.configuration.request_timeout = request_timeout if request_timeout + Stability.configuration.uri_base = uri_base if uri_base + Stability.configuration.extra_headers = extra_headers if extra_headers.any? + yield(Stability.configuration) if block_given? + end + + # Performs a text-to-image generation request to the Stability API using Stable Image Core. + # + # @param prompt [String] Descriptive prompt for the desired output image. Elements, colors, and subjects should be well-defined + # for optimal results. Use the format (word:weight) to control the weight of specific words, e.g., + # "The sky was a crisp (blue:0.3) and (green:0.8)" indicates a sky more green than blue. + # + # @param options [Hash] Additional options for the request: + # + # - aspect_ratio [String] Specifies the aspect ratio of the generated image. + # Options: "16:9", "1:1" (default), "21:9", "2:3", "3:2", "4:5", "5:4", "9:16", "9:21" + # + # - negative_prompt [String] Describes elements to be excluded from the image. Max 10000 characters. + # + # - seed [Integer] Controls the randomness of generation, where 0 uses a random seed. Range: 0 (default) to 4294967294 + # + # - style_preset [String] Guides the image model towards a particular visual style. + # Options: "3d-model", "analog-film", "anime", "cinematic", "comic-book", "digital-art", "enhance", "fantasy-art", + # "isometric", "line-art", "low-poly", "modeling-compound", "neon-punk", "origami", "photographic", + # "pixel-art", "tile-texture" + # + # - output_format [String] Specifies the format of the generated image. Options: "jpeg", "png" (default), "webp" + # + # @param json [Boolean] Specifies whether to return the response as a JSON object containing a base64 encoded image or as + # image bytes directly. Default is false (image bytes directly). + # + def generate_core(prompt, options: {}, json: false) + headers = { "Accept" => json ? "application/json" : "image/*" } + parameters = { prompt: }.merge(options) + multipart_post(path: "/stable-image/generate/core", headers:, parameters:).tap do |response| + raise ServerError, "Empty response from Stability. Might be worth retrying once or twice." if response.blank? + raise ServerError, response.dig("error", "message") if response.dig("error", "message").present? + end.with_indifferent_access + end + + # Performs a text-to-image or image-to-image generation request to the Stability API using Stable Diffusion 3. + # + # @param prompt [String] Descriptive prompt for the desired output image. Elements, colors, and subjects should be well-defined + # for optimal results. Use the format (word:weight) to control the weight of specific words, e.g., + # "The sky was a crisp (blue:0.3) and (green:0.8)" indicates a sky more green than blue. + # + # @param options [Hash] Additional options for the request: + # + # - aspect_ratio [String] Specifies the aspect ratio of the generated image. + # Options: "16:9", "1:1" (default), "21:9", "2:3", "3:2", "4:5", "5:4", "9:16", "9:21" + # + # - mode [String] Controls whether this is a text-to-image or image-to-image generation. + # Options: "text-to-image" (default), "image-to-image" + # + # - image [File] Required if mode is "image-to-image". The input image file. + # + # - strength [Float] Required if mode is "image-to-image". Controls the strength of the transformation. + # + # - negative_prompt [String] Describes elements to be excluded from the image. Max 10000 characters. + # + # - model [String] Specifies the model to use for generation. + # Options: "sd3" (default), "sd3-turbo" + # + # - seed [Integer] Controls the randomness of generation, where 0 uses a random seed. Range: 0 (default) to 4294967294 + # + # - output_format [String] Specifies the format of the generated image. Options: "jpeg", "png" (default) + # + # @param json [Boolean] Specifies whether to return the response as a JSON object containing a base64 encoded image or as + # image bytes directly. Default is false (image bytes directly). + # + def generate_sd3(prompt, options: {}, json: false) + headers = { "Accept" => json ? "application/json" : "image/*" } + parameters = { prompt: }.merge(options) + + # Ensure required parameters for image-to-image mode + if parameters[:mode] == "image-to-image" + raise ArgumentError, "image is required for image-to-image mode" unless parameters[:image] + raise ArgumentError, "strength is required for image-to-image mode" unless parameters[:strength] + end + + multipart_post(path: "/stable-image/generate/sd3", headers:, parameters:).tap do |response| + raise ServerError, "Empty response from Stability. Might be worth retrying once or twice." if response.blank? + raise ServerError, response.dig("error", "message") if response.dig("error", "message").present? + end.with_indifferent_access + end + end +end diff --git a/lib/stability/http.rb b/lib/stability/http.rb new file mode 100644 index 0000000..cd8f6d3 --- /dev/null +++ b/lib/stability/http.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +require "faraday" +require "faraday/multipart" + +module Stability + module HTTP + def get(path:) + conn.get(uri(path:)) do |req| + req.headers = headers + end&.body + end + + def post(path:, parameters:) + conn.post(uri(path:)) do |req| + if parameters[:stream].respond_to?(:call) + req.options.on_data = to_json_stream(user_proc: parameters[:stream]) + parameters[:stream] = true + end + + req.headers = headers + req.body = parameters.to_json + end&.body + end + + def multipart_post(path:, headers: {}, parameters: nil) + conn(multipart: true).post(uri(path:)) do |req| + req.headers = default_headers.merge(headers).merge({ "Content-Type" => "multipart/form-data" }) + req.body = multipart_parameters(parameters) + end&.body + end + + def delete(path:) + conn.delete(uri(path:)) do |req| + req.headers = headers + end&.body + end + + private + + # Given a proc, returns an outer proc that can be used to iterate over a JSON stream of chunks. + # For each chunk, the inner user_proc is called giving it the JSON object. The JSON object could + # be a data object or an error object as described in the API documentation. + # + # If the JSON object for a given data or error message is invalid, it is ignored. + # + # @param user_proc [Proc] The inner proc to call for each JSON object in the chunk. + # @return [Proc] An outer proc that iterates over a raw stream, converting it to JSON. + def to_json_stream(user_proc:) + proc do |chunk, _| + chunk.scan(/(?:data|error): (\{.*\})/i).flatten.each do |data| + user_proc.call(JSON.parse(data)) + rescue JSON::ParserError + # Ignore invalid JSON. + end + end + end + + def conn(multipart: false) + Faraday.new do |f| + f.options[:timeout] = Stability.configuration.request_timeout + f.request(:multipart) if multipart + f.use MiddlewareErrors if @log_errors + f.response :raise_error + f.response :json + + Stability.configuration.faraday_config&.call(f) + end + end + + def uri(path:) + File.join(Stability.configuration.uri_base, Stability.configuration.api_version, path) + end + + def default_headers + { + "Authorization" => "Bearer #{Stability.configuration.api_key}", + "Content-Type" => "application/json" + }.merge(Stability.configuration.extra_headers) + end + + def multipart_parameters(parameters) + parameters&.transform_values do |value| + next value unless value.is_a?(File) + + # Doesn't seem like Stability needs mime_type yet, so not worth + # the library to figure this out. Hence the empty string + # as the second argument. + Faraday::UploadIO.new(value, "", value.path) + end + end + end +end diff --git a/lib/stability/version.rb b/lib/stability/version.rb new file mode 100644 index 0000000..1d6e536 --- /dev/null +++ b/lib/stability/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Stability + VERSION = "0.1.0" +end diff --git a/sig/stability.rbs b/sig/stability.rbs new file mode 100644 index 0000000..4d732fe --- /dev/null +++ b/sig/stability.rbs @@ -0,0 +1,4 @@ +module Stability + VERSION: String + # See the writing guide of rbs: https://github.com/ruby/rbs#guides +end diff --git a/spec/fixtures/files/sample_image.jpg b/spec/fixtures/files/sample_image.jpg new file mode 100644 index 0000000..b90cb79 Binary files /dev/null and b/spec/fixtures/files/sample_image.jpg differ diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..7db487b --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require "pry" +require "dotenv/load" +require "stability" + +RSpec.configure do |config| + # Enable flags like --only-failures and --next-failure + config.example_status_persistence_file_path = ".rspec_status" + + # Disable RSpec exposing methods globally on `Module` and `main` + config.disable_monkey_patching! + + config.expect_with :rspec do |c| + c.syntax = :expect + end +end diff --git a/spec/stability_spec.rb b/spec/stability_spec.rb new file mode 100644 index 0000000..735574e --- /dev/null +++ b/spec/stability_spec.rb @@ -0,0 +1,118 @@ +# frozen_string_literal: true +require 'base64' + +RSpec.describe Stability do + it "has a version number" do + expect(Stability::VERSION).not_to be nil + end + + describe Stability::Client do + let(:client) do + Stability::Client.new(api_key: ENV["API_KEY"]) do |config| + config.faraday do |f| + f.response :logger, ::Logger.new($stdout), { headers: true, bodies: true, errors: true } do |logger| + logger.filter(/(Bearer) (\S+)/, '\1[REDACTED]') + end + end + end + end + + describe "#initialize" do + it "yields the configuration" do + expect { |b| Stability::Client.new(&b) }.to yield_with_args(Stability.configuration) + end + end + + describe "#generate_core" do + let(:prompt) { "A beautiful sunset over the city" } + + it "sends a POST request to the generate endpoint with the correct parameters and generates an image" do + expect(client).to receive(:multipart_post).with( + path: "/stable-image/generate/core", + headers: { "Accept" => "application/json" }, + parameters: { prompt: } + ).and_call_original + + response = client.generate_core(prompt, json: true) + expect(response).to be_a(Hash) + expect(response).to have_key("image") + expect(response["image"]).to be_a(String) + expect(response["finish_reason"]).to eq("SUCCESS") + + unless ENV['CI'] + # Decode the base64 image and save it to a specific file in /tmp + image_data = Base64.decode64(response["image"]) + file_path = "/tmp/core_generated_image.png" + File.open(file_path, "wb") do |file| + file.write(image_data) + end + + # Open the image file + system("open", file_path) + end + end + end + + describe "#generate_sd3" do + let(:prompt) { "A futuristic cityscape at night" } + + it "sends a POST request to the generate endpoint with the correct parameters and generates an image" do + expect(client).to receive(:multipart_post).with( + path: "/stable-image/generate/sd3", + headers: { "Accept" => "application/json" }, + parameters: { prompt: } + ).and_call_original + + response = client.generate_sd3(prompt, json: true) + expect(response).to be_a(Hash) + expect(response).to have_key("image") + expect(response["image"]).to be_a(String) + expect(response["finish_reason"]).to eq("SUCCESS") + + # Decode the base64 image and save it to a specific file in /tmp + unless ENV['CI'] + image_data = Base64.decode64(response["image"]) + file_path = "/tmp/sd3_generated_image.png" + File.open(file_path, "wb") do |file| + file.write(image_data) + end + + # Open the image file + system("open", file_path) + end + end + + context "when mode is image-to-image" do + let(:image_path) { "spec/fixtures/files/sample_image.jpg" } + let(:image_file) { File.open(image_path, "rb") } + let(:strength) { 0.75 } + + it "sends a POST request to the generate endpoint with the correct parameters and generates an image" do + expect(client).to receive(:multipart_post).with( + path: "/stable-image/generate/sd3", + headers: { "Accept" => "application/json" }, + parameters: { prompt:, model: "sd3-turbo", mode: "image-to-image", image: image_file, strength: } + ).and_call_original + + response = client.generate_sd3(prompt, options: { model: "sd3-turbo", mode: "image-to-image", image: image_file, strength: }, json: true) + expect(response).to be_a(Hash) + expect(response).to have_key("image") + expect(response["image"]).to be_a(String) + expect(response["finish_reason"]).to eq("SUCCESS") + + # Decode the base64 image and save it to a specific file in /tmp + unless ENV['CI'] + image_data = Base64.decode64(response["image"]) + file_path = "/tmp/sd3_generated_image-to-image.png" + File.open(file_path, "wb") do |file| + file.write(image_data) + end + + # Open the image file + system("open", file_path) + end + end + end + end + end +end diff --git a/stability.gemspec b/stability.gemspec new file mode 100644 index 0000000..82e602e --- /dev/null +++ b/stability.gemspec @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require_relative "lib/stability/version" + +Gem::Specification.new do |spec| + spec.name = "stability" + spec.version = Stability::VERSION + spec.authors = ["Obie Fernandez"] + spec.email = ["obiefernandez@gmail.com"] + + spec.summary = "Ruby SDK for the Stability Platform API" + spec.homepage = "https://github.com/OlympiaAI/stabillity" + spec.license = "MIT" + spec.required_ruby_version = ">= 3.2.2" + + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = "https://github.com/OlympiaAI/stability" + spec.metadata["changelog_uri"] = "https://github.com/OlympiaAI/stability/blob/main/CHANGELOG.md" + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + spec.files = Dir.chdir(__dir__) do + `git ls-files -z`.split("\x0").reject do |f| + (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor]) + end + end + spec.bindir = "exe" + spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.require_paths = ["lib"] + + spec.add_dependency "dotenv", ">= 2" + spec.add_dependency "faraday", ">= 1" + spec.add_dependency "faraday-multipart", ">= 1" +end