|
<script lang="ts"> |
|
import type { PicletGeneratorProps, PicletWorkflowState, CaptionType, CaptionLength, PicletStats } from '$lib/types'; |
|
import { Nature } from '$lib/types'; |
|
import type { PicletInstance } from '$lib/db/schema'; |
|
import UploadStep from './UploadStep.svelte'; |
|
import WorkflowProgress from './WorkflowProgress.svelte'; |
|
import PicletResult from './PicletResult.svelte'; |
|
import { removeBackground } from '$lib/utils/professionalImageProcessing'; |
|
import { extractPicletMetadata } from '$lib/services/picletMetadata'; |
|
import { savePicletInstance, generatedDataToPicletInstance } from '$lib/db/piclets'; |
|
import { PicletType, TYPE_DATA } from '$lib/types/picletTypes'; |
|
import { EncounterService } from '$lib/db/encounterService'; |
|
|
|
|
|
interface Props extends PicletGeneratorProps { |
|
|
|
isTrainerMode?: boolean; |
|
onTrainerImageCompleted?: (imagePath: string, picletId: number) => void; |
|
onTrainerImageFailed?: (imagePath: string, error: string) => void; |
|
} |
|
|
|
let { |
|
joyCaptionClient, |
|
fluxClient, |
|
commandClient, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
isTrainerMode = false, |
|
onTrainerImageCompleted, |
|
onTrainerImageFailed |
|
}: Props = $props(); |
|
|
|
|
|
type TextGenerationClient = 'hunyuan' | 'command' | 'zephyr' | 'qwen' | 'dots'; |
|
let currentTextClient: TextGenerationClient = $state('command'); |
|
|
|
|
|
const getActiveTextClient = () => { |
|
if (!commandClient) { |
|
console.warn('Command client not yet initialized'); |
|
return null; |
|
} |
|
return commandClient; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}; |
|
|
|
|
|
const generateText = async (prompt: string): Promise<string> => { |
|
const client = getActiveTextClient(); |
|
if (!client) { |
|
throw new Error(`Command client is not available`); |
|
} |
|
|
|
console.log(`Generating text with Command client...`); |
|
|
|
|
|
|
|
const message = { |
|
text: prompt, |
|
files: [] |
|
}; |
|
|
|
|
|
const result = await client.predict("/chat", { |
|
message: message, |
|
max_new_tokens: 2000 |
|
}); |
|
|
|
return result.data || ''; |
|
}; |
|
|
|
let workflowState: PicletWorkflowState = $state({ |
|
currentStep: 'upload', |
|
userImage: null, |
|
imageCaption: null, |
|
picletConcept: null, |
|
picletStats: null, |
|
imagePrompt: null, |
|
picletImage: null, |
|
error: null, |
|
isProcessing: false |
|
}); |
|
|
|
|
|
let imageQueue: File[] = $state([]); |
|
let currentImageIndex: number = $state(0); |
|
|
|
|
|
let trainerImagePaths: string[] = $state([]); |
|
|
|
const IMAGE_GENERATION_PROMPT = (concept: string) => `Extract ONLY the visual appearance from this monster concept and describe it in one concise sentence: |
|
"${concept}" |
|
|
|
Focus on: colors, body shape, eyes, limbs, mouth, and key visual features. Omit backstory, abilities, and non-visual details.`; |
|
|
|
|
|
async function importPiclet(picletData: PicletInstance) { |
|
workflowState.isProcessing = true; |
|
workflowState.currentStep = 'complete'; |
|
|
|
try { |
|
|
|
const savedId = await savePicletInstance(picletData); |
|
|
|
|
|
workflowState.picletImage = { |
|
imageUrl: picletData.imageUrl, |
|
imageData: picletData.imageData, |
|
seed: 0, |
|
prompt: 'Imported piclet' |
|
}; |
|
|
|
|
|
workflowState.isProcessing = false; |
|
alert(`Successfully imported ${picletData.nickname || picletData.typeId}!`); |
|
|
|
|
|
setTimeout(() => reset(), 2000); |
|
} catch (error) { |
|
workflowState.error = `Failed to import piclet: ${error}`; |
|
workflowState.isProcessing = false; |
|
} |
|
} |
|
|
|
async function handleImageSelected(file: File) { |
|
if (!joyCaptionClient || !fluxClient) { |
|
workflowState.error = "Services not connected. Please wait..."; |
|
return; |
|
} |
|
|
|
|
|
imageQueue = []; |
|
currentImageIndex = 0; |
|
|
|
workflowState.userImage = file; |
|
workflowState.error = null; |
|
|
|
|
|
const picletData = await extractPicletMetadata(file); |
|
if (picletData) { |
|
|
|
await importPiclet(picletData); |
|
} else { |
|
|
|
startWorkflow(); |
|
} |
|
} |
|
|
|
async function handleImagesSelected(files: File[]) { |
|
if (!joyCaptionClient || !fluxClient) { |
|
workflowState.error = "Services not connected. Please wait..."; |
|
return; |
|
} |
|
|
|
|
|
imageQueue = files; |
|
currentImageIndex = 0; |
|
|
|
await processCurrentImage(); |
|
} |
|
|
|
async function processCurrentImage() { |
|
if (currentImageIndex >= imageQueue.length) { |
|
|
|
console.log('All images processed!'); |
|
return; |
|
} |
|
|
|
const currentFile = imageQueue[currentImageIndex]; |
|
workflowState.userImage = currentFile; |
|
workflowState.error = null; |
|
|
|
|
|
const picletData = await extractPicletMetadata(currentFile); |
|
if (picletData) { |
|
|
|
await importPiclet(picletData); |
|
|
|
await advanceToNextImage(); |
|
} else { |
|
|
|
startWorkflow(); |
|
} |
|
} |
|
|
|
async function advanceToNextImage() { |
|
currentImageIndex++; |
|
|
|
if (currentImageIndex < imageQueue.length) { |
|
|
|
setTimeout(() => processCurrentImage(), 1000); |
|
} else if (isTrainerMode) { |
|
|
|
console.log('🔧 DEBUG: Trainer mode - waiting for next image to be queued'); |
|
|
|
currentImageIndex = 0; |
|
imageQueue = []; |
|
|
|
} else { |
|
|
|
imageQueue = []; |
|
currentImageIndex = 0; |
|
reset(); |
|
} |
|
} |
|
|
|
async function startWorkflow() { |
|
workflowState.isProcessing = true; |
|
|
|
try { |
|
|
|
await captionImage(); |
|
await new Promise(resolve => setTimeout(resolve, 100)); |
|
|
|
|
|
await generateConcept(); |
|
await new Promise(resolve => setTimeout(resolve, 100)); |
|
|
|
|
|
await generateStats(); |
|
await new Promise(resolve => setTimeout(resolve, 100)); |
|
|
|
|
|
await generateImagePrompt(); |
|
await new Promise(resolve => setTimeout(resolve, 100)); |
|
|
|
|
|
await generateMonsterImage(); |
|
|
|
|
|
await autoSavePiclet(); |
|
|
|
workflowState.currentStep = 'complete'; |
|
|
|
|
|
if (imageQueue.length > 1 || isTrainerMode) { |
|
setTimeout(() => advanceToNextImage(), 2000); |
|
} |
|
} catch (err) { |
|
console.error('Workflow error:', err); |
|
|
|
|
|
if (err && typeof err === 'object' && 'message' in err) { |
|
const errorMessage = String(err.message); |
|
if (errorMessage.includes('exceeded your GPU quota') || errorMessage.includes('GPU quota')) { |
|
workflowState.error = 'GPU quota exceeded! You need to sign in with Hugging Face for free GPU time, or upgrade to Hugging Face Pro for more quota.'; |
|
} else { |
|
workflowState.error = errorMessage; |
|
} |
|
} else if (err instanceof Error) { |
|
workflowState.error = err.message; |
|
} else { |
|
workflowState.error = 'An unknown error occurred'; |
|
} |
|
} finally { |
|
workflowState.isProcessing = false; |
|
} |
|
} |
|
|
|
function handleAPIError(error: any): never { |
|
console.error('API Error:', error); |
|
|
|
|
|
if (error && typeof error === 'object' && 'message' in error) { |
|
const errorMessage = String(error.message); |
|
if (errorMessage.includes('exceeded your GPU quota') || errorMessage.includes('GPU quota')) { |
|
throw new Error('GPU quota exceeded! You need to sign in with Hugging Face for free GPU time, or upgrade to Hugging Face Pro for more quota.'); |
|
} |
|
throw new Error(errorMessage); |
|
} |
|
|
|
|
|
if (error && typeof error === 'object' && 'type' in error && error.type === 'status') { |
|
const statusError = error as any; |
|
if (statusError.message && statusError.message.includes('GPU quota')) { |
|
throw new Error('GPU quota exceeded! You need to sign in with Hugging Face for free GPU time, or upgrade to Hugging Face Pro for more quota.'); |
|
} |
|
throw new Error(statusError.message || 'API request failed'); |
|
} |
|
|
|
throw error; |
|
} |
|
|
|
async function captionImage() { |
|
workflowState.currentStep = 'captioning'; |
|
|
|
if (!joyCaptionClient || !workflowState.userImage) { |
|
throw new Error('Caption service not available or no image provided'); |
|
} |
|
|
|
try { |
|
const output = await joyCaptionClient.predict("/stream_chat", [ |
|
workflowState.userImage, |
|
"Descriptive", |
|
"long", |
|
[], |
|
"", |
|
"" |
|
]); |
|
|
|
const [, caption] = output.data; |
|
|
|
workflowState.imageCaption = caption; |
|
console.log('Detailed object description generated:', caption); |
|
} catch (error) { |
|
handleAPIError(error); |
|
} |
|
} |
|
|
|
async function generateConcept() { |
|
workflowState.currentStep = 'conceptualizing'; |
|
|
|
const activeClient = getActiveTextClient(); |
|
if (!activeClient || !workflowState.imageCaption) { |
|
throw new Error(`${currentTextClient} service not available or no image caption provided`); |
|
} |
|
|
|
const conceptPrompt = `Based on this detailed object description, create a Pokémon-style monster that transforms the object into an imaginative creature. The monster should clearly be inspired by the object's appearance but reimagined as a living monster. |
|
|
|
Object description: "${workflowState.imageCaption}" |
|
|
|
Guidelines: |
|
- Take the object's key visual elements (colors, shapes, materials) incorporating all of them into a single creature design |
|
- Add eyes (can be glowing, mechanical, multiple, etc.) positioned where they make sense |
|
- Include limbs (legs, arms, wings, tentacles) that grow from or replace parts of the object |
|
- Add a mouth, beak, or feeding apparatus if appropriate |
|
- Add creature elements like tail, fins, claws, horns, etc where fitting |
|
|
|
Format your response exactly as follows: |
|
\`\`\`md |
|
# Object Rarity |
|
{Assess how rare the object is based on real-world availability and value. Rare objects give strong monsters while common objects give weak ones. Use: common, uncommon, rare, or legendary} |
|
|
|
# Monster Name |
|
{Creative name that hints at the original object, 11 letters max} |
|
|
|
# Monster Description |
|
{Detailed physical description showing how the object becomes a creature. Ensure the creature uses all the unique attributes of the object. Include colors, shapes, materials, eyes, limbs, mouth, and distinctive features. This section will be used for stats generation and lore.} |
|
|
|
# Monster Image Prompt |
|
{Extensive visual description of the Pokémon style monster for image generation. Focus on key visual elements: body shape, colors, distinctive features, pose. Keep this optimized for AI image generation.} |
|
\`\`\``; |
|
|
|
try { |
|
const responseText = await generateText(conceptPrompt); |
|
|
|
if (!responseText || responseText.trim() === '') { |
|
throw new Error('Failed to generate monster concept'); |
|
} |
|
|
|
|
|
let cleanedResponse = responseText.trim(); |
|
|
|
|
|
if (cleanedResponse.includes('```')) { |
|
|
|
const codeBlockRegex = /```(?:md|markdown)?\s*\n([\s\S]*?)```/; |
|
const match = cleanedResponse.match(codeBlockRegex); |
|
|
|
if (match && match[1]) { |
|
cleanedResponse = match[1].trim(); |
|
console.log('Extracted content from markdown code block'); |
|
} else { |
|
|
|
const simpleMatch = cleanedResponse.match(/```([\s\S]*?)```/); |
|
if (simpleMatch && simpleMatch[1]) { |
|
cleanedResponse = simpleMatch[1].trim(); |
|
console.log('Extracted content from generic code block'); |
|
} |
|
} |
|
} |
|
|
|
|
|
if (!cleanedResponse.includes('# Object Rarity') || !cleanedResponse.includes('# Monster Name') || !cleanedResponse.includes('# Monster Image Prompt')) { |
|
console.warn('Response does not contain expected markdown structure (missing Object Rarity, Monster Name, or Monster Image Prompt)'); |
|
} |
|
|
|
workflowState.picletConcept = cleanedResponse; |
|
console.log('Monster concept generated:', cleanedResponse); |
|
} catch (error) { |
|
handleAPIError(error); |
|
} |
|
} |
|
|
|
async function generateImagePrompt() { |
|
workflowState.currentStep = 'promptCrafting'; |
|
|
|
const activeClient = getActiveTextClient(); |
|
if (!activeClient || !workflowState.picletConcept || !workflowState.imageCaption) { |
|
throw new Error(`HunyuanTurbos service not available or no concept/caption available for prompt generation`); |
|
} |
|
|
|
|
|
const imagePromptMatch = workflowState.picletConcept.match(/# Monster Image Prompt\s*\n([\s\S]*?)(?=^#|$)/m); |
|
|
|
if (imagePromptMatch && imagePromptMatch[1]) { |
|
workflowState.imagePrompt = imagePromptMatch[1].trim(); |
|
console.log('Extracted image prompt for generation:', workflowState.imagePrompt); |
|
return; |
|
} |
|
|
|
|
|
const imagePromptPrompt = `Based on this monster concept, extract ONLY the visual description for image generation: |
|
|
|
MONSTER CONCEPT: |
|
""" |
|
${workflowState.picletConcept} |
|
""" |
|
|
|
Create a concise visual description (1-3 sentences, max 100 words). Focus only on colors, shapes, materials, eyes, limbs, mouth, and distinctive features. Omit all non-visual information like abilities and backstory.`; |
|
|
|
try { |
|
const responseText = await generateText(imagePromptPrompt); |
|
|
|
if (!responseText || responseText.trim() === '') { |
|
throw new Error('Failed to generate image prompt'); |
|
} |
|
|
|
workflowState.imagePrompt = responseText.trim(); |
|
console.log('Image prompt generated:', workflowState.imagePrompt); |
|
} catch (error) { |
|
handleAPIError(error); |
|
} |
|
} |
|
|
|
async function generateMonsterImage() { |
|
workflowState.currentStep = 'generating'; |
|
|
|
if (!fluxClient || !workflowState.imagePrompt || !workflowState.picletStats) { |
|
throw new Error('Image generation service not available or no prompt/stats'); |
|
} |
|
|
|
|
|
|
|
|
|
const tier = workflowState.picletStats.tier || 'medium'; |
|
const tierDescriptions = { |
|
low: 'simple and iconic design', |
|
medium: 'detailed and well-crafted design', |
|
high: 'highly detailed and impressive design with special effects', |
|
legendary: 'highly detailed and majestic design with dramatic lighting and aura effects' |
|
}; |
|
|
|
try { |
|
const output = await fluxClient.predict("/infer", [ |
|
`${workflowState.imagePrompt}\nNow generate an Pokémon Anime image of the monster in an idle pose with a plain dark-grey background. This is a ${tier} tier monster with a ${tierDescriptions[tier as keyof typeof tierDescriptions]}. The monster should not be attacking or in motion. The full monster must be visible within the frame.`, |
|
0, |
|
true, |
|
1024, |
|
1024, |
|
4 |
|
]); |
|
|
|
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) { |
|
|
|
console.log('Processing image for background removal...'); |
|
try { |
|
const transparentBase64 = await removeBackground(url); |
|
workflowState.picletImage = { |
|
imageUrl: url, |
|
imageData: transparentBase64, |
|
seed: usedSeed, |
|
prompt: workflowState.imagePrompt |
|
}; |
|
console.log('Background removal completed successfully'); |
|
} catch (processError) { |
|
console.error('Failed to process image for background removal:', processError); |
|
|
|
workflowState.picletImage = { |
|
imageUrl: url, |
|
seed: usedSeed, |
|
prompt: workflowState.imagePrompt |
|
}; |
|
} |
|
} else { |
|
throw new Error('Failed to generate monster image'); |
|
} |
|
} catch (error) { |
|
handleAPIError(error); |
|
} |
|
} |
|
|
|
async function generateStats() { |
|
workflowState.currentStep = 'statsGenerating'; |
|
|
|
const activeClient = getActiveTextClient(); |
|
if (!activeClient || !workflowState.picletConcept || !workflowState.imageCaption) { |
|
throw new Error(`${currentTextClient} service not available or no concept/caption available for stats generation`); |
|
} |
|
|
|
|
|
let tier: 'low' | 'medium' | 'high' | 'legendary' = 'medium'; |
|
|
|
|
|
const monsterNameMatch = workflowState.picletConcept.match(/# Monster Name\s*\n([\s\S]*?)(?=^#|$)/m); |
|
let monsterName = monsterNameMatch ? monsterNameMatch[1].trim() : 'Unknown Monster'; |
|
|
|
|
|
if (monsterName.includes(',')) { |
|
monsterName = monsterName.split(',')[0].trim(); |
|
} |
|
|
|
|
|
if (monsterName.length > 12) { |
|
monsterName = monsterName.substring(0, 12); |
|
} |
|
|
|
const rarityMatch = workflowState.picletConcept.match(/# Object Rarity\s*\n([\s\S]*?)(?=^#)/m); |
|
const objectRarity = rarityMatch ? rarityMatch[1].trim().toLowerCase() : 'common'; |
|
|
|
|
|
const statsPrompt = `Based on this detailed object description and monster concept, create a complete battle-ready monster for the Pictuary Battle System: |
|
|
|
ORIGINAL OBJECT DESCRIPTION: |
|
"${workflowState.imageCaption}" |
|
|
|
MONSTER CONCEPT: |
|
"${workflowState.picletConcept}" |
|
|
|
The object rarity has been assessed as: ${objectRarity} |
|
|
|
## BATTLE SYSTEM OVERVIEW |
|
This monster will be used in a turn-based battle system with composable effects. You must create: |
|
1. **Base Stats**: Core combat statistics |
|
2. **Special Ability**: Passive trait with triggers and effects |
|
3. **Movepool**: 4 battle moves with complex effect combinations |
|
|
|
## TYPE SYSTEM |
|
Choose the primary type (and optional secondary type) based on the object: |
|
• **beast**: Vertebrate wildlife — mammals, birds, reptiles. Raw physicality, instincts |
|
• **bug**: Arthropods — butterflies, beetles, mantises. Agile swarms, precision strikes |
|
• **aquatic**: Life that swims, dives, sloshes — fish, octopus, sentient puddles. Tides, pressure |
|
• **flora**: Plants and fungi — blooming or decaying. Growth, spores, vines, seasonal shifts |
|
• **mineral**: Stones, crystals, metals — earth's depths. Durability, reflective armor, seismic shocks |
|
• **space**: Stars, moon, cosmic objects — not of this world. Celestial energy, gravitational effects |
|
• **machina**: Engineered devices — gadgets to machinery. Gears, circuits, drones, power surges |
|
• **structure**: Buildings, bridges, monuments — architectural titans. Fortification, terrain shaping |
|
• **culture**: Art, fashion, toys, symbols — creative expressions. Buffs, debuffs, illusion, stories |
|
• **cuisine**: Dishes, drinks, culinary art — flavors and aromas. Temperature, restorative effects |
|
|
|
## EFFECT SYSTEM |
|
All abilities and moves use these **atomic building blocks**: |
|
|
|
### **Effect Types:** |
|
1. **damage**: Deal damage (weak/normal/strong/extreme) with formulas (standard/recoil/drain/fixed/percentage) |
|
2. **modifyStats**: Change stats (increase/decrease/greatly_increase/greatly_decrease) for hp/attack/defense/speed/accuracy |
|
3. **applyStatus**: Apply status effects (burn/freeze/paralyze/poison/sleep/confuse) with chance percentage |
|
4. **heal**: Restore HP (small/medium/large/full) or by percentage/fixed amounts |
|
5. **manipulatePP**: Drain, restore, or disable PP from moves |
|
6. **fieldEffect**: Persistent battlefield modifications (reflect/lightScreen for defense, spikes for entry damage, mist for stat protection, healingField for regeneration, etc.) |
|
7. **counter**: Reflect damage |
|
8. **priority**: Modify move priority (-5 to +5) |
|
9. **removeStatus**: Cure specific status conditions |
|
10. **mechanicOverride**: Modify core game mechanics (immunity, type changes, etc.) |
|
|
|
### **Targets:** |
|
- **self**: The move user |
|
- **opponent**: The target opponent |
|
- **all**: All combatants |
|
- **allies**: Allied creatures (team battles) |
|
- **field**: Entire battlefield |
|
|
|
### **Conditions:** |
|
- **always**: Effect always applies |
|
- **onHit**: Only if move hits successfully |
|
- **afterUse**: After move execution regardless of hit/miss |
|
- **onCritical**: Only on critical hits |
|
- **ifLowHp**: If user's HP < 25% |
|
- **ifHighHp**: If user's HP > 75% |
|
|
|
### **Move Flags:** |
|
Moves can have flags affecting interactions: |
|
- **contact**: Makes physical contact (triggers contact abilities) |
|
- **explosive**: Explosive move (affected by explosion-related abilities) |
|
- **draining**: Drains HP from target |
|
- **priority**: Natural priority move (+1 to +5) |
|
- **sacrifice**: Involves self-sacrifice or major cost |
|
- **reckless**: High power with drawbacks |
|
|
|
## SPECIAL ABILITY TRIGGERS |
|
Special abilities activate on specific events: |
|
- **onSwitchIn**: When entering battle |
|
- **onDamageTaken**: When this monster takes damage |
|
- **onContactDamage**: When hit by a contact move |
|
- **endOfTurn**: At the end of each turn |
|
- **onLowHP**: When HP drops below 25% |
|
- **onStatusInflicted**: When a status is applied |
|
|
|
## BALANCING GUIDELINES |
|
**Stat Ranges by Rarity:** |
|
- **common**: 45-80 total stats, individual stats 10-25 |
|
- **uncommon**: 80-120 total stats, individual stats 15-35 |
|
- **rare**: 120-160 total stats, individual stats 25-45 |
|
- **legendary**: 160-200+ total stats, individual stats 35-50 |
|
|
|
**Design Philosophy:** |
|
- **Risk-Reward**: Powerful moves must have meaningful drawbacks |
|
- **Type Synergy**: Moves should match the monster's type and concept |
|
- **Strategic Depth**: Abilities should create interesting decision points |
|
- **No Strictly Better**: Every powerful effect has a cost or condition |
|
|
|
The output should be formatted as a JSON instance that conforms to the schema below. |
|
|
|
\`\`\`json |
|
{ |
|
"type": "object", |
|
"properties": { |
|
"name": {"type": "string", "description": "Creative name for the monster that hints at the original object"}, |
|
"description": {"type": "string", "description": "Flavor text describing the monster (2-3 sentences)"}, |
|
"tier": {"type": "string", "enum": ["low", "medium", "high", "legendary"], "description": "Power tier based on rarity: common=low, uncommon=medium, rare=high, legendary=legendary"}, |
|
"primaryType": {"type": "string", "enum": ["beast", "bug", "aquatic", "flora", "mineral", "space", "machina", "structure", "culture", "cuisine"], "description": "Primary type based on object characteristics"}, |
|
"secondaryType": {"type": ["string", "null"], "enum": ["beast", "bug", "aquatic", "flora", "mineral", "space", "machina", "structure", "culture", "cuisine", null], "description": "Optional secondary type for dual-type monsters"}, |
|
"baseStats": { |
|
"type": "object", |
|
"properties": { |
|
"hp": {"type": "integer", "minimum": 10, "maximum": 50, "description": "Hit points"}, |
|
"attack": {"type": "integer", "minimum": 10, "maximum": 50, "description": "Attack power"}, |
|
"defense": {"type": "integer", "minimum": 10, "maximum": 50, "description": "Defensive capability"}, |
|
"speed": {"type": "integer", "minimum": 10, "maximum": 50, "description": "Speed and agility"} |
|
}, |
|
"required": ["hp", "attack", "defense", "speed"], |
|
"additionalProperties": false |
|
}, |
|
"nature": { |
|
"type": "string", |
|
"enum": ["hardy", "docile", "serious", "bashful", "quirky", "lonely", "brave", "adamant", "naughty", "bold", "relaxed", "impish", "lax", "timid", "hasty", "jolly", "naive", "modest", "mild", "quiet", "gentle", "sassy", "careful", "calm", "reckless"], |
|
"description": "Personality trait affecting behavior and battle style" |
|
}, |
|
"specialAbility": { |
|
"type": "object", |
|
"properties": { |
|
"name": {"type": "string", "description": "Name of the special ability"}, |
|
"triggers": { |
|
"type": "array", |
|
"items": {"$ref": "#/definitions/Trigger"}, |
|
"minItems": 1, |
|
"maxItems": 1, |
|
"description": "Single trigger effect for the special ability" |
|
} |
|
}, |
|
"required": ["name"], |
|
"additionalProperties": false |
|
}, |
|
"movepool": { |
|
"type": "array", |
|
"items": {"$ref": "#/definitions/Move"}, |
|
"minItems": 4, |
|
"maxItems": 4, |
|
"description": "Exactly 4 battle moves" |
|
} |
|
}, |
|
"required": ["name", "description", "tier", "primaryType", "baseStats", "nature", "specialAbility", "movepool"], |
|
"additionalProperties": false, |
|
"definitions": { |
|
"Effect": { |
|
"type": "object", |
|
"properties": { |
|
"type": {"type": "string", "enum": ["damage", "modifyStats", "applyStatus", "heal", "manipulatePP", "fieldEffect", "counter", "priority", "removeStatus", "mechanicOverride"]}, |
|
"target": {"type": "string", "enum": ["self", "opponent", "allies", "all", "attacker", "field", "playerSide", "opponentSide"]}, |
|
"condition": {"type": "string", "enum": ["always", "onHit", "afterUse", "onCritical", "ifLowHp", "ifHighHp", "thisTurn", "nextTurn", "restOfBattle"]} |
|
}, |
|
"required": ["type"], |
|
"allOf": [ |
|
{"if": {"properties": {"type": {"const": "damage"}}}, "then": {"properties": {"amount": {"enum": ["weak", "normal", "strong", "extreme"]}, "formula": {"enum": ["standard", "recoil", "drain", "fixed", "percentage"]}, "value": {"type": "number"}}}}, |
|
{"if": {"properties": {"type": {"const": "modifyStats"}}}, "then": {"properties": {"stats": {"type": "object", "properties": {"hp": {"enum": ["increase", "decrease", "greatly_increase", "greatly_decrease"]}, "attack": {"enum": ["increase", "decrease", "greatly_increase", "greatly_decrease"]}, "defense": {"enum": ["increase", "decrease", "greatly_increase", "greatly_decrease"]}, "speed": {"enum": ["increase", "decrease", "greatly_increase", "greatly_decrease"]}, "accuracy": {"enum": ["increase", "decrease", "greatly_increase", "greatly_decrease"]}}}}}}, |
|
{"if": {"properties": {"type": {"const": "applyStatus"}}}, "then": {"properties": {"status": {"enum": ["burn", "freeze", "paralyze", "poison", "sleep", "confuse"]}, "chance": {"type": "number", "minimum": 1, "maximum": 100}}}}, |
|
{"if": {"properties": {"type": {"const": "heal"}}}, "then": {"properties": {"amount": {"enum": ["small", "medium", "large", "full"]}, "formula": {"enum": ["percentage", "fixed"]}, "value": {"type": "number"}}}}, |
|
{"if": {"properties": {"type": {"const": "fieldEffect"}}}, "then": {"properties": {"effect": {"enum": ["reflect", "lightScreen", "spikes", "healingMist", "toxicSpikes"]}, "stackable": {"type": "boolean"}}}}, |
|
{"if": {"properties": {"type": {"const": "manipulatePP"}}}, "then": {"properties": {"action": {"enum": ["drain", "restore", "disable"]}, "amount": {"enum": ["small", "medium", "large"]}}}}, |
|
{"if": {"properties": {"type": {"const": "counter"}}}, "then": {"properties": {"strength": {"enum": ["weak", "normal", "strong"]}}}}, |
|
{"if": {"properties": {"type": {"const": "priority"}}}, "then": {"properties": {"value": {"type": "integer", "minimum": -5, "maximum": 5}}}}, |
|
{"if": {"properties": {"type": {"const": "removeStatus"}}}, "then": {"properties": {"status": {"enum": ["burn", "freeze", "paralyze", "poison", "sleep", "confuse"]}}}}, |
|
{"if": {"properties": {"type": {"const": "mechanicOverride"}}}, "then": {"properties": {"mechanic": {"enum": ["criticalHits", "statusImmunity", "damageReflection", "damageAbsorption", "damageCalculation", "damageMultiplier", "healingInversion", "healingBlocked", "priorityOverride", "accuracyBypass", "typeImmunity", "typeChange", "contactDamage", "drainInversion", "weatherImmunity", "flagImmunity", "flagWeakness", "flagResistance", "statModification", "targetRedirection", "extraTurn"]}, "value": {}}}} |
|
] |
|
}, |
|
"Trigger": { |
|
"type": "object", |
|
"properties": { |
|
"event": {"type": "string", "enum": ["onSwitchIn", "onDamageTaken", "onContactDamage", "endOfTurn", "onLowHP", "onStatusInflicted", "beforeMoveUse", "afterMoveUse"]}, |
|
"condition": {"type": "string", "enum": ["always", "ifLowHp", "ifHighHp", "ifStatus:burn", "ifStatus:freeze", "ifStatus:paralyze", "ifStatus:poison", "ifStatus:sleep", "ifStatus:confuse"]}, |
|
"effects": {"type": "array", "items": {"$ref": "#/definitions/Effect"}, "minItems": 1} |
|
}, |
|
"required": ["event", "effects"] |
|
}, |
|
"Move": { |
|
"type": "object", |
|
"properties": { |
|
"name": {"type": "string", "description": "Name of the move"}, |
|
"description": {"type": "string", "description": "Description of what the move does"}, |
|
"type": {"type": "string", "enum": ["beast", "bug", "aquatic", "flora", "mineral", "space", "machina", "structure", "culture", "cuisine", "normal"], "description": "Move type for STAB and effectiveness"}, |
|
"power": {"type": "integer", "minimum": 0, "maximum": 250, "description": "Base power (0 for status moves)"}, |
|
"accuracy": {"type": "integer", "minimum": 30, "maximum": 100, "description": "Hit chance percentage"}, |
|
"pp": {"type": "integer", "minimum": 1, "maximum": 40, "description": "Power points (uses per battle)"}, |
|
"priority": {"type": "integer", "minimum": -5, "maximum": 5, "description": "Priority bracket"}, |
|
"flags": {"type": "array", "items": {"enum": ["contact", "explosive", "draining", "priority", "sacrifice", "reckless", "bite", "punch", "sound", "ground"]}, "description": "Move characteristics"}, |
|
"effects": {"type": "array", "items": {"$ref": "#/definitions/Effect"}, "minItems": 1, "description": "What the move does"} |
|
}, |
|
"required": ["name", "type", "power", "accuracy", "pp", "priority", "flags", "effects"], |
|
"additionalProperties": false |
|
} |
|
} |
|
} |
|
\`\`\` |
|
|
|
**STAT GUIDELINES:** |
|
Base the tier and stats on the object rarity: |
|
- **common → low tier**: hp/attack/defense/speed should be 10-25 (total ~40-80) |
|
- **uncommon → medium tier**: hp/attack/defense/speed should be 15-35 (total ~80-120) |
|
- **rare → high tier**: hp/attack/defense/speed should be 25-45 (total ~120-160) |
|
- **legendary → legendary tier**: hp/attack/defense/speed should be 35-50 (total ~160-200) |
|
|
|
**CREATIVITY & DIVERSITY REQUIREMENTS:** |
|
🎲 **CRITICAL**: Make this monster unique! Avoid generic patterns and create something distinctive. |
|
|
|
**SPECIAL ABILITY CREATIVITY:** |
|
- Draw inspiration from the SPECIFIC object description and monster concept |
|
- Avoid overused triggers like "onSwitchIn with healingMist" |
|
- Use diverse triggers: onContactDamage, onLowHP, onStatusInflicted, onCriticalHit, etc. |
|
- Create unique effects that match the monster's nature and appearance |
|
|
|
**MOVEPOOL DIVERSITY REQUIREMENTS:** |
|
- Each of the 4 moves MUST use different primary effect types |
|
- Vary the mechanics: one utility, one status, one damage, one defensive/field effect |
|
- Use different status effects if applying status (avoid repeating burn/sleep/paralyze) |
|
- Vary power/accuracy/PP patterns - don't use template values |
|
- Reference specific visual elements from the monster description in move names |
|
|
|
**FORBIDDEN REPETITIVE PATTERNS:** |
|
❌ Do NOT use these overused combinations: |
|
- "healingMist" field effect on switch-in (find alternatives!) |
|
- Defense boost + small percentage heal combo moves |
|
- High power + self-recoil damage as the only "ultimate" move pattern |
|
- All moves having same status effect (sleep/paralyze) |
|
- Generic move names like "Basic Attack" or "Status Move" |
|
|
|
**ORIGINALITY GUIDELINES:** |
|
- Connect abilities to the original object's unique properties |
|
- Use unconventional effect combinations and mechanics |
|
- Experiment with mechanicOverride, priority manipulation, counter effects |
|
- Create moves that tell a story about how this creature fights |
|
|
|
Write your response within \`\`\`json\`\`\``; |
|
|
|
console.log('Generating monster stats'); |
|
|
|
try { |
|
const responseText = await generateText(statsPrompt); |
|
|
|
if (!responseText || responseText.trim() === '') { |
|
throw new Error('Failed to generate monster stats'); |
|
} |
|
|
|
console.log('Stats output:', responseText); |
|
let jsonString = responseText; |
|
|
|
|
|
let cleanJson = jsonString; |
|
if (jsonString.includes('```')) { |
|
const matches = jsonString.match(/```(?:json)?\s*([\s\S]*?)```/); |
|
if (matches) { |
|
cleanJson = matches[1]; |
|
} else { |
|
|
|
cleanJson = jsonString.replace(/^```(?:json)?\s*/, '').replace(/```\s*$/, ''); |
|
} |
|
} |
|
|
|
try { |
|
|
|
const startIndex = cleanJson.indexOf('{'); |
|
if (startIndex !== -1) { |
|
let braceCount = 0; |
|
let endIndex = -1; |
|
|
|
|
|
for (let i = startIndex; i < cleanJson.length; i++) { |
|
if (cleanJson[i] === '{') braceCount++; |
|
if (cleanJson[i] === '}') { |
|
braceCount--; |
|
if (braceCount === 0) { |
|
endIndex = i; |
|
break; |
|
} |
|
} |
|
} |
|
|
|
if (endIndex !== -1) { |
|
cleanJson = cleanJson.substring(startIndex, endIndex + 1); |
|
console.log('Balanced JSON extracted, length:', cleanJson.length); |
|
} else { |
|
throw new Error('JSON appears to be truncated - unable to balance braces'); |
|
} |
|
} else { |
|
throw new Error('No JSON object found in response'); |
|
} |
|
|
|
console.log('Final JSON to parse (length: ' + cleanJson.length + '):', cleanJson.substring(0, 500) + '...'); |
|
|
|
|
|
cleanJson = cleanJson.replace(/"priority":\s*\+(\d+)/g, '"priority": $1'); |
|
|
|
|
|
cleanJson = cleanJson.replace(/"([^"\\]*)(?:\\.|[^"\\])*"/g, (match) => { |
|
|
|
if (match.includes('\n')) { |
|
return match.replace(/\n/g, '\\n').replace(/\r/g, '\\r'); |
|
} |
|
return match; |
|
}); |
|
|
|
const parsedStats = JSON.parse(cleanJson.trim()); |
|
|
|
|
|
console.log('Parsed battle monster:', parsedStats); |
|
|
|
|
|
if (!parsedStats.name || !parsedStats.baseStats || !parsedStats.specialAbility || !parsedStats.movepool) { |
|
throw new Error('Generated monster is missing required battle system fields'); |
|
} |
|
|
|
|
|
if (!Array.isArray(parsedStats.movepool) || parsedStats.movepool.length !== 4) { |
|
throw new Error('Monster movepool must contain exactly 4 moves'); |
|
} |
|
|
|
|
|
for (const move of parsedStats.movepool) { |
|
if (!move.effects || !Array.isArray(move.effects) || move.effects.length === 0) { |
|
throw new Error(`Move "${move.name}" is missing effects array`); |
|
} |
|
} |
|
|
|
|
|
tier = parsedStats.tier || 'medium'; |
|
|
|
|
|
if (parsedStats.name) { |
|
parsedStats.name = parsedStats.name.replace(/\*/g, ''); |
|
} |
|
|
|
|
|
if (parsedStats.specialAbility?.name) { |
|
parsedStats.specialAbility.name = parsedStats.specialAbility.name.replace(/\*/g, ''); |
|
} |
|
|
|
|
|
if (parsedStats.movepool) { |
|
for (const move of parsedStats.movepool) { |
|
if (move.name) { |
|
move.name = move.name.replace(/\*/g, ''); |
|
} |
|
} |
|
} |
|
|
|
|
|
if (monsterName && monsterName !== 'Unknown Monster') { |
|
|
|
parsedStats.name = monsterName.replace(/\*/g, ''); |
|
} |
|
|
|
|
|
if (parsedStats.baseStats) { |
|
const statFields = ['hp', 'attack', 'defense', 'speed']; |
|
for (const field of statFields) { |
|
if (parsedStats.baseStats[field] !== undefined) { |
|
parsedStats.baseStats[field] = Math.max(10, Math.min(50, parseInt(parsedStats.baseStats[field]))); |
|
} |
|
} |
|
} |
|
|
|
const stats: PicletStats = parsedStats; |
|
workflowState.picletStats = stats; |
|
console.log('Monster stats generated:', stats); |
|
console.log('Monster stats JSON:', JSON.stringify(stats, null, 2)); |
|
} catch (parseError) { |
|
console.error('Failed to parse JSON:', parseError, 'Raw output:', cleanJson); |
|
throw new Error('Failed to parse monster stats JSON'); |
|
} |
|
} catch (error) { |
|
handleAPIError(error); |
|
} |
|
} |
|
|
|
async function autoSavePiclet() { |
|
if (!workflowState.picletImage || !workflowState.imageCaption || !workflowState.picletConcept || !workflowState.imagePrompt || !workflowState.picletStats) { |
|
console.error('Cannot auto-save: missing required data'); |
|
return; |
|
} |
|
|
|
try { |
|
|
|
const cleanStats = JSON.parse(JSON.stringify(workflowState.picletStats)); |
|
|
|
const picletData = { |
|
name: workflowState.picletStats.name, |
|
imageUrl: workflowState.picletImage.imageUrl, |
|
imageData: workflowState.picletImage.imageData, |
|
imageCaption: workflowState.imageCaption, |
|
concept: workflowState.picletConcept, |
|
imagePrompt: workflowState.imagePrompt, |
|
stats: cleanStats, |
|
createdAt: new Date() |
|
}; |
|
|
|
|
|
console.log('Checking piclet data for serializability:'); |
|
console.log('- name type:', typeof picletData.name); |
|
console.log('- imageUrl type:', typeof picletData.imageUrl); |
|
console.log('- imageData type:', typeof picletData.imageData, picletData.imageData ? `length: ${picletData.imageData.length}` : 'null/undefined'); |
|
console.log('- imageCaption type:', typeof picletData.imageCaption); |
|
console.log('- concept type:', typeof picletData.concept); |
|
console.log('- imagePrompt type:', typeof picletData.imagePrompt); |
|
console.log('- stats:', cleanStats); |
|
|
|
|
|
const picletInstance = await generatedDataToPicletInstance(picletData); |
|
const picletId = await savePicletInstance(picletInstance); |
|
console.log('Piclet auto-saved as uncaught with ID:', picletId); |
|
|
|
|
|
if (isTrainerMode && onTrainerImageCompleted && trainerImagePaths[currentImageIndex]) { |
|
onTrainerImageCompleted(trainerImagePaths[currentImageIndex], picletId); |
|
} |
|
} catch (err) { |
|
console.error('Failed to auto-save piclet:', err); |
|
console.error('Piclet data that failed to save:', { |
|
name: workflowState.picletStats?.name, |
|
hasImageUrl: !!workflowState.picletImage?.imageUrl, |
|
hasImageData: !!workflowState.picletImage?.imageData, |
|
hasStats: !!workflowState.picletStats |
|
}); |
|
|
|
|
|
if (isTrainerMode && onTrainerImageFailed && trainerImagePaths[currentImageIndex]) { |
|
const errorMessage = err instanceof Error ? err.message : 'Failed to save piclet'; |
|
onTrainerImageFailed(trainerImagePaths[currentImageIndex], errorMessage); |
|
} |
|
|
|
|
|
} |
|
} |
|
|
|
function reset() { |
|
workflowState = { |
|
currentStep: 'upload', |
|
userImage: null, |
|
imageCaption: null, |
|
picletConcept: null, |
|
picletStats: null, |
|
imagePrompt: null, |
|
picletImage: null, |
|
error: null, |
|
isProcessing: false |
|
}; |
|
} |
|
|
|
|
|
export function queueTrainerImage(imageFile: File, imagePath: string) { |
|
imageQueue.push(imageFile); |
|
trainerImagePaths.push(imagePath); |
|
|
|
|
|
if (imageQueue.length === 1 && !workflowState.isProcessing) { |
|
processCurrentImage(); |
|
} |
|
} |
|
</script> |
|
|
|
<div class="piclet-generator"> |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
{#if workflowState.currentStep !== 'upload'} |
|
<WorkflowProgress currentStep={workflowState.currentStep} error={workflowState.error} /> |
|
{/if} |
|
|
|
{#if workflowState.currentStep === 'upload'} |
|
<UploadStep |
|
onImageSelected={handleImageSelected} |
|
onImagesSelected={handleImagesSelected} |
|
isProcessing={workflowState.isProcessing} |
|
imageQueue={imageQueue} |
|
currentImageIndex={currentImageIndex} |
|
/> |
|
{:else if workflowState.currentStep === 'complete'} |
|
<PicletResult workflowState={workflowState} onReset={reset} /> |
|
{:else} |
|
<div class="processing-container"> |
|
<div class="spinner"></div> |
|
<p class="processing-text"> |
|
{#if workflowState.currentStep === 'captioning'} |
|
Analyzing your image... |
|
{:else if workflowState.currentStep === 'conceptualizing'} |
|
Creating Piclet concept... |
|
{:else if workflowState.currentStep === 'statsGenerating'} |
|
Generating battle stats... |
|
{:else if workflowState.currentStep === 'promptCrafting'} |
|
Creating image prompt... |
|
{:else if workflowState.currentStep === 'generating'} |
|
Generating your Piclet... |
|
{/if} |
|
</p> |
|
</div> |
|
{/if} |
|
</div> |
|
|
|
<style> |
|
.piclet-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; |
|
} |
|
|
|
</style> |