stability 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9e8bb5d8534a091a11a2e0ec70b4dcd9aec57486a64b8a5f1fc90925c119eb74
4
+ data.tar.gz: 541d3c8d6e6e3c9a5df91e0022f1695702c8cf7ed33b8f87be94b3a597383e74
5
+ SHA512:
6
+ metadata.gz: 8566508c4ca12a6603c301a7b322e3a6006723099ba02ec75c50b312ab69bd01da9e429b1026b5ef6542a65dc87b9fe5d514955a6fe8603f90aa9fcd49f082cb
7
+ data.tar.gz: 4d40796870ffc649ed8e21cc7b4f66e2211e21249f42bc1dc5a964644d4ef90941ad201d3ecdb8c143f10fdb9d0d2e8d0f3becf3533d89bdebf22db54d7052a7
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,32 @@
1
+ AllCops:
2
+ SuggestExtensions: false
3
+ TargetRubyVersion: 3.2.1
4
+
5
+ Style/StringLiterals:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Layout/LineLength:
14
+ Enabled: false
15
+
16
+ Metrics/BlockLength:
17
+ Enabled: false
18
+
19
+ Metrics/MethodLength:
20
+ Enabled: false
21
+
22
+ Metrics/ModuleLength:
23
+ Enabled: false
24
+
25
+ Metrics/AbcSize:
26
+ Enabled: false
27
+
28
+ Metrics/CyclomaticComplexity:
29
+ Enabled: false
30
+
31
+ Metrics/PerceivedComplexity:
32
+ Enabled: false
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.2.2
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-05-28
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ 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.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ 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.
33
+
34
+ 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.
35
+
36
+ ## Scope
37
+
38
+ 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.
39
+
40
+ ## Enforcement
41
+
42
+ 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.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **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.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **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.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **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.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **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.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in stability.gemspec
6
+ gemspec
7
+
8
+
9
+ group :development do
10
+ gem "dotenv", ">= 2"
11
+ gem "pry", ">= 0.14"
12
+ gem "rake", "~> 13.0"
13
+ gem "rspec", "~> 3.0"
14
+ gem "rubocop", "~> 1.21"
15
+ gem "solargraph-rails", "~> 0.2.0.pre"
16
+ gem "sorbet"
17
+ gem "tapioca", require: false
18
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,173 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ stability (0.1.0)
5
+ dotenv (>= 2)
6
+ faraday (>= 1)
7
+ faraday-multipart (>= 1)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ activesupport (7.1.3.3)
13
+ base64
14
+ bigdecimal
15
+ concurrent-ruby (~> 1.0, >= 1.0.2)
16
+ connection_pool (>= 2.2.5)
17
+ drb
18
+ i18n (>= 1.6, < 2)
19
+ minitest (>= 5.1)
20
+ mutex_m
21
+ tzinfo (~> 2.0)
22
+ ast (2.4.2)
23
+ backport (1.2.0)
24
+ base64 (0.2.0)
25
+ benchmark (0.3.0)
26
+ bigdecimal (3.1.8)
27
+ coderay (1.1.3)
28
+ concurrent-ruby (1.2.3)
29
+ connection_pool (2.4.1)
30
+ diff-lcs (1.5.1)
31
+ dotenv (3.1.2)
32
+ drb (2.2.1)
33
+ e2mmap (0.1.0)
34
+ erubi (1.12.0)
35
+ faraday (2.9.0)
36
+ faraday-net_http (>= 2.0, < 3.2)
37
+ faraday-multipart (1.0.4)
38
+ multipart-post (~> 2)
39
+ faraday-net_http (3.1.0)
40
+ net-http
41
+ i18n (1.14.5)
42
+ concurrent-ruby (~> 1.0)
43
+ jaro_winkler (1.5.6)
44
+ json (2.7.2)
45
+ kramdown (2.4.0)
46
+ rexml
47
+ kramdown-parser-gfm (1.1.0)
48
+ kramdown (~> 2.0)
49
+ language_server-protocol (3.17.0.3)
50
+ method_source (1.1.0)
51
+ minitest (5.23.1)
52
+ multipart-post (2.4.1)
53
+ mutex_m (0.2.0)
54
+ net-http (0.4.1)
55
+ uri
56
+ netrc (0.11.0)
57
+ nokogiri (1.16.5-arm64-darwin)
58
+ racc (~> 1.4)
59
+ parallel (1.24.0)
60
+ parser (3.3.1.0)
61
+ ast (~> 2.4.1)
62
+ racc
63
+ prism (0.29.0)
64
+ pry (0.14.2)
65
+ coderay (~> 1.1)
66
+ method_source (~> 1.0)
67
+ racc (1.8.0)
68
+ rainbow (3.1.1)
69
+ rake (13.2.1)
70
+ rbi (0.1.13)
71
+ prism (>= 0.18.0, < 1.0.0)
72
+ sorbet-runtime (>= 0.5.9204)
73
+ rbs (2.8.4)
74
+ regexp_parser (2.9.2)
75
+ reverse_markdown (2.1.1)
76
+ nokogiri
77
+ rexml (3.2.8)
78
+ strscan (>= 3.0.9)
79
+ rspec (3.13.0)
80
+ rspec-core (~> 3.13.0)
81
+ rspec-expectations (~> 3.13.0)
82
+ rspec-mocks (~> 3.13.0)
83
+ rspec-core (3.13.0)
84
+ rspec-support (~> 3.13.0)
85
+ rspec-expectations (3.13.0)
86
+ diff-lcs (>= 1.2.0, < 2.0)
87
+ rspec-support (~> 3.13.0)
88
+ rspec-mocks (3.13.1)
89
+ diff-lcs (>= 1.2.0, < 2.0)
90
+ rspec-support (~> 3.13.0)
91
+ rspec-support (3.13.1)
92
+ rubocop (1.64.0)
93
+ json (~> 2.3)
94
+ language_server-protocol (>= 3.17.0)
95
+ parallel (~> 1.10)
96
+ parser (>= 3.3.0.2)
97
+ rainbow (>= 2.2.2, < 4.0)
98
+ regexp_parser (>= 1.8, < 3.0)
99
+ rexml (>= 3.2.5, < 4.0)
100
+ rubocop-ast (>= 1.31.1, < 2.0)
101
+ ruby-progressbar (~> 1.7)
102
+ unicode-display_width (>= 2.4.0, < 3.0)
103
+ rubocop-ast (1.31.3)
104
+ parser (>= 3.3.1.0)
105
+ ruby-progressbar (1.13.0)
106
+ solargraph (0.50.0)
107
+ backport (~> 1.2)
108
+ benchmark
109
+ bundler (~> 2.0)
110
+ diff-lcs (~> 1.4)
111
+ e2mmap
112
+ jaro_winkler (~> 1.5)
113
+ kramdown (~> 2.3)
114
+ kramdown-parser-gfm (~> 1.1)
115
+ parser (~> 3.0)
116
+ rbs (~> 2.0)
117
+ reverse_markdown (~> 2.0)
118
+ rubocop (~> 1.38)
119
+ thor (~> 1.0)
120
+ tilt (~> 2.0)
121
+ yard (~> 0.9, >= 0.9.24)
122
+ solargraph-rails (0.2.2.pre.4)
123
+ activesupport
124
+ solargraph (>= 0.41.1)
125
+ sorbet (0.5.11391)
126
+ sorbet-static (= 0.5.11391)
127
+ sorbet-runtime (0.5.11391)
128
+ sorbet-static (0.5.11391-universal-darwin)
129
+ sorbet-static-and-runtime (0.5.11391)
130
+ sorbet (= 0.5.11391)
131
+ sorbet-runtime (= 0.5.11391)
132
+ spoom (1.3.2)
133
+ erubi (>= 1.10.0)
134
+ prism (>= 0.19.0)
135
+ sorbet-static-and-runtime (>= 0.5.10187)
136
+ thor (>= 0.19.2)
137
+ strscan (3.1.0)
138
+ tapioca (0.14.2)
139
+ bundler (>= 2.2.25)
140
+ netrc (>= 0.11.0)
141
+ parallel (>= 1.21.0)
142
+ rbi (>= 0.1.4, < 0.2)
143
+ sorbet-static-and-runtime (>= 0.5.11087)
144
+ spoom (>= 1.2.0)
145
+ thor (>= 1.2.0)
146
+ yard-sorbet
147
+ thor (1.3.1)
148
+ tilt (2.3.0)
149
+ tzinfo (2.0.6)
150
+ concurrent-ruby (~> 1.0)
151
+ unicode-display_width (2.5.0)
152
+ uri (0.13.0)
153
+ yard (0.9.36)
154
+ yard-sorbet (0.8.1)
155
+ sorbet-runtime (>= 0.5)
156
+ yard (>= 0.9)
157
+
158
+ PLATFORMS
159
+ arm64-darwin-21
160
+
161
+ DEPENDENCIES
162
+ dotenv (>= 2)
163
+ pry (>= 0.14)
164
+ rake (~> 13.0)
165
+ rspec (~> 3.0)
166
+ rubocop (~> 1.21)
167
+ solargraph-rails (~> 0.2.0.pre)
168
+ sorbet
169
+ stability!
170
+ tapioca
171
+
172
+ BUNDLED WITH
173
+ 2.4.18
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Obie Fernandez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # Stability
2
+
3
+ Provides easy access to the Stable Image REST API provided by [stability.ai](https://platform.stability.ai/docs/api-reference).
4
+ 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,
5
+ 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
6
+ [Patterns of Application Development Using AI](https://leanpub.com/patterns-of-application-development-using-ai)
7
+
8
+ ## Installation
9
+
10
+ Install the gem and add to the application's Gemfile by executing:
11
+
12
+ $ bundle add stability
13
+
14
+ If bundler is not being used to manage dependencies, install the gem by executing:
15
+
16
+ $ gem install stability
17
+
18
+ ## Usage
19
+
20
+ TODO: Write usage instructions here
21
+
22
+ ## Development
23
+
24
+ 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.
25
+
26
+ 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).
27
+
28
+ ## Contributing
29
+
30
+ 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).
31
+
32
+ ## License
33
+
34
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
35
+
36
+ ## Code of Conduct
37
+
38
+ 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).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/object/blank"
4
+ require "active_support/core_ext/hash/indifferent_access"
5
+
6
+ require_relative "http"
7
+
8
+ module Stability
9
+ class ServerError < StandardError; end
10
+
11
+ class Client
12
+ include Stability::HTTP
13
+
14
+ # Initializes the client with optional configurations.
15
+ def initialize(api_key: nil, request_timeout: nil, uri_base: nil, extra_headers: {})
16
+ Stability.configuration.api_key = api_key if api_key
17
+ Stability.configuration.request_timeout = request_timeout if request_timeout
18
+ Stability.configuration.uri_base = uri_base if uri_base
19
+ Stability.configuration.extra_headers = extra_headers if extra_headers.any?
20
+ yield(Stability.configuration) if block_given?
21
+ end
22
+
23
+ # Performs a text-to-image generation request to the Stability API using Stable Image Core.
24
+ #
25
+ # @param prompt [String] Descriptive prompt for the desired output image. Elements, colors, and subjects should be well-defined
26
+ # for optimal results. Use the format (word:weight) to control the weight of specific words, e.g.,
27
+ # "The sky was a crisp (blue:0.3) and (green:0.8)" indicates a sky more green than blue.
28
+ #
29
+ # @param options [Hash] Additional options for the request:
30
+ #
31
+ # - aspect_ratio [String] Specifies the aspect ratio of the generated image.
32
+ # Options: "16:9", "1:1" (default), "21:9", "2:3", "3:2", "4:5", "5:4", "9:16", "9:21"
33
+ #
34
+ # - negative_prompt [String] Describes elements to be excluded from the image. Max 10000 characters.
35
+ #
36
+ # - seed [Integer] Controls the randomness of generation, where 0 uses a random seed. Range: 0 (default) to 4294967294
37
+ #
38
+ # - style_preset [String] Guides the image model towards a particular visual style.
39
+ # Options: "3d-model", "analog-film", "anime", "cinematic", "comic-book", "digital-art", "enhance", "fantasy-art",
40
+ # "isometric", "line-art", "low-poly", "modeling-compound", "neon-punk", "origami", "photographic",
41
+ # "pixel-art", "tile-texture"
42
+ #
43
+ # - output_format [String] Specifies the format of the generated image. Options: "jpeg", "png" (default), "webp"
44
+ #
45
+ # @param json [Boolean] Specifies whether to return the response as a JSON object containing a base64 encoded image or as
46
+ # image bytes directly. Default is false (image bytes directly).
47
+ #
48
+ def generate_core(prompt, options: {}, json: false)
49
+ headers = { "Accept" => json ? "application/json" : "image/*" }
50
+ parameters = { prompt: }.merge(options)
51
+ multipart_post(path: "/stable-image/generate/core", headers:, parameters:).tap do |response|
52
+ raise ServerError, "Empty response from Stability. Might be worth retrying once or twice." if response.blank?
53
+ raise ServerError, response.dig("error", "message") if response.dig("error", "message").present?
54
+ end.with_indifferent_access
55
+ end
56
+
57
+ # Performs a text-to-image or image-to-image generation request to the Stability API using Stable Diffusion 3.
58
+ #
59
+ # @param prompt [String] Descriptive prompt for the desired output image. Elements, colors, and subjects should be well-defined
60
+ # for optimal results. Use the format (word:weight) to control the weight of specific words, e.g.,
61
+ # "The sky was a crisp (blue:0.3) and (green:0.8)" indicates a sky more green than blue.
62
+ #
63
+ # @param options [Hash] Additional options for the request:
64
+ #
65
+ # - aspect_ratio [String] Specifies the aspect ratio of the generated image.
66
+ # Options: "16:9", "1:1" (default), "21:9", "2:3", "3:2", "4:5", "5:4", "9:16", "9:21"
67
+ #
68
+ # - mode [String] Controls whether this is a text-to-image or image-to-image generation.
69
+ # Options: "text-to-image" (default), "image-to-image"
70
+ #
71
+ # - image [File] Required if mode is "image-to-image". The input image file.
72
+ #
73
+ # - strength [Float] Required if mode is "image-to-image". Controls the strength of the transformation.
74
+ #
75
+ # - negative_prompt [String] Describes elements to be excluded from the image. Max 10000 characters.
76
+ #
77
+ # - model [String] Specifies the model to use for generation.
78
+ # Options: "sd3" (default), "sd3-turbo"
79
+ #
80
+ # - seed [Integer] Controls the randomness of generation, where 0 uses a random seed. Range: 0 (default) to 4294967294
81
+ #
82
+ # - output_format [String] Specifies the format of the generated image. Options: "jpeg", "png" (default)
83
+ #
84
+ # @param json [Boolean] Specifies whether to return the response as a JSON object containing a base64 encoded image or as
85
+ # image bytes directly. Default is false (image bytes directly).
86
+ #
87
+ def generate_sd3(prompt, options: {}, json: false)
88
+ headers = { "Accept" => json ? "application/json" : "image/*" }
89
+ parameters = { prompt: }.merge(options)
90
+
91
+ # Ensure required parameters for image-to-image mode
92
+ if parameters[:mode] == "image-to-image"
93
+ raise ArgumentError, "image is required for image-to-image mode" unless parameters[:image]
94
+ raise ArgumentError, "strength is required for image-to-image mode" unless parameters[:strength]
95
+ end
96
+
97
+ multipart_post(path: "/stable-image/generate/sd3", headers:, parameters:).tap do |response|
98
+ raise ServerError, "Empty response from Stability. Might be worth retrying once or twice." if response.blank?
99
+ raise ServerError, response.dig("error", "message") if response.dig("error", "message").present?
100
+ end.with_indifferent_access
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+ require "faraday/multipart"
5
+
6
+ module Stability
7
+ module HTTP
8
+ def get(path:)
9
+ conn.get(uri(path:)) do |req|
10
+ req.headers = headers
11
+ end&.body
12
+ end
13
+
14
+ def post(path:, parameters:)
15
+ conn.post(uri(path:)) do |req|
16
+ if parameters[:stream].respond_to?(:call)
17
+ req.options.on_data = to_json_stream(user_proc: parameters[:stream])
18
+ parameters[:stream] = true
19
+ end
20
+
21
+ req.headers = headers
22
+ req.body = parameters.to_json
23
+ end&.body
24
+ end
25
+
26
+ def multipart_post(path:, headers: {}, parameters: nil)
27
+ conn(multipart: true).post(uri(path:)) do |req|
28
+ req.headers = default_headers.merge(headers).merge({ "Content-Type" => "multipart/form-data" })
29
+ req.body = multipart_parameters(parameters)
30
+ end&.body
31
+ end
32
+
33
+ def delete(path:)
34
+ conn.delete(uri(path:)) do |req|
35
+ req.headers = headers
36
+ end&.body
37
+ end
38
+
39
+ private
40
+
41
+ # Given a proc, returns an outer proc that can be used to iterate over a JSON stream of chunks.
42
+ # For each chunk, the inner user_proc is called giving it the JSON object. The JSON object could
43
+ # be a data object or an error object as described in the API documentation.
44
+ #
45
+ # If the JSON object for a given data or error message is invalid, it is ignored.
46
+ #
47
+ # @param user_proc [Proc] The inner proc to call for each JSON object in the chunk.
48
+ # @return [Proc] An outer proc that iterates over a raw stream, converting it to JSON.
49
+ def to_json_stream(user_proc:)
50
+ proc do |chunk, _|
51
+ chunk.scan(/(?:data|error): (\{.*\})/i).flatten.each do |data|
52
+ user_proc.call(JSON.parse(data))
53
+ rescue JSON::ParserError
54
+ # Ignore invalid JSON.
55
+ end
56
+ end
57
+ end
58
+
59
+ def conn(multipart: false)
60
+ Faraday.new do |f|
61
+ f.options[:timeout] = Stability.configuration.request_timeout
62
+ f.request(:multipart) if multipart
63
+ f.use MiddlewareErrors if @log_errors
64
+ f.response :raise_error
65
+ f.response :json
66
+
67
+ Stability.configuration.faraday_config&.call(f)
68
+ end
69
+ end
70
+
71
+ def uri(path:)
72
+ File.join(Stability.configuration.uri_base, Stability.configuration.api_version, path)
73
+ end
74
+
75
+ def default_headers
76
+ {
77
+ "Authorization" => "Bearer #{Stability.configuration.api_key}",
78
+ "Content-Type" => "application/json"
79
+ }.merge(Stability.configuration.extra_headers)
80
+ end
81
+
82
+ def multipart_parameters(parameters)
83
+ parameters&.transform_values do |value|
84
+ next value unless value.is_a?(File)
85
+
86
+ # Doesn't seem like Stability needs mime_type yet, so not worth
87
+ # the library to figure this out. Hence the empty string
88
+ # as the second argument.
89
+ Faraday::UploadIO.new(value, "", value.path)
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stability
4
+ VERSION = "0.1.0"
5
+ end
data/lib/stability.rb ADDED
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "stability/http"
4
+ require_relative "stability/client"
5
+ require_relative "stability/version"
6
+
7
+ module Stability
8
+ class Error < StandardError; end
9
+ class ConfigurationError < Error; end
10
+
11
+ class Configuration
12
+ attr_writer :api_key
13
+ attr_accessor :api_version, :extra_headers, :faraday_config, :log_errors, :request_timeout, :uri_base
14
+
15
+ DEFAULT_API_VERSION = "v2beta"
16
+ DEFAULT_REQUEST_TIMEOUT = 120
17
+ DEFAULT_URI_BASE = "https://api.stability.ai"
18
+
19
+ def initialize
20
+ self.api_key = nil
21
+ self.api_version = DEFAULT_API_VERSION
22
+ self.extra_headers = {}
23
+ self.log_errors = false
24
+ self.request_timeout = DEFAULT_REQUEST_TIMEOUT
25
+ self.uri_base = DEFAULT_URI_BASE
26
+ end
27
+
28
+ def api_key
29
+ return @api_key if @api_key
30
+
31
+ raise ConfigurationError, "Stability AI api key missing!"
32
+ end
33
+
34
+ def faraday(&block)
35
+ self.faraday_config = block
36
+ end
37
+ end
38
+
39
+ class << self
40
+ attr_writer :configuration
41
+ end
42
+
43
+ def self.configuration
44
+ @configuration ||= Stability::Configuration.new
45
+ end
46
+
47
+ def self.configure
48
+ yield(configuration)
49
+ end
50
+ end
data/sig/stability.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Stability
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
data/stability.gemspec ADDED
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/stability/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "stability"
7
+ spec.version = Stability::VERSION
8
+ spec.authors = ["Obie Fernandez"]
9
+ spec.email = ["obiefernandez@gmail.com"]
10
+
11
+ spec.summary = "Ruby SDK for the Stability Platform API"
12
+ spec.homepage = "https://github.com/OlympiaAI/stabillity"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = ">= 3.2.2"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = "https://github.com/OlympiaAI/stability"
18
+ spec.metadata["changelog_uri"] = "https://github.com/OlympiaAI/stability/blob/main/CHANGELOG.md"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(__dir__) do
23
+ `git ls-files -z`.split("\x0").reject do |f|
24
+ (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor])
25
+ end
26
+ end
27
+ spec.bindir = "exe"
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ["lib"]
30
+
31
+ spec.add_dependency "dotenv", ">= 2"
32
+ spec.add_dependency "faraday", ">= 1"
33
+ spec.add_dependency "faraday-multipart", ">= 1"
34
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: stability
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Obie Fernandez
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-05-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: dotenv
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: faraday
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '1'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: faraday-multipart
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '1'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '1'
55
+ description:
56
+ email:
57
+ - obiefernandez@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - ".rubocop.yml"
64
+ - ".ruby-version"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - Gemfile.lock
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - lib/stability.rb
73
+ - lib/stability/client.rb
74
+ - lib/stability/http.rb
75
+ - lib/stability/version.rb
76
+ - sig/stability.rbs
77
+ - stability.gemspec
78
+ homepage: https://github.com/OlympiaAI/stabillity
79
+ licenses:
80
+ - MIT
81
+ metadata:
82
+ homepage_uri: https://github.com/OlympiaAI/stabillity
83
+ source_code_uri: https://github.com/OlympiaAI/stability
84
+ changelog_uri: https://github.com/OlympiaAI/stability/blob/main/CHANGELOG.md
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: 3.2.2
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubygems_version: 3.4.10
101
+ signing_key:
102
+ specification_version: 4
103
+ summary: Ruby SDK for the Stability Platform API
104
+ test_files: []