File size: 9,614 Bytes
415a17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad58c8
415a17d
9ad58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
415a17d
 
 
 
 
9ad58c8
415a17d
1eac263
415a17d
 
1eac263
334ad08
7a8c809
415a17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a8c809
 
415a17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a8c809
9ad58c8
7a8c809
 
415a17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a8c809
415a17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<script lang="ts">
  import type { MonsterGeneratorProps, MonsterWorkflowState, CaptionType, CaptionLength } from '$lib/types';
  import UploadStep from './UploadStep.svelte';
  import WorkflowProgress from './WorkflowProgress.svelte';
  import MonsterResult from './MonsterResult.svelte';
  
  interface Props extends MonsterGeneratorProps {}
  
  let { joyCaptionClient, rwkvClient, fluxClient }: Props = $props();
  
  let state: MonsterWorkflowState = $state({
    currentStep: 'upload',
    userImage: null,
    imageCaption: null,
    monsterConcept: null,
    imagePrompt: null,
    monsterImage: null,
    error: null,
    isProcessing: false
  });
  
  // Prompt templates
  const MONSTER_CONCEPT_PROMPT = (caption: string) => `User: Based on this image caption: "${caption}"

Come up with a monster idea (in the vein of Pokémon) that incorporates properties of what the pictured object is.
Assess how unique the pictured object is. If the image is not very unique then it should result in weak & common monster.
Meanwhile if the image is very unique the monster should be unique and powerful.

Create a creature that reflects the essence, materials, function, and characteristics of the object. Consider:
- What the object is made of (metal, wood, fabric, etc.)
- How it functions or is used
- Its physical properties (hard, soft, hot, cold, etc.)
- Its cultural or symbolic meaning
- Its shape, texture, and visual characteristics

The monster should have unique strengths and weaknesses based on these properties.

Include:
- Physical appearance and distinguishing features
- Special abilities or powers  
- Personality traits
- Habitat or origin

Assistant: **Monster Name:**`;

  const IMAGE_GENERATION_PROMPT = (concept: string) => `User: Convert this monster concept into a clear and succinct description of its appearance:
"${concept}"

Include all of its visual details, format the description as a single long sentence.

Assistant:`;
  
  async function handleImageSelected(file: File) {
    if (!joyCaptionClient || !rwkvClient || !fluxClient) {
      state.error = "Services not connected. Please wait...";
      return;
    }
    
    state.userImage = file;
    state.error = null;
    startWorkflow();
  }
  
  async function startWorkflow() {
    state.isProcessing = true;
    
    try {
      // Step 1: Caption the image
      await captionImage();
      await new Promise(resolve => setTimeout(resolve, 100)); // Small delay for state update
      
      // Step 2: Generate monster concept
      await generateMonsterConcept();
      await new Promise(resolve => setTimeout(resolve, 100)); // Small delay for state update
      
      // Step 3: Generate image prompt
      await generateImagePrompt();
      await new Promise(resolve => setTimeout(resolve, 100)); // Small delay for state update
      
      // Step 4: Generate monster image
      await generateMonsterImage();
      
      state.currentStep = 'complete';
    } catch (err) {
      console.error('Workflow error:', err);
      state.error = err instanceof Error ? err.message : 'An unknown error occurred';
    } finally {
      state.isProcessing = false;
    }
  }
  
  async function captionImage() {
    state.currentStep = 'captioning';
    
    if (!joyCaptionClient || !state.userImage) {
      throw new Error('Caption service not available or no image provided');
    }
    
    const output = await joyCaptionClient.predict("/stream_chat", [
      state.userImage,
      "Descriptive" as CaptionType,
      "very long" as CaptionLength,
      [], // extra_options
      "", // name_input
      ""  // custom_prompt
    ]);
    
    const [prompt, caption] = output.data;
    state.imageCaption = caption;
    console.log('Caption generated:', caption);
  }
  
  async function generateMonsterConcept() {
    state.currentStep = 'conceptualizing';
    
    if (!rwkvClient || !state.imageCaption) {
      throw new Error('Text generation service not available or no caption');
    }
    
    const conceptPrompt = MONSTER_CONCEPT_PROMPT(state.imageCaption);
    
    console.log('Generating monster concept with prompt:', conceptPrompt);
    
    const output = await rwkvClient.predict(0, [
      conceptPrompt,
      300,   // maxTokens
      0.7,   // temperature
      0.8,   // topP
      0.1,   // presencePenalty
      0.1    // countPenalty
    ]);
    
    console.log('RWKV output:', output);
    state.monsterConcept = output.data[0];
    console.log('Monster concept generated:', state.monsterConcept);
    
    if (!state.monsterConcept || state.monsterConcept.trim() === '') {
      throw new Error('Failed to generate monster concept - received empty response');
    }
  }
  
  async function generateImagePrompt() {
    state.currentStep = 'promptCrafting';
    
    if (!rwkvClient || !state.monsterConcept) {
      throw new Error('Text generation service not available or no concept');
    }
    
    const promptGenerationPrompt = IMAGE_GENERATION_PROMPT(state.monsterConcept);
    
    console.log('Generating image prompt from concept');
    
    const output = await rwkvClient.predict(0, [
      promptGenerationPrompt,
      300,   // maxTokens
      0.7,   // temperature
      0.8,   // topP
      0.1,   // presencePenalty
      0.1    // countPenalty
    ]);
    
    console.log('Image prompt output:', output);
    state.imagePrompt = output.data[0];
    console.log('Image prompt generated:', state.imagePrompt);
    
    if (!state.imagePrompt || state.imagePrompt.trim() === '') {
      throw new Error('Failed to generate image prompt - received empty response');
    }
  }
  
  async function generateMonsterImage() {
    state.currentStep = 'generating';
    
    if (!fluxClient || !state.imagePrompt) {
      throw new Error('Image generation service not available or no prompt');
    }
    
    const output = await fluxClient.predict("/infer", [
      `${state.imagePrompt}\nNow generate an Anime-style image of the monster in an idle pose. The monster should not be attacking or in motion. The full monster must be visible within the frame.`,
      0,      // seed
      true,   // randomizeSeed
      1024,   // width
      1024,   // height
      4       // steps
    ]);
    
    const [image, usedSeed] = output.data;
    let url: string | undefined;
    
    if (typeof image === "string") url = image;
    else if (image && image.url) url = image.url;
    else if (image && image.path) url = image.path;
    
    if (url) {
      state.monsterImage = {
        imageUrl: url,
        seed: usedSeed,
        prompt: state.imagePrompt
      };
    } else {
      throw new Error('Failed to generate monster image');
    }
  }
  
  function reset() {
    state = {
      currentStep: 'upload',
      userImage: null,
      imageCaption: null,
      monsterConcept: null,
      imagePrompt: null,
      monsterImage: null,
      error: null,
      isProcessing: false
    };
  }
</script>

<div class="monster-generator">
  
  {#if state.currentStep !== 'upload'}
    <WorkflowProgress currentStep={state.currentStep} error={state.error} />
  {/if}
  
  {#if state.currentStep === 'upload'}
    <UploadStep 
      onImageSelected={handleImageSelected}
      isProcessing={state.isProcessing}
    />
  {:else if state.currentStep === 'complete'}
    <MonsterResult state={state} onReset={reset} />
  {:else}
    <div class="processing-container">
      <div class="spinner"></div>
      <p class="processing-text">
        {#if state.currentStep === 'captioning'}
          Analyzing your image...
        {:else if state.currentStep === 'conceptualizing'}
          Creating monster concept...
        {:else if state.currentStep === 'promptCrafting'}
          Crafting generation prompt...
        {:else if state.currentStep === 'generating'}
          Generating your monster...
        {/if}
      </p>
      
      {#if state.imageCaption && state.currentStep !== 'captioning'}
        <div class="intermediate-result">
          <h4>Image Description:</h4>
          <p>{state.imageCaption}</p>
        </div>
      {/if}
      
      {#if state.monsterConcept && state.currentStep !== 'captioning' && state.currentStep !== 'conceptualizing'}
        <div class="intermediate-result">
          <h4>Monster Concept:</h4>
          <p>{state.monsterConcept}</p>
        </div>
      {/if}
      
      {#if state.imagePrompt && state.currentStep === 'generating'}
        <div class="intermediate-result">
          <h4>Generation Prompt:</h4>
          <p>{state.imagePrompt}</p>
        </div>
      {/if}
    </div>
  {/if}
</div>

<style>
  .monster-generator {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
  }
  
  
  .processing-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 3rem 1rem;
  }
  
  .spinner {
    width: 60px;
    height: 60px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 2rem;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  .processing-text {
    font-size: 1.2rem;
    color: #333;
    margin-bottom: 2rem;
  }
  
  .intermediate-result {
    width: 100%;
    max-width: 700px;
    background: #f8f9fa;
    padding: 1.5rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
    text-align: left;
  }
  
  .intermediate-result h4 {
    margin: 0 0 0.5rem 0;
    color: #495057;
  }
  
  .intermediate-result p {
    margin: 0;
    line-height: 1.6;
    color: #333;
  }
</style>