Spaces:
Running
Running
File size: 22,911 Bytes
21d7fc3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 |
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
});
}
} |