word-to-code / pages /api /generate.js
tinazone's picture
Upload 44 files
21d7fc3 verified
raw
history blame
22.9 kB
const {
GoogleGenerativeAI,
HarmCategory,
HarmBlockThreshold,
} = require("@google/generative-ai");
const apiKey = process.env.GEMINI_API_KEY;
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({
model: "gemini-2.0-flash-thinking-exp-01-21",
safetySettings: [
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
{
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
{
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
],
});
const generationConfig = {
temperature: 0.7,
topP: 0.95,
topK: 64,
maxOutputTokens: 65536,
};
const systemPrompt = `You are a creative coding expert specializing in p5.js animations. Given a single word, you create expressive looping animations that bring that word to life using particle systems.
Here are example animations that show different particle behaviors, along with the reasoning behind each approach:
EXAMPLE 1 - "fluid":
Reasoning: To capture the essence of "fluid", I'll use Perlin noise to create smooth, organic movement of particles. The particles will flow like water or liquid, with each particle following its own noise-based path while maintaining a cohesive, flowing appearance. The blue gradient colors reinforce the liquid feeling, and the screen blend mode creates a glowing effect that enhances the fluid motion.
Code:
let font;
let fontSize = 200;
let word = "fluid";
let points;
let particles = [];
let particleMinSize = 3;
let particleMaxSize = 7;
// Fluid effect parameters
let noiseScale = 0.015; // Scale of the Perlin noise - adjust for wave size
let noiseStrength = 20; // Intensity of the noise displacement
let noiseSpeed = 0.002; // Speed of the noise evolution
// Colors for gradient
let color1 = "#217BFE";
let color2 = "#078BFE";
let color3 = "#AC87EB";
function preload() {
font = loadFont('/fonts/GoogleSans-Bold.ttf');
}
function setup() {
createCanvas(500, 500);
background(0);
textFont(font);
textSize(fontSize);
textAlign(CENTER, CENTER);
// Get the width of the text
let textW = textWidth(word);
// If text is too wide, scale down fontSize
if (textW > width * 0.8) {
fontSize = fontSize * (width * 0.8) / textW;
textSize(fontSize);
textW = textWidth(word);
}
points = font.textToPoints(word, width/2 - textW/2, height/2 + fontSize/3, fontSize, {
sampleFactor: 0.1
});
for (let i = 0; i < points.length; i++) {
particles.push(new Particle(points[i].x, points[i].y, i, points.length));
}
}
function draw() {
blendMode(BLEND); // Reset to default blend mode first
background(0); // Clear with black background
blendMode(SCREEN); // Then set screen blend mode for particles
for (let particle of particles) {
particle.update();
particle.display();
}
}
class Particle {
constructor(x, y, index, totalParticles) {
this.pos = createVector(x, y);
this.originalPos = createVector(x, y);
this.originalX = x;
this.originalY = y;
this.size = random(particleMinSize, particleMaxSize);
this.alpha = 255;
this.colorValue = this.getColor(index, totalParticles);
}
getColor(index, totalParticles) {
let normalizedIndex = index / (totalParticles - 1);
let particleColor;
if (normalizedIndex < 0.5) {
particleColor = lerpColor(color(color1), color(color2), normalizedIndex * 2);
} else {
particleColor = lerpColor(color(color2), color(color3), (normalizedIndex - 0.5) * 2);
}
return particleColor;
}
update() {
let noiseValueX = noise((this.originalX + frameCount) * noiseScale,
this.originalY * noiseScale,
frameCount * noiseSpeed);
let noiseValueY = noise(this.originalX * noiseScale,
this.originalY * noiseScale,
frameCount * noiseSpeed + 1000);
let offsetX = map(noiseValueX, 0, 1, -noiseStrength, noiseStrength);
let offsetY = map(noiseValueY, 0, 1, -noiseStrength, noiseStrength);
this.pos.x = this.originalPos.x + offsetX;
this.pos.y = this.originalPos.y + offsetY;
}
display() {
noStroke();
fill(this.colorValue);
ellipse(this.pos.x, this.pos.y, this.size, this.size);
}
}
EXAMPLE 2 - "rise":
Reasoning: For "rise", I'll create a staged animation where particles gradually appear, pause briefly, then float upward. This creates a sense of emergence and ascension. Each particle follows this sequence independently with slight timing variations, creating a continuous cycle of rising elements. The fade-in adds a gentle, ethereal quality that matches the upward motion.
Code:
let font;
let fontSize = 200;
let word = "rise";
let points;
let particles = [];
let floatSpeed = 4;
let fadeInSpeed = 10;
let minWaitTime = 50;
let maxWaitTime = 200;
let particleMinSize = 3;
let particleMaxSize = 7;
let color1 = "#217BFE";
let color2 = "#078BFE";
let color3 = "#AC87EB";
function preload() {
font = loadFont('/fonts/GoogleSans-Bold.ttf');
}
function setup() {
createCanvas(500, 500);
background(0);
textFont(font);
textSize(fontSize);
textAlign(CENTER, CENTER);
// Get the width of the text
let textW = textWidth(word);
// If text is too wide, scale down fontSize
if (textW > width * 0.8) {
fontSize = fontSize * (width * 0.8) / textW;
textSize(fontSize);
textW = textWidth(word);
}
points = font.textToPoints(word, width/2 - textW/2, height/2 + fontSize/3, fontSize, {
sampleFactor: 0.1
});
// Find min and max x positions for color gradient
let minX = points[0].x;
let maxX = points[0].x;
for (let pt of points) {
minX = min(minX, pt.x);
maxX = max(maxX, pt.x);
}
let xRange = maxX - minX;
for (let pt of points) {
particles.push(new Particle(pt.x, pt.y, pt.x, minX, xRange));
}
}
function draw() {
blendMode(BLEND);
background(0);
blendMode(SCREEN);
for (let particle of particles) {
particle.update();
particle.display();
}
}
class Particle {
constructor(x, y, particleX, minX, xRange) {
this.pos = createVector(x, y);
this.originalPos = createVector(x, y);
this.size = random(particleMinSize, particleMaxSize);
this.alpha = 255;
this.floatSpeedVariation = random(0.5, 2.0);
this.isFadingIn = true;
this.isWaiting = false;
this.waitTime = 0;
this.particleX = particleX;
this.minX = minX;
this.xRange = xRange;
this.color = this.getColorForPosition();
}
getColorForPosition() {
let normalizedX = 0;
if (this.xRange > 0) {
normalizedX = constrain((this.particleX - this.minX) / this.xRange, 0, 1);
}
let particleColor;
if (normalizedX < 0.5) {
particleColor = lerpColor(color(color1), color(color2), normalizedX * 2);
} else {
particleColor = lerpColor(color(color2), color(color3), (normalizedX - 0.5) * 2);
}
return particleColor;
}
update() {
if (this.isFadingIn) {
this.alpha += fadeInSpeed;
if (this.alpha >= 255) {
this.alpha = 255;
this.isFadingIn = false;
this.isWaiting = true;
this.waitTime = floor(random(minWaitTime, maxWaitTime));
}
} else if (this.isWaiting) {
this.waitTime--;
if (this.waitTime <= 0) {
this.isWaiting = false;
}
} else {
this.pos.y -= floatSpeed * this.floatSpeedVariation;
if (this.pos.y < -this.size) {
this.respawn();
}
}
}
respawn() {
this.pos.y = this.originalPos.y;
this.pos.x = this.originalPos.x;
this.alpha = 0;
this.isFadingIn = true;
this.isWaiting = false;
this.waitTime = 0;
this.size = random(particleMinSize, particleMaxSize);
this.floatSpeedVariation = random(0.5, 2.0);
this.color = this.getColorForPosition();
}
display() {
noStroke();
fill(red(this.color), green(this.color), blue(this.color), this.alpha);
ellipse(this.pos.x, this.pos.y, this.size, this.size);
}
}
EXAMPLE 3 - "light":
Reasoning: To visualize "light", I'll make particles that pulse and glow like twinkling lights. Each particle will cycle through brightness levels independently, creating a sparkling effect. Adding blur and glow effects when particles are at peak brightness enhances the illuminated feeling. The gradient colors blend into white at maximum brightness for a true lighting effect.
Code:
let font;
let fontSize = 200;
let word = "light";
let points;
let particles = [];
let lightCycleSpeed = 0.02;
let particleMinSize = 5;
let particleMaxSize = 5;
let shadowBlurAmount = 30;
let minX, maxX;
let color1 = "#217BFE";
let color2 = "#078BFE";
let color3 = "#AC87EB";
let lightColor;
function preload() {
font = loadFont('/fonts/GoogleSans-Bold.ttf');
}
function setup() {
createCanvas(500, 500);
background(0);
lightColor = color(255, 255, 255);
textFont(font);
textSize(fontSize);
textAlign(CENTER, CENTER);
// Get the width of the text
let textW = textWidth(word);
// If text is too wide, scale down fontSize
if (textW > width * 0.8) {
fontSize = fontSize * (width * 0.8) / textW;
textSize(fontSize);
textW = textWidth(word);
}
points = font.textToPoints(word, width/2 - textW/2, height/2 + fontSize/3, fontSize, {
sampleFactor: 0.1
});
minX = width;
maxX = 0;
for (let pt of points) {
minX = min(minX, pt.x);
maxX = max(maxX, pt.x);
}
for (let i = 0; i < points.length; i++) {
let pt = points[i];
particles.push(new Particle(pt.x, pt.y, i));
}
}
function draw() {
blendMode(BLEND); // Reset to default blend mode first
background(0); // Clear with black background
blendMode(SCREEN); // Then set screen blend mode for particles
for (let particle of particles) {
particle.update();
particle.display();
}
}
class Particle {
constructor(x, y, index) {
this.pos = createVector(x, y);
this.size = random(particleMinSize, particleMaxSize);
this.alpha = 255;
this.lightOffset = index * 0.1;
}
update() {
// No position update needed for light animation
}
getBaseColor() {
let normalizedX = map(this.pos.x, minX, maxX, 0, 1);
let baseParticleColor;
if (normalizedX < 0.5) {
baseParticleColor = lerpColor(color(color1), color(color2), normalizedX * 2);
} else {
baseParticleColor = lerpColor(color(color2), color(color3), (normalizedX - 0.5) * 2);
}
return baseParticleColor;
}
display() {
let brightness = sin(frameCount * lightCycleSpeed + this.lightOffset);
brightness = map(brightness, -1, 1, 0, 1);
brightness = constrain(brightness, 0, 1);
let baseParticleColor = this.getBaseColor();
let particleColor = lerpColor(baseParticleColor, lightColor, brightness);
noStroke();
if (brightness > 0.8) {
drawingContext.shadowBlur = shadowBlurAmount;
drawingContext.shadowColor = color(255);
fill(particleColor);
ellipse(this.pos.x, this.pos.y, this.size * 1.5, this.size * 1.5);
drawingContext.shadowBlur = 0;
} else {
drawingContext.shadowBlur = 0;
fill(particleColor);
ellipse(this.pos.x, this.pos.y, this.size, this.size);
}
}
}
EXAMPLE 4 - "travel":
Reasoning: For "travel", particles will journey along the letter contours, creating a sense of continuous movement and exploration. Each particle follows the path of letter points, creating flowing trails that highlight the shape of the text. The movement speed and particle size are tuned to maintain legibility while conveying constant motion.
Code:
let font;
let fontSize = 200;
let word = "travel";
let points;
let particles = [];
let travelSpeed = 0.8;
let particleMinSize = 4;
let particleMaxSize = 4;
let minX, maxX;
let color1 = "#217BFE";
let color2 = "#078BFE";
let color3 = "#AC87EB";
function preload() {
font = loadFont('/fonts/GoogleSans-Bold.ttf');
}
function setup() {
createCanvas(500, 500);
background(0);
textFont(font);
textSize(fontSize);
textAlign(CENTER, CENTER);
// Get the width of the text
let textW = textWidth(word);
// If text is too wide, scale down fontSize
if (textW > width * 0.8) {
fontSize = fontSize * (width * 0.8) / textW;
textSize(fontSize);
textW = textWidth(word);
}
points = font.textToPoints(word, width/2 - textW/2, height/2 + fontSize/3, fontSize, {
sampleFactor: 0.1
});
minX = width;
maxX = 0;
for (let pt of points) {
minX = min(minX, pt.x);
maxX = max(maxX, pt.x);
}
for (let i = 0; i < points.length; i++) {
let pt = points[i];
particles.push(new Particle(pt.x, pt.y, i, points));
}
}
function draw() {
blendMode(BLEND); // Reset to default blend mode first
background(0); // Clear with black background
blendMode(SCREEN); // Then set screen blend mode for particles
for (let particle of particles) {
particle.update();
particle.display();
}
}
class Particle {
constructor(x, y, index, allPoints) {
this.pos = createVector(x, y);
this.size = random(particleMinSize, particleMaxSize);
this.alpha = 255;
this.pointIndex = index;
this.points = allPoints;
this.targetPoint = this.getNextTargetPoint();
}
getNextTargetPoint() {
if (this.points.length === 0) return this.pos;
this.pointIndex++;
if (this.pointIndex >= this.points.length) {
this.pointIndex = 0;
}
return createVector(this.points[this.pointIndex].x, this.points[this.pointIndex].y);
}
update() {
if (!this.targetPoint) return;
let direction = p5.Vector.sub(this.targetPoint, this.pos);
let distance = direction.mag();
if (distance < 1) {
this.targetPoint = this.getNextTargetPoint();
if (!this.targetPoint) return;
direction = p5.Vector.sub(this.targetPoint, this.pos);
}
direction.normalize();
direction.mult(travelSpeed);
this.pos.add(direction);
}
display() {
noStroke();
let normalizedX = map(this.pos.x, minX, maxX, 0, 1, true);
let particleColor = this.getColorBlend(normalizedX);
fill(particleColor);
ellipse(this.pos.x, this.pos.y, this.size, this.size);
}
getColorBlend(normalizedX) {
if (normalizedX < 0.5) {
return lerpColor(color(color1), color(color2), normalizedX * 2);
} else {
return lerpColor(color(color2), color(color3), (normalizedX - 0.5) * 2);
}
}
}
EXAMPLE 5 - "bounce":
Reasoning: To represent "bounce", I'll implement simple physics with gravity and elastic collision. Particles fall and bounce off surfaces with dampening, creating a playful and dynamic animation. The varying particle sizes and bounce heights add visual interest while maintaining the word's readability.
Code:
let font;
let fontSize = 200;
let word = "bounce";
let points;
let particles = [];
let gravity = 0.5;
let bounce = -0.7;
let friction = 0.99;
let particleMinSize = 3;
let particleMaxSize = 7;
let color1 = "#217BFE";
let color2 = "#078BFE";
let color3 = "#AC87EB";
function preload() {
font = loadFont('/fonts/GoogleSans-Bold.ttf');
}
function setup() {
createCanvas(500, 500);
background(0);
textFont(font);
textSize(fontSize);
textAlign(CENTER, CENTER);
// Get the width of the text
let textW = textWidth(word);
// If text is too wide, scale down fontSize
if (textW > width * 0.8) {
fontSize = fontSize * (width * 0.8) / textW;
textSize(fontSize);
textW = textWidth(word);
}
points = font.textToPoints(word, width/2 - textW/2, height/2 + fontSize/3, fontSize, {
sampleFactor: 0.1
});
// Find min and max x positions for color gradient
let minX = points[0].x;
let maxX = points[0].x;
for (let pt of points) {
minX = min(minX, pt.x);
maxX = max(maxX, pt.x);
}
for (let pt of points) {
let normalizedX = map(pt.x, minX, maxX, 0, 1);
particles.push(new Particle(pt.x, pt.y, normalizedX));
}
}
function draw() {
blendMode(BLEND);
background(0);
blendMode(SCREEN);
for (let particle of particles) {
particle.update();
particle.display();
}
}
class Particle {
constructor(x, y, normalizedX) {
this.pos = createVector(x, y);
this.vel = createVector(random(-2, 2), random(-10, -5));
this.acc = createVector(0, gravity);
this.size = random(particleMinSize, particleMaxSize);
this.originalY = y;
this.colorValue = this.getColor(normalizedX);
}
getColor(normalizedX) {
let particleColor;
if (normalizedX < 0.5) {
particleColor = lerpColor(color(color1), color(color2), normalizedX * 2);
} else {
particleColor = lerpColor(color(color2), color(color3), (normalizedX - 0.5) * 2);
}
return particleColor;
}
update() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.vel.x *= friction;
if (this.pos.y > height - this.size/2) {
this.pos.y = height - this.size/2;
this.vel.y *= bounce;
}
if (this.pos.x < this.size/2) {
this.pos.x = this.size/2;
this.vel.x *= bounce;
} else if (this.pos.x > width - this.size/2) {
this.pos.x = width - this.size/2;
this.vel.x *= bounce;
}
// Reset particle if it goes too far down
if (this.pos.y > height + 100) {
this.pos.y = this.originalY;
this.vel.y = random(-10, -5);
}
}
display() {
noStroke();
fill(this.colorValue);
ellipse(this.pos.x, this.pos.y, this.size, this.size);
}
}
Your task is to create a similar p5.js sketch for the given word. Follow these rules:
Keep all the consistent elements:
- Looping
- Canvas size: 500x500
- Font: GoogleSans-Bold.ttf
- Initial fontSize: 200 (will adjust automatically)
- ALWAYS Colors: #217BFE, #078BFE, #AC87EB gradient
- Text alignment: CENTER, CENTER
- Proper text centering using textWidth()
- IMPORTANT: Always position text vertically using: height/2 + fontSize/3
Return ONLY the complete p5.js code in global mode format, with all necessary functions (preload, setup, draw) and variables defined globally.`;
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ message: 'Method not allowed' });
}
try {
const { word, instructions } = req.body;
if (!word) {
return res.status(400).json({ message: 'Word is required' });
}
const prompt = `Create a p5.js animation for the word "${word}"${instructions ? ` with these additional requirements: ${instructions}` : ''}.
First, explain your creative approach:
- How will you animate this word to reflect its meaning?
- What particle behaviors and effects will you use?
- How will these choices enhance the viewer's understanding of the word?
Then provide the complete p5.js sketch code using these requirements:
- Canvas size of 500x500
- Black background
- Font loading from '/fonts/GoogleSans-Bold.ttf'
- Gradient colors using #217BFE, #078BFE, and #AC87EB
- Screen blend mode for particles
- Responsive text sizing
- Global mode format (no instance mode wrapper)
Animation timing requirements:
- Start with particles clearly forming the word on the screen
- If particles move away from the word, they should do so gradually
- For any cycling animations, ensure each cycle is slow enough to read the word
Your response MUST follow this exact format:
Reasoning:
[Your explanation here]
Code:
[Your code here in global mode format]
Make sure your code is complete and properly closed with all necessary brackets.`;
const result = await model.generateContent([systemPrompt, prompt], generationConfig);
const response = await result.response;
const text = response.text();
console.log('Raw model response:', text); // Debug log
// Extract reasoning and code using multiple fallback approaches
let reasoning = '';
let code = '';
// Helper function to clean code
const cleanCode = (str) => {
return str
.replace(/```javascript\s*/g, '')
.replace(/```js\s*/g, '')
.replace(/```\s*/g, '')
.replace(/^Code:\s*/g, '')
.trim();
};
// Helper function to validate global mode code
const isValidCode = (str) => {
return str.includes('function setup()') &&
str.includes('function draw()') &&
str.includes('function preload()') &&
(str.match(/{/g) || []).length === (str.match(/}/g) || []).length; // Check balanced braces
};
// Approach 1: Try to extract from markdown code blocks
const codeBlockMatch = text.match(/```(?:javascript|js)?\s*(let\s+font[\s\S]*?class\s+Particle[\s\S]*?})\s*```/);
if (codeBlockMatch) {
code = cleanCode(codeBlockMatch[1]);
reasoning = text.split('```')[0].replace(/^Reasoning:\s*/i, '').trim();
}
// Approach 2: Try to split by explicit "Reasoning:" and "Code:" markers
if (!code && text.includes('Reasoning:') && text.includes('Code:')) {
const [reasoningPart, codePart] = text.split(/Code:\s*/i);
reasoning = reasoningPart.replace(/^Reasoning:\s*/i, '').trim();
code = cleanCode(codePart);
}
// Approach 3: Look for global mode function declarations
if (!code) {
const functionMatch = text.match(/(let\s+font[\s\S]*function\s+setup\(\)[\s\S]*function\s+draw\(\)[\s\S]*class\s+Particle[\s\S]*$)/);
if (functionMatch) {
code = cleanCode(functionMatch[1]);
reasoning = text.split(functionMatch[1])[0].replace(/^Reasoning:\s*/i, '').trim();
}
}
// Approach 4: Most aggressive - find anything that looks like the global mode structure
if (!code) {
const lastResortMatch = text.match(/let\s+font[\s\S]*?class\s+Particle[\s\S]*?}/);
if (lastResortMatch) {
code = cleanCode(lastResortMatch[0]);
reasoning = text.replace(lastResortMatch[0], '').replace(/^Reasoning:\s*/i, '').trim();
}
}
// Final validation
if (!code || !isValidCode(code)) {
console.error('Invalid code structure:', { code: code?.substring(0, 100) });
throw new Error('Could not extract valid p5.js sketch code from the response');
}
console.log('Successfully parsed response:', {
reasoningPreview: reasoning?.substring(0, 100) + '...',
codePreview: code?.substring(0, 100) + '...',
});
return res.status(200).json({
code,
fullResponse: reasoning || 'No explanation provided'
});
} catch (error) {
console.error('Error generating animation:', error);
return res.status(500).json({
message: 'Error generating animation',
error: error.message
});
}
}