2023-05-20 03:45:54 -04:00
#frozen_string_literal: true
module DiscourseAi::AiBot::Commands
class ImageCommand < Command
class << self
def name
" image "
end
def desc
2023-06-19 18:45:31 -04:00
" Renders an image from the description (remove all connector words, keep it to 40 words or less). Despite being a text based bot you can generate images! "
end
def parameters
[
Parameter . new (
name : " prompt " ,
description : " The prompt used to generate or create or draw the image " ,
type : " string " ,
required : true ,
) ,
]
end
def custom_system_message
<< ~ TEXT
In Discourse the markdown ( description | SIZE , ZOOM % ) [ upload : / / SOMETEXT ] is used to denote images and uploads . NEVER try changing the to http or https links .
ALWAYS prefer the upload : / / format if available .
When rendering multiple images place them in a [ grid ] ... [ / grid] block
TEXT
2023-05-20 03:45:54 -04:00
end
end
def result_name
" results "
end
def description_args
2023-06-20 01:44:03 -04:00
{ prompt : @last_prompt }
2023-05-20 03:45:54 -04:00
end
def chain_next_response
2023-06-19 18:45:31 -04:00
true
2023-05-20 03:45:54 -04:00
end
def process ( prompt )
2023-06-19 18:45:31 -04:00
@last_prompt = prompt = JSON . parse ( prompt ) [ " prompt " ]
2023-05-20 03:45:54 -04:00
results = DiscourseAi :: Inference :: StabilityGenerator . perform! ( prompt )
uploads = [ ]
results [ :artifacts ] . each_with_index do | image , i |
f = Tempfile . new ( " v1_txt2img_ #{ i } .png " )
f . binmode
f . write ( Base64 . decode64 ( image [ :base64 ] ) )
f . rewind
uploads << UploadCreator . new ( f , " image.png " ) . create_for ( bot_user . id )
f . unlink
end
2023-06-19 18:45:31 -04:00
raw = << ~ RAW
[ grid ]
#{
2023-05-20 03:45:54 -04:00
uploads
. map { | upload | " ![ #{ prompt . gsub ( / \ | \ ' \ " / , " " ) } |512x512, 50%]( #{ upload . short_url } ) " }
. join ( " " )
2023-06-19 18:45:31 -04:00
}
[ / grid]
RAW
{ prompt : prompt , markdown : raw , display_to_user : true }
2023-05-20 03:45:54 -04:00
end
end
end