@project-ava-supernova/core 0.2.176 → 0.2.178

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/dist/agent/agent.d.ts +3 -0
  2. package/dist/agent/agent.d.ts.map +1 -1
  3. package/dist/agent/agent.js +44 -11
  4. package/dist/agent/agent.js.map +1 -1
  5. package/dist/agent/social-craft.d.ts +30 -67
  6. package/dist/agent/social-craft.d.ts.map +1 -1
  7. package/dist/agent/social-craft.js +58 -185
  8. package/dist/agent/social-craft.js.map +1 -1
  9. package/dist/agent/system-prompt.d.ts +10 -3
  10. package/dist/agent/system-prompt.d.ts.map +1 -1
  11. package/dist/agent/system-prompt.js +1184 -1321
  12. package/dist/agent/system-prompt.js.map +1 -1
  13. package/dist/auto/aurora-router.d.ts +1 -1
  14. package/dist/auto/aurora-router.d.ts.map +1 -1
  15. package/dist/auto/aurora-router.js +4 -1
  16. package/dist/auto/aurora-router.js.map +1 -1
  17. package/dist/auto/auto-coordinator.d.ts.map +1 -1
  18. package/dist/auto/auto-coordinator.js +2 -1
  19. package/dist/auto/auto-coordinator.js.map +1 -1
  20. package/dist/auto/longxiang-router.d.ts.map +1 -1
  21. package/dist/auto/longxiang-router.js +1 -0
  22. package/dist/auto/longxiang-router.js.map +1 -1
  23. package/dist/auto/model-router.d.ts.map +1 -1
  24. package/dist/auto/model-router.js +1 -0
  25. package/dist/auto/model-router.js.map +1 -1
  26. package/dist/auto/supernova-router.d.ts.map +1 -1
  27. package/dist/auto/supernova-router.js +3 -0
  28. package/dist/auto/supernova-router.js.map +1 -1
  29. package/dist/auto/task-classifier.d.ts.map +1 -1
  30. package/dist/auto/task-classifier.js +8 -1
  31. package/dist/auto/task-classifier.js.map +1 -1
  32. package/dist/auto/types.d.ts +1 -1
  33. package/dist/auto/types.d.ts.map +1 -1
  34. package/dist/brand/brand-kits.d.ts +217 -0
  35. package/dist/brand/brand-kits.d.ts.map +1 -0
  36. package/dist/brand/brand-kits.js +681 -0
  37. package/dist/brand/brand-kits.js.map +1 -0
  38. package/dist/brand/kit-py.d.ts +7 -0
  39. package/dist/brand/kit-py.d.ts.map +1 -0
  40. package/dist/brand/kit-py.js +49 -0
  41. package/dist/brand/kit-py.js.map +1 -0
  42. package/dist/config/schema.d.ts +5 -0
  43. package/dist/config/schema.d.ts.map +1 -1
  44. package/dist/config/schema.js.map +1 -1
  45. package/dist/creative/folder-export.d.ts +72 -0
  46. package/dist/creative/folder-export.d.ts.map +1 -0
  47. package/dist/creative/folder-export.js +463 -0
  48. package/dist/creative/folder-export.js.map +1 -0
  49. package/dist/creative/library-folders.d.ts +171 -0
  50. package/dist/creative/library-folders.d.ts.map +1 -0
  51. package/dist/creative/library-folders.js +515 -0
  52. package/dist/creative/library-folders.js.map +1 -0
  53. package/dist/creative/library-upload.d.ts +23 -0
  54. package/dist/creative/library-upload.d.ts.map +1 -0
  55. package/dist/creative/library-upload.js +152 -0
  56. package/dist/creative/library-upload.js.map +1 -0
  57. package/dist/creative/making-report.d.ts +46 -0
  58. package/dist/creative/making-report.d.ts.map +1 -0
  59. package/dist/creative/making-report.js +244 -0
  60. package/dist/creative/making-report.js.map +1 -0
  61. package/dist/creative/pack-plan-status.d.ts +18 -0
  62. package/dist/creative/pack-plan-status.d.ts.map +1 -0
  63. package/dist/creative/pack-plan-status.js +58 -0
  64. package/dist/creative/pack-plan-status.js.map +1 -0
  65. package/dist/creative/store-profiles.d.ts +46 -0
  66. package/dist/creative/store-profiles.d.ts.map +1 -0
  67. package/dist/creative/store-profiles.js +486 -0
  68. package/dist/creative/store-profiles.js.map +1 -0
  69. package/dist/docs/data/tools.d.ts.map +1 -1
  70. package/dist/docs/data/tools.js +17 -0
  71. package/dist/docs/data/tools.js.map +1 -1
  72. package/dist/index.d.ts +32 -1
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +22 -0
  75. package/dist/index.js.map +1 -1
  76. package/dist/memory/config.d.ts +12 -0
  77. package/dist/memory/config.d.ts.map +1 -1
  78. package/dist/memory/config.js +12 -0
  79. package/dist/memory/config.js.map +1 -1
  80. package/dist/memory/memory-manager.d.ts +11 -0
  81. package/dist/memory/memory-manager.d.ts.map +1 -1
  82. package/dist/memory/memory-manager.js +90 -2
  83. package/dist/memory/memory-manager.js.map +1 -1
  84. package/dist/memory/project-brain.d.ts.map +1 -1
  85. package/dist/memory/project-brain.js +2 -1
  86. package/dist/memory/project-brain.js.map +1 -1
  87. package/dist/memory/tfidf.d.ts +10 -0
  88. package/dist/memory/tfidf.d.ts.map +1 -1
  89. package/dist/memory/tfidf.js +27 -0
  90. package/dist/memory/tfidf.js.map +1 -1
  91. package/dist/portability/bundle.d.ts.map +1 -1
  92. package/dist/portability/bundle.js +1 -0
  93. package/dist/portability/bundle.js.map +1 -1
  94. package/dist/portability/factory-reset.js +1 -1
  95. package/dist/portability/factory-reset.js.map +1 -1
  96. package/dist/social/index.d.ts +57 -0
  97. package/dist/social/index.d.ts.map +1 -1
  98. package/dist/social/index.js +54 -5
  99. package/dist/social/index.js.map +1 -1
  100. package/dist/social/tag-volume.d.ts +7 -0
  101. package/dist/social/tag-volume.d.ts.map +1 -1
  102. package/dist/social/tag-volume.js +27 -0
  103. package/dist/social/tag-volume.js.map +1 -1
  104. package/dist/tools/blender/build-model.d.ts +62 -0
  105. package/dist/tools/blender/build-model.d.ts.map +1 -0
  106. package/dist/tools/blender/build-model.js +501 -0
  107. package/dist/tools/blender/build-model.js.map +1 -0
  108. package/dist/tools/blender/find-blender.d.ts +43 -0
  109. package/dist/tools/blender/find-blender.d.ts.map +1 -0
  110. package/dist/tools/blender/find-blender.js +154 -0
  111. package/dist/tools/blender/find-blender.js.map +1 -0
  112. package/dist/tools/blender/model-brief.d.ts +64 -0
  113. package/dist/tools/blender/model-brief.d.ts.map +1 -0
  114. package/dist/tools/blender/model-brief.js +117 -0
  115. package/dist/tools/blender/model-brief.js.map +1 -0
  116. package/dist/tools/blender/model-history.d.ts +42 -0
  117. package/dist/tools/blender/model-history.d.ts.map +1 -0
  118. package/dist/tools/blender/model-history.js +145 -0
  119. package/dist/tools/blender/model-history.js.map +1 -0
  120. package/dist/tools/blender/paths.d.ts +20 -0
  121. package/dist/tools/blender/paths.d.ts.map +1 -0
  122. package/dist/tools/blender/paths.js +37 -0
  123. package/dist/tools/blender/paths.js.map +1 -0
  124. package/dist/tools/blender/runner-py.d.ts +2 -0
  125. package/dist/tools/blender/runner-py.d.ts.map +1 -0
  126. package/dist/tools/blender/runner-py.js +455 -0
  127. package/dist/tools/blender/runner-py.js.map +1 -0
  128. package/dist/tools/brief-store.d.ts +28 -0
  129. package/dist/tools/brief-store.d.ts.map +1 -0
  130. package/dist/tools/brief-store.js +76 -0
  131. package/dist/tools/brief-store.js.map +1 -0
  132. package/dist/tools/check-posts.d.ts.map +1 -1
  133. package/dist/tools/check-posts.js +21 -3
  134. package/dist/tools/check-posts.js.map +1 -1
  135. package/dist/tools/design-checkin.d.ts +28 -0
  136. package/dist/tools/design-checkin.d.ts.map +1 -0
  137. package/dist/tools/design-checkin.js +74 -0
  138. package/dist/tools/design-checkin.js.map +1 -0
  139. package/dist/tools/design-docs.d.ts +37 -0
  140. package/dist/tools/design-docs.d.ts.map +1 -0
  141. package/dist/tools/design-docs.js +367 -0
  142. package/dist/tools/design-docs.js.map +1 -0
  143. package/dist/tools/design-folder.d.ts +24 -0
  144. package/dist/tools/design-folder.d.ts.map +1 -0
  145. package/dist/tools/design-folder.js +277 -0
  146. package/dist/tools/design-folder.js.map +1 -0
  147. package/dist/tools/design-fonts.d.ts +58 -0
  148. package/dist/tools/design-fonts.d.ts.map +1 -0
  149. package/dist/tools/design-fonts.js +316 -0
  150. package/dist/tools/design-fonts.js.map +1 -0
  151. package/dist/tools/design-studio-tools.d.ts +16 -0
  152. package/dist/tools/design-studio-tools.d.ts.map +1 -1
  153. package/dist/tools/design-studio-tools.js +288 -43
  154. package/dist/tools/design-studio-tools.js.map +1 -1
  155. package/dist/tools/generation-manager.d.ts +1 -1
  156. package/dist/tools/generation-manager.d.ts.map +1 -1
  157. package/dist/tools/gimp/build-image.d.ts +161 -0
  158. package/dist/tools/gimp/build-image.d.ts.map +1 -0
  159. package/dist/tools/gimp/build-image.js +900 -0
  160. package/dist/tools/gimp/build-image.js.map +1 -0
  161. package/dist/tools/gimp/find-gimp.d.ts +32 -0
  162. package/dist/tools/gimp/find-gimp.d.ts.map +1 -0
  163. package/dist/tools/gimp/find-gimp.js +149 -0
  164. package/dist/tools/gimp/find-gimp.js.map +1 -0
  165. package/dist/tools/gimp/runner-py.d.ts +2 -0
  166. package/dist/tools/gimp/runner-py.d.ts.map +1 -0
  167. package/dist/tools/gimp/runner-py.js +750 -0
  168. package/dist/tools/gimp/runner-py.js.map +1 -0
  169. package/dist/tools/making-record.d.ts +80 -0
  170. package/dist/tools/making-record.d.ts.map +1 -0
  171. package/dist/tools/making-record.js +221 -0
  172. package/dist/tools/making-record.js.map +1 -0
  173. package/dist/tools/propose-brief.d.ts.map +1 -1
  174. package/dist/tools/propose-brief.js +6 -1
  175. package/dist/tools/propose-brief.js.map +1 -1
  176. package/dist/tools/research-post.d.ts +1 -1
  177. package/dist/tools/research-post.d.ts.map +1 -1
  178. package/dist/tools/research-post.js +20 -9
  179. package/dist/tools/research-post.js.map +1 -1
  180. package/dist/tools/review-post.d.ts +25 -0
  181. package/dist/tools/review-post.d.ts.map +1 -0
  182. package/dist/tools/review-post.js +63 -0
  183. package/dist/tools/review-post.js.map +1 -0
  184. package/dist/tools/tool-registry.d.ts.map +1 -1
  185. package/dist/tools/tool-registry.js +42 -1
  186. package/dist/tools/tool-registry.js.map +1 -1
  187. package/dist/tools/tool-request-words.d.ts +7 -0
  188. package/dist/tools/tool-request-words.d.ts.map +1 -0
  189. package/dist/tools/tool-request-words.js +39 -0
  190. package/dist/tools/tool-request-words.js.map +1 -0
  191. package/dist/tools/write-post.d.ts.map +1 -1
  192. package/dist/tools/write-post.js +38 -2
  193. package/dist/tools/write-post.js.map +1 -1
  194. package/dist/tools/write-video-post.d.ts.map +1 -1
  195. package/dist/tools/write-video-post.js +10 -1
  196. package/dist/tools/write-video-post.js.map +1 -1
  197. package/package.json +2 -1
@@ -0,0 +1,750 @@
1
+ /**
2
+ * The Python that runs inside GIMP for design_build_image. A string so core
3
+ * stays a single bundle; written to the OS temp folder before each run.
4
+ * Proven on GIMP 3.2.6, 4 Nov 2026: an icon built, reopened and added to, a
5
+ * second image joining the set, and every guard refusal confirmed.
6
+ */
7
+ import { KIT_PY } from '../../brand/kit-py.js';
8
+ // prettier-ignore
9
+ export const GIMP_RUNNER_PY = String.raw `# Ava's GIMP runner. Started by design_build_image as:
10
+ # gimp-console -i --batch-interpreter python-fu-eval -b "exec(open(r'runner.py').read())" --quit
11
+ # with AVA_GIMP_JOB pointing at the job file. It installs the guard, runs Ava's
12
+ # script, then saves every image she touched as .xcf, exports a PNG of each and
13
+ # builds a preview. The last line it prints is the result.
14
+ import sys, os, json, time, traceback, shutil
15
+ import gi
16
+ gi.require_version('Gimp', '3.0')
17
+ gi.require_version('Gegl', '0.4')
18
+ from gi.repository import Gimp, Gegl, Gio
19
+
20
+ JOB = json.load(open(os.environ['AVA_GIMP_JOB'], encoding='utf-8'))
21
+ ASSET_DIR = os.path.realpath(JOB['assetDir'])
22
+ STARTED = time.time()
23
+ result = {'ok': False, 'files': [], 'warnings': [], 'images': [], 'report': [], 'looks': []}
24
+ ${KIT_PY}
25
+
26
+ def emit():
27
+ sys.stdout.write('\n@@AVA_RESULT@@' + json.dumps(result) + '\n')
28
+ sys.stdout.flush()
29
+
30
+ # ── The guard ────────────────────────────────────────────────────────────────
31
+ # Same as Blender's. GIMP's own file plug-ins run in other processes and are
32
+ # not seen here, which is why the tool also refuses absolute paths in the
33
+ # script itself. A guard, not a sandbox.
34
+ _TMP = os.path.join(ASSET_DIR, '.tmp')
35
+ os.makedirs(_TMP, exist_ok=True)
36
+ import tempfile
37
+ tempfile.tempdir = _TMP
38
+ _ALLOWED = [os.path.normcase(ASSET_DIR)]
39
+ def _inside(p):
40
+ try:
41
+ rp = os.path.normcase(os.path.realpath(os.fsdecode(p)))
42
+ except Exception:
43
+ return False
44
+ return any(rp == a or rp.startswith(a.rstrip(os.sep) + os.sep) for a in _ALLOWED)
45
+ _BLOCKED = {
46
+ 'subprocess.Popen': 'starting other programs', 'os.system': 'starting other programs',
47
+ 'os.exec': 'starting other programs', 'os.posix_spawn': 'starting other programs',
48
+ 'os.spawn': 'starting other programs', 'os.startfile': 'opening files in other programs',
49
+ 'os.kill': 'stopping other programs', 'webbrowser.open': 'opening a browser',
50
+ 'socket.connect': 'network access', 'socket.bind': 'network access',
51
+ 'socket.getaddrinfo': 'network access', 'socket.gethostbyname': 'network access',
52
+ 'urllib.Request': 'network access', 'ctypes.dlopen': 'loading native code',
53
+ 'ctypes.dlsym': 'calling native code', 'ctypes.call_function': 'calling native code',
54
+ 'winreg.CreateKey': 'changing the registry', 'winreg.SetValue': 'changing the registry',
55
+ 'winreg.DeleteKey': 'changing the registry', 'winreg.DeleteValue': 'changing the registry',
56
+ }
57
+ _WRITE_ARGS = {
58
+ 'os.remove': (0,), 'os.rmdir': (0,), 'os.mkdir': (0,), 'os.chmod': (0,),
59
+ 'os.truncate': (0,), 'os.utime': (0,), 'shutil.rmtree': (0,),
60
+ 'os.rename': (0, 1), 'shutil.move': (0, 1), 'shutil.copyfile': (1,),
61
+ 'shutil.copytree': (1,), 'os.symlink': (1,), 'os.link': (1,),
62
+ }
63
+ _WRITE_FLAGS = os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_TRUNC
64
+ def _refuse(why):
65
+ raise PermissionError(f'Blocked by the Design Studio guard: {why}. '
66
+ f'Scripts here may only make the image and write inside its own folder (ASSET_DIR).')
67
+ def _hook(event, args):
68
+ if event in _BLOCKED:
69
+ _refuse(_BLOCKED[event])
70
+ if event == 'open':
71
+ path, mode, flags = (list(args) + [None, None, 0])[:3]
72
+ if path is None or isinstance(path, int):
73
+ return
74
+ writing = (isinstance(mode, str) and any(c in mode for c in 'wax+')) or \
75
+ (mode is None and isinstance(flags, int) and flags & _WRITE_FLAGS)
76
+ if writing and not _inside(path):
77
+ _refuse(f'writing outside the folder ({os.fsdecode(path)})')
78
+ elif event in _WRITE_ARGS:
79
+ for i in _WRITE_ARGS[event]:
80
+ if i < len(args) and args[i] is not None and not isinstance(args[i], int) and not _inside(args[i]):
81
+ _refuse(f'changing files outside the folder ({os.fsdecode(args[i])})')
82
+
83
+ # ── Helpers ──────────────────────────────────────────────────────────────────
84
+ _open = {} # name -> Gimp.Image she touched this run
85
+ _placed = [] # files brought in with ava_place, for the making record
86
+ result['fonts'] = {}
87
+
88
+ def _file(path):
89
+ return Gio.File.new_for_path(path)
90
+
91
+ def _fonts_in(img):
92
+ """Every font used by a text layer in the saved image, inside groups too:
93
+ hers or ones the person typed by hand. For the making record."""
94
+ found = set()
95
+ def walk(layers):
96
+ for l in layers:
97
+ try:
98
+ if l.is_group():
99
+ walk(l.get_children())
100
+ elif l.is_text_layer():
101
+ t = l if hasattr(l, 'get_font') else Gimp.Item.get_by_id(l.get_id())
102
+ found.add(t.get_font().get_name())
103
+ except Exception:
104
+ found.add('?')
105
+ walk(img.get_layers())
106
+ return sorted(found)
107
+
108
+ def _safe_name(name):
109
+ n = ''.join(c if c.isalnum() or c in '-_' else '-' for c in str(name))
110
+ while '--' in n:
111
+ n = n.replace('--', '-')
112
+ n = n.strip('-')
113
+ if not n:
114
+ raise ValueError('an image needs a name')
115
+ return n
116
+
117
+ def ava_image(name=None, width=1024, height=1024):
118
+ """The image called 'name' in this piece of work: opens its saved .xcf —
119
+ including anything the person changed by hand in GIMP — or makes a new
120
+ transparent one the first time. With no name, the work's only image, or the
121
+ one named after the work. Call once per image; a set is several names.
122
+ Everything you touch is saved and exported after your script. Each run is a
123
+ new GIMP: this is the only way to reach saved work."""
124
+ saved = sorted(f[:-4] for f in os.listdir(ASSET_DIR) if f.endswith('.xcf'))
125
+ if name is None:
126
+ name = saved[0] if len(saved) == 1 else JOB.get('name') or 'image'
127
+ name = _safe_name(name)
128
+ if name in _open:
129
+ return _open[name]
130
+ # One piece of work splitting into two files cost her eight runs: a name
131
+ # that differs only in case or punctuation is the same image.
132
+ same = [s for s in saved if s.lower().replace('-', '') == name.lower().replace('-', '')]
133
+ if same:
134
+ name = same[0]
135
+ if name in _open:
136
+ return _open[name]
137
+ xcf = os.path.join(ASSET_DIR, name + '.xcf')
138
+ if os.path.exists(xcf):
139
+ img = Gimp.file_load(Gimp.RunMode.NONINTERACTIVE, _file(xcf))
140
+ else:
141
+ img = Gimp.Image.new(width, height, Gimp.ImageBaseType.RGB)
142
+ if saved:
143
+ result['warnings'].append(f'ava_image("{name}") started a NEW image. This work already has: {saved}. If this is a new piece of the set, carry on; if you meant one of those, use its exact name.')
144
+ _open[name] = img
145
+ return img
146
+
147
+ def ava_layer(image, name='Layer', fill=None):
148
+ """A new transparent layer the size of the image, on top. fill = a colour
149
+ like '#f0a24b' floods it."""
150
+ w, h = image.get_width(), image.get_height()
151
+ lay = Gimp.Layer.new(image, name, w, h, Gimp.ImageType.RGBA_IMAGE, 100, Gimp.LayerMode.NORMAL)
152
+ image.insert_layer(lay, None, 0)
153
+ if fill:
154
+ Gimp.context_set_foreground(Gegl.Color.new(fill))
155
+ lay.fill(Gimp.FillType.FOREGROUND)
156
+ return lay
157
+
158
+ def ava_place(image, path, name=None):
159
+ """Bring an image file into 'image' as a new layer — a Blender render, a
160
+ generated reference, another piece of the set. 'path' inside ASSET_DIR."""
161
+ full = path if os.path.isabs(path) else os.path.join(ASSET_DIR, path)
162
+ lay = Gimp.file_load_layer(Gimp.RunMode.NONINTERACTIVE, image, _file(full))
163
+ # The making record lists what was brought in. A kit logo is named by KIT.
164
+ inside = os.path.normcase(os.path.abspath(full)).startswith(os.path.normcase(os.path.abspath(ASSET_DIR)) + os.sep)
165
+ rel = os.path.relpath(full, ASSET_DIR).replace(os.sep, '/') if inside else os.path.basename(full)
166
+ if rel not in _placed:
167
+ _placed.append(rel)
168
+ if name:
169
+ lay.set_name(name)
170
+ image.insert_layer(lay, None, 0)
171
+ return lay
172
+
173
+ def ava_filter(layer, op, **props):
174
+ """Run a GEGL filter on a layer and keep the result, e.g.
175
+ ava_filter(lay, 'gegl:dropshadow', x=4.0, y=4.0, radius=8.0).
176
+ Underscores in names become dashes."""
177
+ f = Gimp.DrawableFilter.new(layer, op, '')
178
+ cfg = f.get_config()
179
+ for k, v in props.items():
180
+ k = k.replace('_', '-')
181
+ if isinstance(v, str) and v.startswith('#'):
182
+ v = Gegl.Color.new(v)
183
+ cfg.set_property(k, v)
184
+ f.update()
185
+ layer.merge_filter(f)
186
+ return layer
187
+
188
+ def ava_export(image, filename, size=None):
189
+ """Export a flattened copy into ASSET_DIR/exports — size=(w, h) for an
190
+ exact size; PNG keeps transparency. The layered source is untouched."""
191
+ out = os.path.join(ASSET_DIR, 'exports')
192
+ os.makedirs(out, exist_ok=True)
193
+ _visible(image)
194
+ copy = image.duplicate()
195
+ copy.merge_visible_layers(Gimp.MergeType.CLIP_TO_IMAGE)
196
+ if size:
197
+ copy.scale(int(size[0]), int(size[1]))
198
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, copy, _file(os.path.join(out, filename)), None)
199
+ copy.delete()
200
+ print(f'AVA_EXPORT: exports/{filename}')
201
+ return 'exports/' + filename
202
+
203
+
204
+ _new_finals = []
205
+
206
+ def ava_final(image, filename, size=None):
207
+ """Make a finished file: the real thing, not a test. It goes in final/, shows
208
+ on the stage and in the Library, and is what brand kits offer. Use it when
209
+ the piece is done and they are happy. A run that fails adds nothing."""
210
+ _visible(image)
211
+ out = os.path.join(ASSET_DIR, 'final')
212
+ os.makedirs(out, exist_ok=True)
213
+ copy = image.duplicate()
214
+ copy.merge_visible_layers(Gimp.MergeType.CLIP_TO_IMAGE)
215
+ if size:
216
+ copy.scale(int(size[0]), int(size[1]))
217
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, copy, _file(os.path.join(out, filename)), None)
218
+ copy.delete()
219
+ _new_finals.append('final/' + filename)
220
+ print(f'AVA_FINAL: final/{filename}')
221
+ return 'final/' + filename
222
+
223
+
224
+ # ── Drawing helpers ──────────────────────────────────────────────────────────
225
+ # Her first logo lost 5 of 11 runs to GIMP 2 habits: a tuple where 3.2 wants
226
+ # separate numbers, Image.select_all, ChannelOps.ADD_EXCLUDE, layer.name. These
227
+ # are the verified 3.2 calls behind one shape vocabulary, so a step spends its
228
+ # run on the design and not on the API (4 Nov 2026).
229
+ Gimp.context_set_antialias(True)
230
+
231
+ _OPS = {'replace': Gimp.ChannelOps.REPLACE, 'add': Gimp.ChannelOps.ADD,
232
+ 'subtract': Gimp.ChannelOps.SUBTRACT, 'intersect': Gimp.ChannelOps.INTERSECT}
233
+
234
+ def _select(image, shape, op='replace'):
235
+ mode = _OPS[op]
236
+ if isinstance(shape, dict):
237
+ if 'rect' in shape:
238
+ x, y, w, h = shape['rect']
239
+ r = shape.get('radius', 0)
240
+ if r:
241
+ image.select_round_rectangle(mode, x, y, w, h, r, r)
242
+ else:
243
+ image.select_rectangle(mode, x, y, w, h)
244
+ elif 'ellipse' in shape:
245
+ x, y, w, h = shape['ellipse']
246
+ image.select_ellipse(mode, x, y, w, h)
247
+ elif 'svg' in shape:
248
+ w, h = image.get_width(), image.get_height()
249
+ svg = f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}"><path d="{shape["svg"]}"/></svg>'
250
+ ok, paths = image.import_paths_from_string(svg, len(svg), True, False)
251
+ if not ok or not paths:
252
+ raise ValueError('That SVG path could not be read. Use d-attribute syntax: "M 10 10 C 40 0, 60 0, 90 10 Z"')
253
+ image.select_item(mode, paths[0])
254
+ for p in paths:
255
+ image.remove_path(p)
256
+ else:
257
+ raise ValueError('A shape is a list of points, or rect=(x,y,w,h), ellipse=(x,y,w,h), or svg="M ... Z"')
258
+ else:
259
+ pts = [float(n) for n in shape]
260
+ if len(pts) < 6 or len(pts) % 2:
261
+ raise ValueError('A polygon is a flat list: [x1, y1, x2, y2, x3, y3, ...]')
262
+ image.select_polygon(mode, pts)
263
+
264
+ def _shapes(shape):
265
+ return shape if isinstance(shape, tuple) else (shape,)
266
+
267
+ def ava_fill(layer, shape, colour):
268
+ """Fill a shape on a layer. shape: [x1,y1,x2,y2,...], dict(rect=(x,y,w,h),
269
+ radius=12), dict(ellipse=(x,y,w,h)), or dict(svg="M 10 10 C ... Z") for
270
+ smooth curves. Several shapes as a tuple are filled together."""
271
+ image = layer.get_image()
272
+ for i, s in enumerate(_shapes(shape)):
273
+ _select(image, s, 'replace' if i == 0 else 'add')
274
+ Gimp.context_set_foreground(Gegl.Color.new(colour))
275
+ layer.edit_fill(Gimp.FillType.FOREGROUND)
276
+ Gimp.Selection.none(image)
277
+ return layer
278
+
279
+ def ava_cut(layer, shape):
280
+ """Remove a shape from a layer: real transparency, for negative space."""
281
+ image = layer.get_image()
282
+ for i, s in enumerate(_shapes(shape)):
283
+ _select(image, s, 'replace' if i == 0 else 'add')
284
+ layer.edit_clear()
285
+ Gimp.Selection.none(image)
286
+ return layer
287
+
288
+ def ava_gradient(layer, shape, start, end, y0, y1):
289
+ """Fill a shape with a vertical gradient between two colours, top to bottom
290
+ from y0 to y1. Good for edge light and metal on a flat mark."""
291
+ image = layer.get_image()
292
+ for i, s in enumerate(_shapes(shape)):
293
+ _select(image, s, 'replace' if i == 0 else 'add')
294
+ Gimp.context_set_foreground(Gegl.Color.new(start))
295
+ Gimp.context_set_background(Gegl.Color.new(end))
296
+ Gimp.context_set_gradient_fg_bg_rgb()
297
+ layer.edit_gradient_fill(Gimp.GradientType.LINEAR, 0.0, False, 1, 0.0, False, 0.0, float(y0), 0.0, float(y1))
298
+ Gimp.Selection.none(image)
299
+ return layer
300
+
301
+ def ava_fonts(match=''):
302
+ """Font names installed here that contain 'match'."""
303
+ return sorted(f.get_name() for f in Gimp.fonts_get_list(match))
304
+
305
+ # ── Layers ───────────────────────────────────────────────────────────────────
306
+ # Thirteen of the title logo's 24 failed runs were guesses at these jobs:
307
+ # layer.duplicate, lower_layer, layer.remove, moving layers between images.
308
+
309
+ def _named(image, ref):
310
+ if not isinstance(ref, str):
311
+ return ref
312
+ for l in image.get_layers():
313
+ if l.get_name() == ref:
314
+ return l
315
+ raise ValueError(f'No layer called "{ref}". Layers here: {[l.get_name() for l in image.get_layers()]}')
316
+
317
+ def ava_copy_layer(layer, name=None, into=None):
318
+ """Copy a layer, on top of its own image or of another one (into=image)."""
319
+ dest = into or layer.get_image()
320
+ copy = Gimp.Layer.new_from_drawable(layer, dest)
321
+ dest.insert_layer(copy, None, 0)
322
+ _, x, y = layer.get_offsets()
323
+ copy.set_offsets(x, y)
324
+ if name:
325
+ copy.set_name(name)
326
+ return copy
327
+
328
+ def ava_remove(layer):
329
+ """Delete a layer."""
330
+ layer.get_image().remove_layer(layer)
331
+
332
+ def ava_move(layer, to=None, above=None, below=None):
333
+ """Change a layer's place: to='top', to='bottom', above=other or below=other."""
334
+ image = layer.get_image()
335
+ last = len(image.get_layers()) - 1
336
+ now = image.get_item_position(layer)
337
+ if to == 'top':
338
+ pos = 0
339
+ elif to == 'bottom':
340
+ pos = last
341
+ elif above is not None:
342
+ ref = image.get_item_position(_named(image, above))
343
+ pos = ref if ref < now else ref - 1
344
+ elif below is not None:
345
+ ref = image.get_item_position(_named(image, below))
346
+ pos = ref + 1 if ref < now else ref
347
+ else:
348
+ raise ValueError("Say where: to='top', to='bottom', above=layer or below=layer")
349
+ image.reorder_item(layer, None, max(0, min(last, pos)))
350
+ return layer
351
+
352
+ def _visible(image):
353
+ if not any(l.get_visible() for l in image.get_layers()):
354
+ raise ValueError('Nothing is visible in this image: every layer is hidden, or it has no layers.')
355
+
356
+ def ava_merged(image, layers=None, name='Merged'):
357
+ """A merged copy of some layers as ONE new layer on top of the same image,
358
+ leaving the originals editable. layers = names or layers; default is
359
+ everything visible. This is the safe way to derive a glow or a shadow."""
360
+ copy = image.duplicate()
361
+ if layers is not None:
362
+ keep = {l if isinstance(l, str) else l.get_name() for l in layers}
363
+ missing = keep - {l.get_name() for l in copy.get_layers()}
364
+ if missing:
365
+ raise ValueError(f'No layer called {sorted(missing)}. Layers here: {[l.get_name() for l in copy.get_layers()]}')
366
+ for l in copy.get_layers():
367
+ l.set_visible(l.get_name() in keep)
368
+ _visible(copy)
369
+ merged = copy.merge_visible_layers(Gimp.MergeType.CLIP_TO_IMAGE)
370
+ lay = Gimp.Layer.new_from_drawable(merged, image)
371
+ image.insert_layer(lay, None, 0)
372
+ _, x, y = merged.get_offsets()
373
+ lay.set_offsets(x, y)
374
+ lay.set_name(name)
375
+ lay.set_mode(Gimp.LayerMode.NORMAL)
376
+ lay.set_opacity(100.0)
377
+ lay.set_visible(True)
378
+ copy.delete()
379
+ return lay
380
+
381
+ def ava_glow(image, layers=None, radius=24.0, opacity=50.0, colour=None, name='Glow'):
382
+ """A real glow on its own switchable layer: a blurred merged copy, in Screen
383
+ mode. Call it twice for a tight bloom plus a wide halo. opacity is 0-100."""
384
+ if 0 < opacity <= 1:
385
+ raise ValueError(f'opacity is 0-100, so {opacity} would be invisible. Did you mean {opacity * 100:g}?')
386
+ lay = ava_merged(image, layers, name)
387
+ lay.resize_to_image_size() # a blur cannot spread past the layer's edge
388
+ if colour:
389
+ ava_filter(lay, 'gegl:color-overlay', value=colour)
390
+ ava_filter(lay, 'gegl:gaussian-blur', std_dev_x=float(radius), std_dev_y=float(radius))
391
+ lay.set_mode(Gimp.LayerMode.SCREEN)
392
+ lay.set_opacity(float(opacity))
393
+ return lay
394
+
395
+ def ava_pixel(image, x, y):
396
+ """The colour you would really see at x, y in the whole image, as '#RRGGBB',
397
+ or '#RRGGBBAA' where it isn't solid. Image coordinates, all layers combined."""
398
+ copy = image.duplicate()
399
+ _visible(copy)
400
+ merged = copy.merge_visible_layers(Gimp.MergeType.CLIP_TO_IMAGE)
401
+ _, ox, oy = merged.get_offsets()
402
+ w, h = merged.get_width(), merged.get_height()
403
+ lx, ly = int(x) - ox, int(y) - oy
404
+ if not (0 <= lx < w and 0 <= ly < h):
405
+ copy.delete()
406
+ return '#00000000'
407
+ c = merged.get_pixel(lx, ly)
408
+ copy.delete()
409
+ r, g, b, a = c.get_rgba_with_space(None)
410
+ hex_ = '#%02X%02X%02X' % tuple(int(round(max(0.0, min(1.0, v)) * 255)) for v in (r, g, b))
411
+ return hex_ if a >= 0.999 else hex_ + '%02X' % int(round(a * 255))
412
+
413
+ _TEST_NAMES = ('test', 'compare', 'comparison', 'thumb', 'proof', 'tmp', 'temp', 'scratch', 'draft', 'check', 'trial')
414
+
415
+ def _is_test(name):
416
+ low = name.lower()
417
+ return any(low == t or low.startswith((t + '-', t + '_', t + ' ')) for t in _TEST_NAMES)
418
+
419
+ def ava_images():
420
+ """The saved images in this work, by name."""
421
+ return sorted(f[:-4] for f in os.listdir(ASSET_DIR) if f.endswith('.xcf'))
422
+
423
+ # ── Seeing the work ──────────────────────────────────────────────────────────
424
+ # She only ever got the preview: every image in the folder on one sheet at
425
+ # 256px. Her exports and comparison sheets never reached her, so she measured
426
+ # pixels instead of looking (4 Nov 2026).
427
+ _LOOK_DIR = os.path.join(ASSET_DIR, '.look')
428
+ MAX_LOOKS = 4
429
+ _looks = []
430
+
431
+ def _path(p):
432
+ full = p if os.path.isabs(p) else os.path.join(ASSET_DIR, p)
433
+ if not os.path.exists(full):
434
+ raise ValueError(f'There is no file at {p}. Paths are relative to the work, e.g. exports/name.png or references/art.png.')
435
+ return full
436
+
437
+ def _load(what):
438
+ if isinstance(what, str):
439
+ return Gimp.file_load(Gimp.RunMode.NONINTERACTIVE, _file(_path(what)))
440
+ return what.duplicate()
441
+
442
+ def _is_colour(on):
443
+ return isinstance(on, str) and on.startswith('#')
444
+
445
+ def _keep_look(img, label):
446
+ if len(_looks) >= MAX_LOOKS:
447
+ result['warnings'].append(f'Only {MAX_LOOKS} looks come back per run; "{label}" was left out.')
448
+ return
449
+ os.makedirs(_LOOK_DIR, exist_ok=True)
450
+ path = os.path.join(_LOOK_DIR, f'{len(_looks) + 1}.png')
451
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, img, _file(path), None)
452
+ _looks.append({'file': os.path.basename(path), 'label': label})
453
+
454
+ def ava_show(what, crop=None, on='#24242c', label=None):
455
+ """Look at something as it really is, up to 1024px: an image, or a file such
456
+ as 'exports/logo.png'. crop=(x, y, w, h) zooms in. on= is what shows through
457
+ transparency: a colour, or a picture in the work such as
458
+ 'references/title.png'. Hidden layers stay hidden. Up to 4 come back to you."""
459
+ img = _load(what)
460
+ _visible(img)
461
+ if crop:
462
+ x, y, w, h = [int(n) for n in crop]
463
+ img.crop(w, h, x, y)
464
+ W, H = img.get_width(), img.get_height()
465
+ _lay_on(img, on)
466
+ img.flatten()
467
+ k = 1024 / max(W, H)
468
+ if k < 1 or crop:
469
+ k = min(k, 8)
470
+ Gimp.context_set_interpolation(Gimp.InterpolationType.NONE if k > 1 else Gimp.InterpolationType.CUBIC)
471
+ img.scale(max(1, int(W * k)), max(1, int(H * k)))
472
+ Gimp.context_set_interpolation(Gimp.InterpolationType.CUBIC)
473
+ _keep_look(img, label or (what if isinstance(what, str) else 'the image'))
474
+ img.delete()
475
+
476
+ def _lay_on(img, back):
477
+ """Put a colour or a picture behind everything, as a real bottom layer, so
478
+ Screen glows and the like composite against it as they will in use."""
479
+ W, H = img.get_width(), img.get_height()
480
+ if _is_colour(back):
481
+ bg = Gimp.Layer.new(img, 'bg', W, H, Gimp.ImageType.RGBA_IMAGE, 100, Gimp.LayerMode.NORMAL)
482
+ img.insert_layer(bg, None, len(img.get_layers()))
483
+ Gimp.context_set_foreground(Gegl.Color.new(back))
484
+ bg.fill(Gimp.FillType.FOREGROUND)
485
+ else:
486
+ bg = Gimp.file_load_layer(Gimp.RunMode.NONINTERACTIVE, img, _file(_path(back)))
487
+ img.insert_layer(bg, None, len(img.get_layers()))
488
+ bg.scale(W, H, False)
489
+ bg.set_offsets(0, 0)
490
+
491
+ def ava_proof(what, on=None, widths=(256, 120, 64), label=None):
492
+ """The proof sheet: the piece, cropped tight, composited large on each
493
+ background, with its real small sizes in true pixels below. on= colours
494
+ and/or pictures in the work, e.g. ('references/title.png', '#101014'); with
495
+ none, the kit's own surface beside plain light and mid, so work is tested
496
+ where it will live. Hide any backdrop layer first. Saved as
497
+ exports/proof.png and shown to you."""
498
+ if on is None:
499
+ on = (KIT.colour('surface'), '#f4f4f4', '#808080') if KIT else ('#f4f4f4', '#808080', '#101014')
500
+ src = _load(what)
501
+ _visible(src)
502
+ W, H = src.get_width(), src.get_height()
503
+ merged = src.merge_visible_layers(Gimp.MergeType.CLIP_TO_IMAGE)
504
+ src.select_item(Gimp.ChannelOps.REPLACE, merged)
505
+ bounds = Gimp.Selection.bounds(src)
506
+ src.delete()
507
+ x1, y1, x2, y2 = bounds[2:6] if bounds[1] else (0, 0, W, H)
508
+ pad = max(x2 - x1, y2 - y1) // 24
509
+ x1, y1, x2, y2 = max(0, x1 - pad), max(0, y1 - pad), min(W, x2 + pad), min(H, y2 + pad)
510
+ sw, sh = x2 - x1, y2 - y1
511
+ os.makedirs(_LOOK_DIR, exist_ok=True)
512
+ backs = [on] if isinstance(on, str) else list(on)
513
+ cw, big, strip = 1024 // len(backs), 300, 170
514
+ sheet = Gimp.Image.new(cw * len(backs), big + strip, Gimp.ImageBaseType.RGB)
515
+ def place(path, w, h, x, y):
516
+ lay = Gimp.file_load_layer(Gimp.RunMode.NONINTERACTIVE, sheet, _file(path))
517
+ sheet.insert_layer(lay, None, 0)
518
+ lay.scale(w, h, False)
519
+ lay.set_offsets(x, y)
520
+ Gimp.context_set_interpolation(Gimp.InterpolationType.CUBIC)
521
+ left_out = set()
522
+ for i, back in enumerate(backs):
523
+ x0 = i * cw
524
+ tile = _load(what)
525
+ _lay_on(tile, back)
526
+ tile.flatten()
527
+ # On a picture the large view is the whole frame, the piece where it
528
+ # really sits; a tight crop of a picture only reads as a patch.
529
+ full_path = None
530
+ if not _is_colour(back):
531
+ full_path = os.path.join(_LOOK_DIR, f'proof-{i}-full.png')
532
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, tile, _file(full_path), None)
533
+ tile.crop(sw, sh, x1, y1)
534
+ tile_path = os.path.join(_LOOK_DIR, f'proof-{i}.png')
535
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, tile, _file(tile_path), None)
536
+ tile.delete()
537
+ bg = Gimp.Layer.new(sheet, 'bg', cw, big + strip, Gimp.ImageType.RGBA_IMAGE, 100, Gimp.LayerMode.NORMAL)
538
+ sheet.insert_layer(bg, None, 0)
539
+ Gimp.context_set_foreground(Gegl.Color.new(back if _is_colour(back) else '#101014'))
540
+ bg.fill(Gimp.FillType.FOREGROUND)
541
+ bg.set_offsets(x0, 0)
542
+ big_w, big_h = (W, H) if full_path else (sw, sh)
543
+ k = min((cw - 24) / big_w, (big - 24) / big_h)
544
+ w, h = max(1, int(big_w * k)), max(1, int(big_h * k))
545
+ place(full_path or tile_path, w, h, x0 + (cw - w) // 2, (big - h) // 2)
546
+ px, py, row = x0 + 12, big + 8, 0
547
+ for wide in widths:
548
+ wide = int(wide)
549
+ h = max(1, round(sh * wide / sw))
550
+ if px > x0 + 12 and px + wide > x0 + cw - 8:
551
+ px, py, row = x0 + 12, py + row + 10, 0
552
+ if wide > cw - 20 or py + h > big + strip - 6:
553
+ left_out.add(wide)
554
+ continue
555
+ place(tile_path, wide, h, px, py)
556
+ px += wide + 12
557
+ row = max(row, h)
558
+ if left_out:
559
+ result['warnings'].append(f'The proof sheet had no room for widths {sorted(left_out)}px. Use fewer backgrounds or show that size with ava_show.')
560
+ sheet.flatten()
561
+ out = os.path.join(ASSET_DIR, 'exports')
562
+ os.makedirs(out, exist_ok=True)
563
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, sheet, _file(os.path.join(out, 'proof.png')), None)
564
+ print('AVA_EXPORT: exports/proof.png')
565
+ _keep_look(sheet, label or f'proof sheet, small widths {list(widths)}px')
566
+ sheet.delete()
567
+
568
+ # ── The report after every run ───────────────────────────────────────────────
569
+ # What the file really is, so a mistake shows without guessing: her glow sat at
570
+ # opacity 0.55 of 100 for about 12 runs, and opaque layers hid her wordmark for 12.
571
+ def _report(name, img):
572
+ W, H = img.get_width(), img.get_height()
573
+ lines, warns = [f'{name} ({W}×{H}), top layer first:'], []
574
+ layers = img.get_layers()
575
+ hiding = None
576
+ for l in layers[:40]:
577
+ n = l.get_name()
578
+ _, x, y = l.get_offsets()
579
+ w, h = l.get_width(), l.get_height()
580
+ op, on = l.get_opacity(), l.get_visible()
581
+ mode = l.get_mode().value_nick
582
+ try:
583
+ ink = (l.histogram(Gimp.HistogramChannel.ALPHA, 0.0, 1.0)[1] / 255) if l.has_alpha() else 1.0
584
+ except Exception:
585
+ ink = None
586
+ kind = 'text, ' if l.is_text_layer() else ''
587
+ lines.append(f' "{n}" {kind}{w}×{h} at {x},{y} · {mode} · opacity {op:g} · {"on" if on else "HIDDEN"}' +
588
+ (f' · covers {ink * w * h / (W * H) * 100:.1f}% of the canvas' if ink is not None else ''))
589
+ if not on:
590
+ continue
591
+ if hiding:
592
+ if ink:
593
+ warns.append(f'"{n}" cannot be seen: "{hiding}" is solid and sits on top of it.')
594
+ continue
595
+ if 0 < op <= 1:
596
+ warns.append(f'"{n}" opacity is {op:g}, and the scale is 0-100, so it is almost invisible. Did you mean {op * 100:g}?')
597
+ if ink == 0:
598
+ warns.append(f'"{n}" is empty: nothing is on it.')
599
+ if x >= W or y >= H or x + w <= 0 or y + h <= 0:
600
+ warns.append(f'"{n}" is completely off the canvas.')
601
+ if ink is not None and ink > 0.995 and op >= 99.9 and mode == 'normal' and x <= 0 and y <= 0 and x + w >= W and y + h >= H:
602
+ hiding = n
603
+ if not any(l.get_visible() for l in layers):
604
+ warns.append('Every layer is hidden, so this image exports as nothing.')
605
+ return lines, warns
606
+
607
+ def ava_text(image, text, font='Sans-serif Bold', size=96, colour='#ffffff', x=0, y=0, name=None, spacing=0.0):
608
+ """A real, editable text layer: the person can retype it in GIMP. size is
609
+ in pixels; spacing adds letter spacing. Check names with ava_fonts('rajdhani')."""
610
+ f = Gimp.Font.get_by_name(font)
611
+ if f is None:
612
+ near = ava_fonts(font.split()[0])[:12]
613
+ raise ValueError(f'No font called "{font}". Close matches: {near}. If this is the font they agreed, ask them whether you may install it, then use design_install_font.')
614
+ lay = Gimp.TextLayer.new(image, text, f, float(size), Gimp.Unit.pixel())
615
+ image.insert_layer(lay, None, 0)
616
+ lay.set_color(Gegl.Color.new(colour))
617
+ if spacing:
618
+ lay.set_letter_spacing(float(spacing))
619
+ lay.set_offsets(int(x), int(y))
620
+ lay.set_name(name or text[:40])
621
+ return lay
622
+
623
+ shutil.rmtree(_LOOK_DIR, ignore_errors=True)
624
+ sys.addaudithook(_hook)
625
+
626
+ # ── Ava's script ─────────────────────────────────────────────────────────────
627
+ script_path = os.path.join(ASSET_DIR, 'script.py')
628
+ ns = {'__name__': '__main__', '__file__': script_path, 'ASSET_DIR': ASSET_DIR,
629
+ 'Gimp': Gimp, 'Gegl': Gegl, 'Gio': Gio, 'os': os, 'KIT': KIT,
630
+ 'ava_copy_layer': ava_copy_layer, 'ava_remove': ava_remove, 'ava_move': ava_move, 'ava_merged': ava_merged,
631
+ 'ava_glow': ava_glow, 'ava_pixel': ava_pixel, 'ava_images': ava_images, 'ava_show': ava_show, 'ava_proof': ava_proof, 'ava_final': ava_final,
632
+ 'ava_image': ava_image, 'ava_layer': ava_layer, 'ava_place': ava_place,
633
+ 'ava_filter': ava_filter, 'ava_export': ava_export, 'ava_fill': ava_fill, 'ava_cut': ava_cut,
634
+ 'ava_gradient': ava_gradient, 'ava_text': ava_text, 'ava_fonts': ava_fonts}
635
+ try:
636
+ with open(script_path, encoding='utf-8') as f:
637
+ code = compile(f.read(), 'script.py', 'exec')
638
+ exec(code, ns)
639
+ except BaseException as e: # the saved work must stay as it was
640
+ result['error'] = ''.join(traceback.format_exception(type(e), e, e.__traceback__)[-12:])
641
+ emit()
642
+ raise SystemExit(0)
643
+
644
+ # ── Save, export, preview ────────────────────────────────────────────────────
645
+ try:
646
+ if not _open:
647
+ raise RuntimeError('The script made no image. Start with: img = ava_image("name", 512, 512)')
648
+ vdir = os.path.join(ASSET_DIR, 'versions')
649
+ stamp = time.strftime('%Y%m%d-%H%M%S')
650
+ saved_any = False
651
+ for name, img in _open.items():
652
+ if not img.get_layers():
653
+ # Saving one crashes GIMP's PNG writer, and an empty file on the
654
+ # stage is what split the title logo in two.
655
+ result['warnings'].append(f'"{name}" has no layers, so it was not saved. Saved images here: {ava_images()}.')
656
+ continue
657
+ saved_any = True
658
+ xcf = os.path.join(ASSET_DIR, name + '.xcf')
659
+ if os.path.exists(xcf): # keep the last 5 versions of each image
660
+ os.makedirs(vdir, exist_ok=True)
661
+ shutil.copy2(xcf, os.path.join(vdir, f'{name}.{stamp}.xcf'))
662
+ old = sorted(f for f in os.listdir(vdir) if f.startswith(name + '.'))
663
+ for f in old[:-5]:
664
+ os.remove(os.path.join(vdir, f))
665
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, img, _file(xcf), None)
666
+ copy = img.duplicate()
667
+ copy.merge_visible_layers(Gimp.MergeType.CLIP_TO_IMAGE)
668
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, copy, _file(os.path.join(ASSET_DIR, name + '.png')), None)
669
+ copy.delete()
670
+ result['images'].append({'name': name, 'width': img.get_width(), 'height': img.get_height(),
671
+ 'layers': len(img.get_layers())})
672
+ lines, warns = _report(name, img)
673
+ result['report'] += lines
674
+ result['warnings'] += warns
675
+ result['fonts'][name] = _fonts_in(img)
676
+ if not saved_any:
677
+ raise RuntimeError(f'Nothing to save: no image here has any layers. Saved images in this work: {ava_images()}. Open one by name, or add a layer.')
678
+ # Finals are written last, so a failed run can't add one.
679
+ finals_path = os.path.join(ASSET_DIR, 'finals.json')
680
+ try:
681
+ finals = json.load(open(finals_path, encoding='utf-8'))
682
+ except Exception:
683
+ finals = []
684
+ finals += [f for f in _new_finals if f not in finals]
685
+ if _new_finals:
686
+ json.dump(finals, open(finals_path, 'w', encoding='utf-8'), indent=2)
687
+ result['newFinals'] = _new_finals
688
+ # Preview: the finished files once there are any. Until then, the piece being
689
+ # worked on: what this run touched, leaving out her tests, so the person can
690
+ # always tell what the focus is. Every image at once told them nothing.
691
+ shown = [os.path.join(ASSET_DIR, f) for f in finals if os.path.exists(os.path.join(ASSET_DIR, f))]
692
+ if not shown:
693
+ saved_names = ava_images()
694
+ pieces = [n for n in saved_names if not _is_test(n)]
695
+ focus = [n for n in pieces if n in _open] or pieces or saved_names
696
+ try:
697
+ chosen = json.load(open(os.path.join(ASSET_DIR, 'main.json'), encoding='utf-8'))
698
+ if chosen in saved_names:
699
+ focus = [chosen]
700
+ except Exception:
701
+ pass
702
+ shown = [os.path.join(ASSET_DIR, n + '.png') for n in focus if os.path.exists(os.path.join(ASSET_DIR, n + '.png'))]
703
+ names = shown
704
+ cols = (min(len(names), 3) if len(names) <= 6 else 6) or 1
705
+ rows = (len(names) + cols - 1) // cols
706
+ cell = 768 if len(names) == 1 else 512 if len(names) <= 6 else 256
707
+ sheet = Gimp.Image.new(cols * cell, rows * cell, Gimp.ImageBaseType.RGB)
708
+ bg = Gimp.Layer.new(sheet, 'bg', cols * cell, rows * cell, Gimp.ImageType.RGBA_IMAGE, 100, Gimp.LayerMode.NORMAL)
709
+ sheet.insert_layer(bg, None, 0)
710
+ # Left empty on purpose: transparency stays real, so the room can show it.
711
+ for i, n in enumerate(names):
712
+ lay = Gimp.file_load_layer(Gimp.RunMode.NONINTERACTIVE, sheet, _file(n))
713
+ sheet.insert_layer(lay, None, 0)
714
+ w, h = lay.get_width(), lay.get_height()
715
+ k = min((cell - 16) / w, (cell - 16) / h)
716
+ nw, nh = max(1, int(w * k)), max(1, int(h * k))
717
+ lay.scale(nw, nh, False)
718
+ lay.set_offsets((i % cols) * cell + (cell - nw) // 2, (i // cols) * cell + (cell - nh) // 2)
719
+ sheet.merge_visible_layers(Gimp.MergeType.CLIP_TO_IMAGE)
720
+ Gimp.file_save(Gimp.RunMode.NONINTERACTIVE, sheet, _file(os.path.join(ASSET_DIR, 'preview.png')), None)
721
+ sheet.delete()
722
+ # What comes back to her: what she asked to see, else what this run touched.
723
+ try:
724
+ if not _looks:
725
+ for name, img in list(_open.items())[:MAX_LOOKS]:
726
+ if img.get_layers() and any(l.get_visible() for l in img.get_layers()):
727
+ ava_show(img, label=name)
728
+ result['looks'] = _looks
729
+ except Exception as e:
730
+ result['warnings'].append(f'Could not prepare the look: {e}')
731
+ result['files'] = sorted(f for f in os.listdir(ASSET_DIR) if f.endswith(('.xcf', '.png')))
732
+ ex = os.path.join(ASSET_DIR, 'exports')
733
+ if os.path.isdir(ex):
734
+ result['files'] += ['exports/' + f for f in sorted(os.listdir(ex))]
735
+ result['placed'] = _placed
736
+ result['kit_logos'] = list(KIT_LOGOS_USED)
737
+ result['ok'] = True
738
+ result['seconds'] = round(time.time() - STARTED, 1)
739
+ except BaseException as e:
740
+ result['error'] = 'The script ran, but saving failed:\n' + \
741
+ ''.join(traceback.format_exception(type(e), e, e.__traceback__)[-8:])
742
+ shutil.rmtree(_TMP, ignore_errors=True)
743
+ emit()
744
+ for img in list(_open.values()):
745
+ try:
746
+ img.delete()
747
+ except Exception:
748
+ pass
749
+ `;
750
+ //# sourceMappingURL=runner-py.js.map