Skip to content

Instantly share code, notes, and snippets.

@knbknb
Last active January 22, 2025 10:38
Show Gist options
  • Save knbknb/fbff39fb65313871b3524f46c6ec4e8b to your computer and use it in GitHub Desktop.
Save knbknb/fbff39fb65313871b3524f46c6ec4e8b to your computer and use it in GitHub Desktop.
recraft-text2image.sh
#!/usr/bin/env bash
RECRAFT_API_KEY=YOU_MUST_REPLACE_THIS_WITH_YOUR_API_KEY
now=$(date +"%Y%m%d_%H%M%S")
logo_description_outfile=logo_description_$now.svg
temp_response_file=response_$now.json
logo_description=$(cat <<EOF
Imagine an abstract logo (for a company) where the top half ....
EOF
)
# Escape newlines and quotes in the logo description to make it JSON-safe for the API request
logo_description_escaped=$(echo "$logo_description" | jq -Rsa .)
# After download of SVG file, add metadata to it, via in-place editing of the raw XML content.
# Escape logo description for XML metadata inclusion,
logo_description_xml=$(echo "$logo_description" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/\"/\&quot;/g; s/'"'"'/\&apos;/g')
recraft_url="https://external.api.recraft.ai/v1/images/generations"
# Submit the request to the API and store the response in a temporary file
curl -s $recraft_url \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $RECRAFT_API_KEY" \
-d "{
\"prompt\": $logo_description_escaped,
\"style\": \"vector_illustration\",
\"model\": \"recraftv3\"
}" > $temp_response_file
# Extract the URL from the response
image_url=$(jq -r '.data[0].url' < $temp_response_file)
if [ -n "$image_url" ]; then
echo "Downloading image from $image_url..."
curl -s "$image_url" -o "$logo_description_outfile"
# Add metadata to the SVG file
echo "Adding metadata to the SVG file..."
svg_metadata="<!-- \nCreated: $now\nImage URL: $image_url\nDescription: $logo_description_xml\n-->"
#{ echo "$svg_metadata"; cat "$logo_description_outfile"; } > "$logo_description_outfile.tmp" && mv "$logo_description_outfile.tmp" "$logo_description_outfile"
echo "Image downloaded and saved as $logo_description_outfile with metadata"
else
echo "Error: Could not extract image URL from API response"
cat $temp_response_file
fi
# Clean up temporary response file
rm -f $temp_response_file
@knbknb
Copy link
Author

knbknb commented Dec 16, 2024

Adding metadata (download-url, text-description, copyright notice...) to SVG file does not work at this time. A quick and dirty method is to provide metadata an HTML comment, but a better way would be to provide real XML elements (but how)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment