1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
|
// Package config provides application configuration loading and prompt template
// helpers for ComicForge.
package config
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/spf13/viper"
"codeberg.org/snonux/comicforge/internal/image"
"codeberg.org/snonux/comicforge/internal/provider"
"codeberg.org/snonux/comicforge/internal/text"
"codeberg.org/snonux/comicforge/internal/tts"
"codeberg.org/snonux/comicforge/prompts"
)
const (
// DefaultPromptsDir is the fallback directory for Go template prompt files.
DefaultPromptsDir = "./prompts"
)
// Config holds ComicForge settings loaded from YAML, environment variables, and defaults.
type Config struct {
Provider ProviderConfig `mapstructure:"provider" yaml:"provider"`
API APIConfig `mapstructure:"api" yaml:"api"`
Models ModelConfig `mapstructure:"models" yaml:"models"`
Comic ComicConfig `mapstructure:"comic" yaml:"comic"`
Language LanguageConfig `mapstructure:"language" yaml:"language"`
Story StoryConfig `mapstructure:"story" yaml:"story"`
Styles StyleConfig `mapstructure:"styles" yaml:"styles"`
Narration NarrationConfig `mapstructure:"narration" yaml:"narration"`
PDF PDFConfig `mapstructure:"pdf" yaml:"pdf"`
PromptsDir string `mapstructure:"prompts_dir" yaml:"prompts_dir"`
}
var (
_ provider.TextConfig = (*Config)(nil)
_ provider.ImageConfig = (*Config)(nil)
_ provider.TTSConfig = (*Config)(nil)
_ text.Config = (*Config)(nil)
_ image.Config = (*Config)(nil)
_ tts.Config = (*Config)(nil)
)
// ProviderConfig stores the selected provider name for each capability.
type ProviderConfig struct {
Text string `mapstructure:"text" yaml:"text"`
Image string `mapstructure:"image" yaml:"image"`
TTS string `mapstructure:"tts" yaml:"tts"`
}
// APIConfig stores API keys and related secrets.
type APIConfig struct {
GoogleAPIKey string `mapstructure:"google_api_key" yaml:"google_api_key"`
}
// ModelConfig stores the model IDs used by each capability.
type ModelConfig struct {
Text string `mapstructure:"text" yaml:"text"`
Image string `mapstructure:"image" yaml:"image"`
ImageText string `mapstructure:"image_text" yaml:"image_text"`
TTS string `mapstructure:"tts" yaml:"tts"`
}
// ComicConfig stores comic generation knobs.
type ComicConfig struct {
StoryPages int `mapstructure:"story_pages" yaml:"story_pages"`
GalleryPages int `mapstructure:"gallery_pages" yaml:"gallery_pages"`
PanelsPerPage int `mapstructure:"panels_per_page" yaml:"panels_per_page"`
AspectRatio string `mapstructure:"aspect_ratio" yaml:"aspect_ratio"`
PromptMaxChars int `mapstructure:"prompt_max_chars" yaml:"prompt_max_chars"`
PageMaxRetries int `mapstructure:"page_max_retries" yaml:"page_max_retries"`
PageRetryBaseSeconds int `mapstructure:"page_retry_base_seconds" yaml:"page_retry_base_seconds"`
}
// LanguageConfig stores language and script labels used by prompts.
type LanguageConfig struct {
Input string `mapstructure:"input" yaml:"input"`
Output string `mapstructure:"output" yaml:"output"`
Story string `mapstructure:"story_language" yaml:"story_language"`
Script string `mapstructure:"script" yaml:"script"`
}
// StoryConfig stores story prompt knobs.
type StoryConfig struct {
Genres []string `mapstructure:"genres" yaml:"genres"`
RealisticWeight float64 `mapstructure:"realistic_weight" yaml:"realistic_weight"`
}
// StyleConfig stores prompt style pools.
type StyleConfig struct {
Comic []string `mapstructure:"comic" yaml:"comic"`
Realistic []string `mapstructure:"realistic" yaml:"realistic"`
Cartoon []string `mapstructure:"cartoon" yaml:"cartoon"`
Action90s []string `mapstructure:"action_90s" yaml:"action_90s"`
Manga []string `mapstructure:"manga" yaml:"manga"`
Horror []string `mapstructure:"horror" yaml:"horror"`
Watercolor []string `mapstructure:"watercolor" yaml:"watercolor"`
}
// NarrationConfig stores narration prompt knobs.
type NarrationConfig struct {
Voices []string `mapstructure:"voices" yaml:"voices"`
ChunkWords int `mapstructure:"chunk_words" yaml:"chunk_words"`
}
// PDFConfig controls final PDF assembly (ImageMagick).
type PDFConfig struct {
// Density is the ImageMagick -density value (DPI hint for the PDF).
Density int `mapstructure:"density" yaml:"density"`
// JPEGQuality is 0 for default encoding, or 1–100 to JPEG-compress the PDF (smaller files).
JPEGQuality int `mapstructure:"jpeg_quality" yaml:"jpeg_quality"`
// Presentation is "none", "print" (matte + ISO A4 portrait pages), or "book" (aged tilt + ISO A4 portrait pages).
Presentation string `mapstructure:"presentation" yaml:"presentation"`
}
// DefaultConfig returns a configuration populated with the initial Gemini-first defaults.
func DefaultConfig() *Config {
return &Config{
Provider: ProviderConfig{
Text: provider.Gemini,
Image: provider.Gemini,
TTS: provider.Gemini,
},
API: APIConfig{},
Models: ModelConfig{
Text: "gemini-2.5-flash",
Image: "gemini-3.1-flash-image-preview",
ImageText: "gemini-2.5-flash",
TTS: "gemini-2.5-flash-preview-tts",
},
Comic: ComicConfig{
StoryPages: 5,
GalleryPages: 5,
PanelsPerPage: 4,
AspectRatio: "16:9",
PromptMaxChars: 900,
PageMaxRetries: 5,
PageRetryBaseSeconds: 15,
},
Language: LanguageConfig{
Input: "Vocabulary",
Output: "Story",
Story: "Bulgarian",
Script: "Cyrillic",
},
Story: StoryConfig{
Genres: []string{
"a warm slice-of-life story",
"a heartfelt family drama",
"an exciting science-fiction adventure",
},
RealisticWeight: 0.4,
},
Styles: StyleConfig{
Comic: []string{
"classic comic book with bold ink outlines",
"graphic novel with dramatic shadows",
},
Realistic: []string{
"ultra-realistic DSLR photography, cinematic 35mm lens",
"cinematic realism with natural light",
},
Cartoon: []string{
"extremely cartoonish 1930s rubber-hose funny-animal comic style, original mouse-and-duck-era mascot energy, pie-cut eyes, button noses or beaks, white gloves, oversized shoes, noodle arms, squash-and-stretch bodies, round heads, huge expressions, flat candy colors, simple gag staging, absolutely no realism",
"vintage theatrical funny-animal cartoon comic style, redesign people as original anthropomorphic mascot characters with beaks or round snouts, pie-cut eyes, white gloves, oversized shoes, elastic limbs, cheerful slapstick poses, bold clean outlines, bright flat backgrounds, no realistic anatomy",
},
Action90s: []string{
"1990s superhero comic splash-page style like a bold caped hero punching a masked villain in a city, huge muscles, spandex costumes, flowing cape, explosive impact burst, speed lines, smoke, rubble, halftone print texture, heavy black inks, saturated primary colors",
"classic 90s action superhero cover style, oversized yellow masthead energy, caped spandex hero, armored villain, clenched fists, dramatic foreshortening, city skyline, explosions, speech balloons, thick ink outlines, Ben-Day dots",
},
Manga: []string{
"true monochrome Japanese shonen manga page, black ink only with grey screentone, no western color rendering, large expressive anime eyes, sharp spiky hair silhouettes, sweat drops, impact bursts, speed-line backgrounds, exaggerated emotion close-ups, dynamic diagonal manga panel language",
"authentic serialized manga action art, crisp black linework, dense screentone gradients, white paper highlights, hand-drawn Japanese comic energy, chibi reaction inset where appropriate, dramatic sound-effect shapes, cinematic close-ups, no painterly western comic coloring",
},
Horror: []string{
"vintage horror comic style, eerie shadows, gothic atmosphere, unsettling monsters, dramatic candlelit contrast, suspenseful panel staging",
"creepy supernatural horror comic style, fog, haunted architecture, anxious expressions, heavy inks, sickly green and crimson accents",
},
Watercolor: []string{
"pure transparent watercolor storybook comic style, visible cold-press paper grain, watery pigment blooms, uneven wash edges, granulation, soft bleeding colors, pale layered washes, loose pencil underdrawing, no digital airbrush, no oil-paint texture, no glossy comic coloring",
"hand-painted watercolor children's adventure style, translucent pastel washes, wet-on-wet skies, dry-brush texture, white paper highlights, delicate ink-and-pencil outlines, puddled pigment edges, airy negative space, gentle low-contrast rendering",
},
},
Narration: NarrationConfig{
Voices: []string{
"Charon",
"Fenrir",
},
ChunkWords: 100,
},
PDF: PDFConfig{
Density: 150,
JPEGQuality: 0,
Presentation: "none",
},
PromptsDir: DefaultPromptsDir,
}
}
// Load reads configuration from YAML, environment variables, and defaults.
func Load(configPath string) (*Config, error) {
cfg := DefaultConfig()
v := viper.New()
v.SetEnvPrefix("COMICFORGE")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
v.SetConfigType("yaml")
setDefaults(v, cfg)
if configPath != "" {
v.SetConfigFile(configPath)
} else {
if homeDir, err := HomeDir(); err == nil {
v.AddConfigPath(filepath.Join(homeDir, ".config", "comicforge"))
v.AddConfigPath(homeDir)
}
v.AddConfigPath(".")
v.SetConfigName("config")
}
if err := v.ReadInConfig(); err != nil {
var notFound viper.ConfigFileNotFoundError
if configPath != "" || !errors.As(err, ¬Found) {
return nil, fmt.Errorf("read config: %w", err)
}
}
if err := v.Unmarshal(cfg); err != nil {
return nil, fmt.Errorf("decode config: %w", err)
}
applyEnvFallbacks(cfg)
cfg.normalize()
if err := cfg.validate(); err != nil {
return nil, err
}
return cfg, nil
}
// TextProviderName returns the configured text provider name.
func (c *Config) TextProviderName() string {
return provider.NormalizeName(c.Provider.Text)
}
// ImageProviderName returns the configured image provider name.
func (c *Config) ImageProviderName() string {
return provider.NormalizeName(c.Provider.Image)
}
// GoogleAPIKey returns the configured Google API key.
func (c *Config) GoogleAPIKey() string {
if c == nil {
return ""
}
return c.API.GoogleAPIKey
}
// TextModel returns the configured text model name.
func (c *Config) TextModel() string {
if c == nil {
return ""
}
return c.Models.Text
}
// ImageModel returns the configured image model name.
func (c *Config) ImageModel() string {
if c == nil {
return ""
}
return c.Models.Image
}
// ImageTextModel returns the configured image-text model name.
func (c *Config) ImageTextModel() string {
if c == nil {
return ""
}
return c.Models.ImageText
}
// ComicAspectRatio returns the configured comic image aspect ratio.
func (c *Config) ComicAspectRatio() string {
if c == nil {
return ""
}
return c.Comic.AspectRatio
}
// TTSModel returns the configured text-to-speech model name.
func (c *Config) TTSModel() string {
if c == nil {
return ""
}
return c.Models.TTS
}
// TTSProviderName returns the configured TTS provider name.
func (c *Config) TTSProviderName() string {
return provider.NormalizeName(c.Provider.TTS)
}
// PromptDir returns the configured prompts directory or the default fallback.
func (c *Config) PromptDir() string {
if c == nil || strings.TrimSpace(c.PromptsDir) == "" {
return DefaultPromptsDir
}
return strings.TrimSpace(c.PromptsDir)
}
// PromptPath joins the configured prompts directory with the requested template file.
func (c *Config) PromptPath(name string) string {
return filepath.Join(c.PromptDir(), name)
}
// LoadPromptTemplate parses a Go text/template prompt file from the configured prompts directory.
func (c *Config) LoadPromptTemplate(name string) (*template.Template, error) {
path := c.PromptPath(name)
content, err := os.ReadFile(path)
if err == nil {
return parsePromptTemplate(path, content)
}
if !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("read prompt %q: %w", path, err)
}
content, err = prompts.Read(name)
if err != nil {
return nil, fmt.Errorf("read embedded prompt %q: %w", name, err)
}
return parsePromptTemplate(filepath.Base(name), content)
}
// RenderPrompt executes a prompt template with the provided data.
func (c *Config) RenderPrompt(name string, data any) (string, error) {
tmpl, err := c.LoadPromptTemplate(name)
if err != nil {
return "", err
}
var builder strings.Builder
if err := tmpl.Execute(&builder, data); err != nil {
return "", fmt.Errorf("render prompt %q: %w", name, err)
}
return builder.String(), nil
}
func parsePromptTemplate(name string, content []byte) (*template.Template, error) {
tmpl, err := template.New(filepath.Base(name)).Option("missingkey=error").Parse(string(content))
if err != nil {
return nil, fmt.Errorf("parse prompt %q: %w", name, err)
}
return tmpl, nil
}
func (c *Config) normalize() {
c.Provider.Text = provider.NormalizeName(c.Provider.Text)
c.Provider.Image = provider.NormalizeName(c.Provider.Image)
c.Provider.TTS = provider.NormalizeName(c.Provider.TTS)
if c.Provider.Text == "" {
c.Provider.Text = provider.Gemini
}
if c.Provider.Image == "" {
c.Provider.Image = provider.Gemini
}
if c.Provider.TTS == "" {
c.Provider.TTS = provider.Gemini
}
if c.PromptsDir == "" {
c.PromptsDir = DefaultPromptsDir
}
if c.PDF.Density <= 0 {
c.PDF.Density = 150
}
if c.PDF.JPEGQuality < 0 {
c.PDF.JPEGQuality = 0
}
if c.PDF.JPEGQuality > 100 {
c.PDF.JPEGQuality = 100
}
c.PDF.Presentation = strings.ToLower(strings.TrimSpace(c.PDF.Presentation))
if c.PDF.Presentation == "" {
c.PDF.Presentation = "none"
}
}
func (c *Config) validate() error {
if !text.DefaultRegistry().Has(c.Provider.Text) {
return fmt.Errorf("unknown text provider: %s", c.Provider.Text)
}
if !image.DefaultRegistry().Has(c.Provider.Image) {
return fmt.Errorf("unknown image provider: %s", c.Provider.Image)
}
if !tts.DefaultRegistry().Has(c.Provider.TTS) {
return fmt.Errorf("unknown TTS provider: %s", c.Provider.TTS)
}
switch c.PDF.Presentation {
case "none", "print", "book":
default:
return fmt.Errorf("unknown pdf.presentation %q (use none, print, or book)", c.PDF.Presentation)
}
return nil
}
func setDefaults(v *viper.Viper, cfg *Config) {
v.SetDefault("provider.text", cfg.Provider.Text)
v.SetDefault("provider.image", cfg.Provider.Image)
v.SetDefault("provider.tts", cfg.Provider.TTS)
v.SetDefault("api.google_api_key", cfg.API.GoogleAPIKey)
v.SetDefault("models.text", cfg.Models.Text)
v.SetDefault("models.image", cfg.Models.Image)
v.SetDefault("models.image_text", cfg.Models.ImageText)
v.SetDefault("models.tts", cfg.Models.TTS)
v.SetDefault("comic.story_pages", cfg.Comic.StoryPages)
v.SetDefault("comic.gallery_pages", cfg.Comic.GalleryPages)
v.SetDefault("comic.panels_per_page", cfg.Comic.PanelsPerPage)
v.SetDefault("comic.aspect_ratio", cfg.Comic.AspectRatio)
v.SetDefault("comic.prompt_max_chars", cfg.Comic.PromptMaxChars)
v.SetDefault("comic.page_max_retries", cfg.Comic.PageMaxRetries)
v.SetDefault("comic.page_retry_base_seconds", cfg.Comic.PageRetryBaseSeconds)
v.SetDefault("language.input", cfg.Language.Input)
v.SetDefault("language.output", cfg.Language.Output)
v.SetDefault("language.story_language", cfg.Language.Story)
v.SetDefault("language.script", cfg.Language.Script)
v.SetDefault("story.genres", cfg.Story.Genres)
v.SetDefault("story.realistic_weight", cfg.Story.RealisticWeight)
v.SetDefault("styles.comic", cfg.Styles.Comic)
v.SetDefault("styles.realistic", cfg.Styles.Realistic)
v.SetDefault("styles.cartoon", cfg.Styles.Cartoon)
v.SetDefault("styles.action_90s", cfg.Styles.Action90s)
v.SetDefault("styles.manga", cfg.Styles.Manga)
v.SetDefault("styles.horror", cfg.Styles.Horror)
v.SetDefault("styles.watercolor", cfg.Styles.Watercolor)
v.SetDefault("narration.voices", cfg.Narration.Voices)
v.SetDefault("narration.chunk_words", cfg.Narration.ChunkWords)
v.SetDefault("pdf.density", cfg.PDF.Density)
v.SetDefault("pdf.jpeg_quality", cfg.PDF.JPEGQuality)
v.SetDefault("pdf.presentation", cfg.PDF.Presentation)
v.SetDefault("prompts_dir", cfg.PromptsDir)
}
func applyEnvFallbacks(cfg *Config) {
if cfg == nil {
return
}
if cfg.API.GoogleAPIKey == "" {
cfg.API.GoogleAPIKey = os.Getenv("GOOGLE_API_KEY")
}
}
|