dalle

package module
v6.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 9, 2025 License: GPL-3.0 Imports: 26 Imported by: 4

README

Dalle Go Package

Trueblocks Dalle is a Go package for generating, enhancing, and annotating creative prompts and images, powering a Dalle application. It combines attribute-driven prompt generation, OpenAI integration, and image annotation in a modular, testable, and extensible design.


🚀 Features

  • Attribute-Driven Prompt Generation: Compose prompts from structured attributes (adjectives, nouns, styles, etc.).
  • Template-Based Construction: Go templates for multiple prompt formats (data, title, terse, enhanced).
  • OpenAI Integration: Enhance prompts with GPT-4 or DALL·E 3 via API.
  • Image Annotation: Overlay text on images with color/contrast analysis.
  • Series Management: Organize and persist sets of attributes for reproducibility.
  • Caching: In-memory cache for fast prompt/image retrieval.
  • Live Progress & Metrics: Phase-based progress reporting with percent and ETA plus persisted rolling phase averages and cache-hit stats.
  • Testability: Centralized mocks and dependency injection for robust testing.

🗂️ Project Structure

File/Folder Purpose
attribute.go Attribute struct and constructor
dresses.go DalleDress struct and prompt logic
series.go Series struct and attribute set management
openai.go OpenAI request/response types
prompt.go Prompt enhancement with OpenAI
annotate.go Image annotation utilities
image.go Image download and processing
database.go Embedded CSV database loading and filtering
context.go Context: templates, series, dbs, cache
testing.go Centralized test helpers and mocks
ai/ AI-related assets
output/ Output and cache files (auto-generated)

🛠️ Setup

Prerequisites
Getting Started
git clone https://github.com/TrueBlocks/trueblocks-dalle/v6.git
cd trueblocks-dalle
go mod tidy
export OPENAI_API_KEY=sk-...yourkey...

✨ Usage

Basic Prompt Generation:

import dalle "github.com/TrueBlocks/trueblocks-dalle/v6"

ctx := dalle.NewContext()
dd, err := ctx.MakeDalleDress("0x1234...")
if err != nil { panic(err) }
fmt.Println(dd.Prompt)

Enhance a Prompt:

result, err := dalle.EnhancePrompt("A cat in a hat", "author")
fmt.Println(result)

Annotate an Image:

outputPath, err := dalle.annotate("Hello World", "input.png", "bottom", 0.1)
fmt.Println("Annotated image saved to:", outputPath)

🧩 Data & Output

  • Attribute Databases: Embedded CSVs (see embedded.go). Add new CSVs to databases/ and update attribute.go if needed.
  • Output: Prompts, images, and cache files are written to output/, organized by series and type.

🧪 Testing

Run all tests:

go test ./...
  • Tests cover core logic, with mocks for file/network operations.
  • Some image annotation tests may require macOS and system fonts.

📝 Contributing

  • Open issues for bugs or features.
  • Submit PRs with clear descriptions and tests.
  • Follow Go best practices.

📜 License

This project is licensed under the GNU GPL v3. See LICENSE.


👩‍💻 Credits


💡 Tips

  • Set OPENAI_API_KEY and (optionally) DALLE_QUALITY.
  • Progress JSON is always available during generation; poll the server endpoint returning the embedded DalleDress and phase timings.
  • Extend attributes by adding CSVs and updating attribute.go.
  • Use Go’s testing/logging for debugging.
  • Caching is built-in; tune batch sizes/rate limits as needed.

🌈 Why Use Dalle Go Package?

  • Modular: Swap templates, attributes, or models easily.
  • Transparent: Open, testable, and well-documented.
  • Creative: Designed for generative art and prompt engineering.

📬 Questions?

Open an issue or reach out on GitHub. Happy prompting!


📊 Progress Reporting & Metrics

The generation pipeline emits a canonical set of phases:

setup → base_prompts → enhance_prompt → image_prep → image_wait → image_download → annotate → completed

Every request produces a JSON progress snapshot containing:

{
	"series": "simple",
	"address": "0x...",
	"currentPhase": "image_wait",
	"startedNs": 1730000000000000000,
	"percent": 37.2,
	"etaSeconds": 12.4,
	"done": false,
	"error": "",
	"cacheHit": false,
	"phases": [
		{"name":"setup","startedNs":...,"endedNs":...,"skipped":false,"error":""},
		...
	],
	"dalleDress": { /* always-present extended object; no omitempty fields */ },
	"phaseAverages": { "image_wait": 2500000000, ... }
}

Key points:

  • Fields are never omitted or null; empty slices are [].
  • percent & etaSeconds derive from an EMA of prior completed phase durations (alpha=0.2). A phase with no prior average contributes 0 to total; percent remains 0 until at least one average exists.
  • Cache hits short‑circuit: a minimal run is marked cacheHit=true and does not update EMAs or generationRuns.
  • Metrics persist to metrics/progress_phase_stats.json (schema version v1). Example:
{
	"version": "v1",
	"phaseAverages": { "image_wait": {"count": 4, "avgNs": 2100000000} },
	"generationRuns": 12,
	"cacheHits": 5
}

Testing helpers: ResetMetricsForTest(), ForceMetricsSave(), GetProgress(series,address).

Cache hit behavior: if an annotated image already exists when a request arrives, a completed progress snapshot is synthesized (if no active run) and metrics file updated with an incremented cacheHits counter only.

Concurrency: a single ProgressManager serializes per-(series,address) updates; the same DalleDress pointer is reused (treat as read‑only outside the manager).

ETA visibility: etaSeconds is 0 until sufficient historical averages exist to compute remaining time; elapsed time in the current phase is capped at its average to limit over-estimation.


Documentation

Overview

Package storage centralizes data-directory handling, series metadata persistence, and other filesystem-backed concerns (cache, output, metrics) for the DALL·E server. By isolating these responsibilities, higher‑level packages avoid duplicating path logic or environment bootstrap code.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AudioURL

func AudioURL(baseURL, series, address string) (string, error)

AudioURL resolves a relative URL (served by internal file server) for an existing or newly generated mp3. Returns empty string if generation not possible or file server base URL unknown.

func Clean

func Clean(series, address string)

Clean removes generated images and data for a given series and address.

func ConfigureManager

func ConfigureManager(opts ManagerOptions)

ConfigureManager allows callers to override default manager options.

func ContextCount

func ContextCount() int

ContextCount (testing) returns number of cached contexts.

func DeleteSeries

func DeleteSeries(seriesDir, suffix string) error

func GenerateAnnotatedImage

func GenerateAnnotatedImage(series, address string, skipImage bool, lockTTL time.Duration) (string, error)

GenerateAnnotatedImage builds (and optionally generates) an annotated image path. The image generation step is skipped if skipImage is true.

func GenerateAnnotatedImageWithBaseURL

func GenerateAnnotatedImageWithBaseURL(series, address string, skipImage bool, lockTTL time.Duration, baseURL string) (string, error)

GenerateAnnotatedImageWithBaseURL builds (and optionally generates) an annotated image path with a specific base URL.

func GenerateSpeech

func GenerateSpeech(series, address string, lockTTL time.Duration) (string, error)

GenerateSpeech ensures a text-to-speech mp3 exists for the enhanced prompt of the given address. It returns the path to the mp3. If already generated it returns existing path.

func GetAllItems added in v6.6.6

func GetAllItems() (map[string][]model.Item, error)

GetAllItems loads all database items from the cache manager into a map keyed by database name. Items are lazily loaded from embedded CSV files on first call, then cached in memory. Returns a map where keys are database names (e.g., "nouns") and values are slices of Items.

func GetItemsForDatabase added in v6.6.6

func GetItemsForDatabase(dbName string) ([]model.Item, error)

GetItemsForDatabase returns all items for a specific database. Returns an empty slice (not an error) if the database is not found.

func IsValidSeries

func IsValidSeries(series string, list []string) bool

IsValidSeries determines whether a requested series is valid given an optional list.

func ListSeries

func ListSeries() []string

ListSeries returns the list of existing series (json files) beneath output Dir/series.

func ReadToMe

func ReadToMe(series, address string) (string, error)

ReadToMe ensures the mp3 exists (generating if necessary) and always attempts playback. It returns the path if the file exists or was generated, else empty string.

func RemoveSeries

func RemoveSeries(seriesDir, suffix string) error

func ResetContextManagerForTest

func ResetContextManagerForTest()

ResetContextManagerForTest clears context cache (test helper).

func SetupTest

func SetupTest(t testing.TB, opts SetupTestOptions)

func SortDalleDress

func SortDalleDress(items []model.DalleDress, sortSpec sdk.SortSpec) error

SortDalleDress sorts in place based on field in spec

func SortDatabases

func SortDatabases(items []model.Database, sortSpec sdk.SortSpec) error

SortDatabases sorts in place based on field in spec

func SortSeries

func SortSeries(items []Series, sortSpec sdk.SortSpec) error

SortSeries sorts in place based on field in spec (suffix, modifiedAt, last)

func Speak

func Speak(series, address string) (string, error)

Speak plays (or generates then plays) the speech mp3 for the given series/address. Returns the path to the mp3 (even if play fails). Generation is skipped if file exists.

func TextToSpeech

func TextToSpeech(text string, voice string, series string, address string) (string, error)

TextToSpeech converts the given text to speech using OpenAI's audio API and writes it to the provided output directory. It returns the full path of the written mp3 file. If the OPENAI_API_KEY is missing, it returns an empty string and no error.

func UndeleteSeries

func UndeleteSeries(seriesDir, suffix string) error

Types

type Context

type Context struct {
	Series     Series
	Databases  map[string][]string
	DalleCache map[string]*model.DalleDress
	CacheMutex sync.Mutex
	// contains filtered or unexported fields
}

Context holds templates, series, dbs, and cache for prompt generation.

func NewContext

func NewContext() *Context

func (*Context) GenerateEnhanced

func (ctx *Context) GenerateEnhanced(addr string) (string, error)

GenerateEnhanced generates a literarily-enhanced prompt for the given address (Stage 1).

func (*Context) GenerateImage

func (ctx *Context) GenerateImage(address string) (string, error)

GenerateImage generates an image using the DALL-E API.

func (*Context) GenerateImageWithBaseURL

func (ctx *Context) GenerateImageWithBaseURL(address, baseURL string) (string, error)

GenerateImageWithBaseURL generates an image using the DALL-E API with a specific base URL.

func (*Context) GetEnhanced

func (ctx *Context) GetEnhanced(addr string) string

GetEnhanced returns the enhanced prompt for the given address.

func (*Context) GetPrompt

func (ctx *Context) GetPrompt(addr string) string

GetPrompt returns the generated prompt for the given address.

func (*Context) MakeDalleDress

func (ctx *Context) MakeDalleDress(addressIn string) (*model.DalleDress, error)

MakeDalleDress builds or retrieves a DalleDress for the given address using the context's templates, series, dbs, and cache.

func (*Context) ReloadDatabases

func (ctx *Context) ReloadDatabases(filter string) error

ReloadDatabases reloads databases applying filters from the specified series suffix. Now uses binary cache for improved performance while maintaining immutability.

func (*Context) Save

func (ctx *Context) Save(addr string) bool

Save generates and saves prompt data for the given address.

type ManagerOptions

type ManagerOptions struct {
	MaxContexts int
	ContextTTL  time.Duration
}

ManagerOptions controls cache sizing and expiration.

type Series

type Series struct {
	Last         int      `json:"last,omitempty"`
	Suffix       string   `json:"suffix"`
	Purpose      string   `json:"purpose,omitempty"`
	Deleted      bool     `json:"deleted,omitempty"`
	Adverbs      []string `json:"adverbs"`
	Adjectives   []string `json:"adjectives"`
	Nouns        []string `json:"nouns"`
	Emotions     []string `json:"emotions"`
	Occupations  []string `json:"occupations"`
	Actions      []string `json:"actions"`
	Artstyles    []string `json:"artstyles"`
	Litstyles    []string `json:"litstyles"`
	Colors       []string `json:"colors"`
	Viewpoints   []string `json:"viewpoints"`
	Gazes        []string `json:"gazes"`
	Backstyles   []string `json:"backstyles"`
	Compositions []string `json:"compositions"`
	ModifiedAt   string   `json:"modifiedAt,omitempty"`
}

Series represents a collection of prompt attributes and their values.

func LoadActiveSeriesModels

func LoadActiveSeriesModels(seriesDir string) ([]Series, error)

LoadActiveSeriesModels loads all non-deleted series JSON files

func LoadDeletedSeriesModels

func LoadDeletedSeriesModels(seriesDir string) ([]Series, error)

LoadDeletedSeriesModels loads all deleted series JSON files

func LoadSeriesModels

func LoadSeriesModels(seriesDir string) ([]Series, error)

LoadSeriesModels loads all series JSON files from the series folder beneath the provided dataDir

func (*Series) GetFilter

func (s *Series) GetFilter(fieldName string) ([]string, error)

GetFilter returns a string slice for the given field name in the Series.

func (*Series) Model

func (s *Series) Model(chain, format string, verbose bool, extraOpts map[string]any) coreTypes.Model

func (*Series) SaveSeries

func (s *Series) SaveSeries(series string, last int)

SaveSeries saves the Series to a file with the given filename and last index.

func (*Series) String

func (s *Series) String() string

String returns the JSON representation of the Series.

type SetupTestOptions

type SetupTestOptions struct {
	Series        []string
	ManagerConfig *ManagerOptions
}

Public test helper: creates isolated data dir with series and output, sets skip image. Intended for consumers writing tests against the dalle package.

Directories

Path Synopsis
pkg
utils
Package utils provides narrowly-scoped helpers shared across packages:
Package utils provides narrowly-scoped helpers shared across packages:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL