discourse-ai/lib/inference/stability_generator.rb
Sam 6ddc17fd61
DEV: port directory structure to Zeitwerk (#319)
Previous to this change we relied on explicit loading for a files in Discourse AI.

This had a few downsides:

- Busywork whenever you add a file (an extra require relative)
- We were not keeping to conventions internally ... some places were OpenAI others are OpenAi
- Autoloader did not work which lead to lots of full application broken reloads when developing.

This moves all of DiscourseAI into a Zeitwerk compatible structure.

It also leaves some minimal amount of manual loading (automation - which is loading into an existing namespace that may or may not be there)

To avoid needing /lib/discourse_ai/... we mount a namespace thus we are able to keep /lib pointed at ::DiscourseAi

Various files were renamed to get around zeitwerk rules and minimize usage of custom inflections

Though we can get custom inflections to work it is not worth it, will require a Discourse core patch which means we create a hard dependency.
2023-11-29 15:17:46 +11:00

74 lines
1.8 KiB
Ruby

# frozen_string_literal: true
module ::DiscourseAi
module Inference
class StabilityGenerator
def self.perform!(
prompt,
width: nil,
height: nil,
api_key: nil,
engine: nil,
api_url: nil,
image_count: 4,
seed: nil
)
api_key ||= SiteSetting.ai_stability_api_key
engine ||= SiteSetting.ai_stability_engine
api_url ||= SiteSetting.ai_stability_api_url
headers = {
"Content-Type" => "application/json",
"Accept" => "application/json",
"Authorization" => "Bearer #{api_key}",
}
sdxl_allowed_dimentions = [
[1024, 1024],
[1152, 896],
[1216, 832],
[1344, 768],
[1536, 640],
[640, 1536],
[768, 1344],
[832, 1216],
[896, 1152],
]
if (!width && !height)
if engine.include? "xl"
width, height = sdxl_allowed_dimentions[0]
else
width, height = [512, 512]
end
end
payload = {
text_prompts: [{ text: prompt }],
cfg_scale: 7,
clip_guidance_preset: "FAST_BLUE",
height: width,
width: height,
samples: image_count,
steps: 30,
}
payload[:seed] = seed if seed
endpoint = "v1/generation/#{engine}/text-to-image"
response = Faraday.post("#{api_url}/#{endpoint}", payload.to_json, headers)
if response.status != 200
Rails.logger.error(
"AI stability generator failed with status #{response.status}: #{response.body}}",
)
raise Net::HTTPBadResponse
end
JSON.parse(response.body, symbolize_names: true)
end
end
end
end