Iot / scripts /seed-data.js
veltrixcode's picture
Upload 74 files
64fa001 verified
Raw
History Blame Contribute Delete
10.7 kB
const fs = require('fs');
const path = require('path');
// Load .env manually since dotenv might not be installed
try {
const envPath = path.resolve(__dirname, '../.env');
if (fs.existsSync(envPath)) {
const envConfig = fs.readFileSync(envPath, 'utf8');
envConfig.split('\n').forEach(line => {
line = line.trim();
if (!line || line.startsWith('#')) return;
const [key, ...valueParts] = line.split('=');
if (key && valueParts.length > 0) {
let value = valueParts.join('=').trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
if (!process.env[key.trim()]) {
process.env[key.trim()] = value;
}
}
});
console.log("Loaded .env file");
}
} catch (e) {
console.warn("Could not load .env file:", e.message);
}
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
// Configuration
const WORKER_URL = process.env.CLOUDFLARE_WORKER_URL || "https://wild-art-dca7.veltrix620.workers.dev"; // Fallback if env not set
const MODELS = ["flux-klein", "flux-klein-4b"];
// 10 Realistic Indian Users
const USERS = [
{ name: "Aarav Patel", email: "aarav.patel@gmail.com", username: "aarav_art" },
{ name: "Diya Sharma", email: "diya.sharma88@outlook.com", username: "diya_creates" },
{ name: "Vihaan Singh", email: "vihaan.singh@yahoo.com", username: "vihaan_visuals" },
{ name: "Ananya Gupta", email: "ananya.g@hotmail.com", username: "art_by_ananya" },
{ name: "Arjun Reddy", email: "arjun.reddy@gmail.com", username: "arjun_pixels" },
{ name: "Zara Khan", email: "zara.khan.design@gmail.com", username: "zara_designs" },
{ name: "Ishaan Kumar", email: "ishaan.k99@outlook.com", username: "ishaan_imagines" },
{ name: "Priya Malhotra", email: "priya.malhotra@yahoo.com", username: "priya_paints" },
{ name: "Rohan Verma", email: "rohan.verma@gmail.com", username: "rohan_renders" },
{ name: "Sanya Kapoor", email: "sanya.kapoor@hotmail.com", username: "sanya_studio" }
];
// 50 Unique Prompts (5 per user)
const PROMPTS = [
// Aarav
"A futuristic cyberpunk city street in Mumbai at night, neon lights reflecting on wet pavement, 8k resolution",
"Portrait of an old Indian wise man with a turban, hyperrealistic, detailed wrinkles, warm lighting",
"A minimalist logo design of a lotus flower, vector art, flat style, orange and white",
"Concept art of a flying car in a retro-futuristic style, chrome finish, sunset background",
"Macro photography of a dew drop on a green leaf, bokeh background, natural lighting",
// Diya
"A watercolor painting of the Taj Mahal at sunrise, soft pastel colors, dreamy atmosphere",
"Digital illustration of a chaotic workspace with multiple screens and coffee cups, lo-fi aesthetic",
"A fantasy landscape with floating islands and waterfalls, vibrant colors, cinematic lighting",
"Character design of a female warrior in ancient armor, holding a glowing sword, dynamic pose",
"Abstract expressionist painting with bold brushstrokes of red and gold, chaotic texture",
// Vihaan
"A close-up of a tiger's eye, intense gaze, highly detailed fur, wildlife photography style",
"A delicious plate of butter chicken with naan, steam rising, food photography, top-down view",
"Architectural render of a modern eco-friendly house in the forest, glass walls, green roof",
"A steampunk robot playing a violin, detailed gears and brass, moody lighting",
"A stylized 3D character of a cute astronaut floating in space, low poly style",
// Ananya
"Pattern design of traditional Indian block print, indigo and white, seamless texture",
"A tranquil zen garden with raked sand and stones, morning mist, peaceful atmosphere",
"Cybernetic implant concept art, detailed metal and skin integration, blue glowing lights",
"A vintage travel poster for Goa, palm trees and beach, retro typography and colors",
"Oil painting of a rainy window looking out at a city skyline, melancholy mood",
// Arjun
"Isometric view of a cozy gaming room, neon accents, detailed props, 3D render",
"A majestic dragon perched on a mountain peak, breathing fire, epic fantasy art",
"Portrait of a woman made entirely of flowers and vines, surrealism style",
"A bustling market in Delhi, colorful spices and fabrics, vibrant energy, street photography",
"A sleek sports car drifting on a race track, motion blur, smoke effects, photorealistic",
// Zara
"Fashion illustration of a modern saree with geometric patterns, high fashion style",
"A glowing magical forest with bioluminescent plants, purple and blue color palette",
"Double exposure portrait of a man and a wolf, black and white photography",
"A tasty burger with melting cheese and fries, advertising photography style",
"Concept art of a space station orbiting a red planet, sci-fi realism",
// Ishaan
"A pixel art scene of a retro arcade, neon signs, 8-bit style",
"A detailed map of a fantasy world, parchment texture, hand-drawn style",
"A spooky haunted house on a hill, thunderstorm background, horror atmosphere",
"Product photography of a luxury perfume bottle, gold accents, elegant lighting",
"A cute anime girl with cat ears holding a bubble tea, pastel colors",
// Priya
"Mandala art with intricate patterns, black ink on white paper, meditative style",
"A majestic lion with a galaxy mane, cosmic colors, digital art",
"A snowy mountain landscape at twilight, cold blue tones, serene mood",
"Character concept of a cyberpunk hacker, neon hair, futuristic clothing",
"A vibrant fruit bowl painting, still life, impressionist style",
// Rohan
"3D text render saying 'WILD ART', metallic texture, glossy finish",
"A surreal landscape with melting clocks, inspired by Dali, dreamlike",
"A detailed sketch of a human skull, anatomical accuracy, charcoal style",
"A cozy library with wall-to-wall books, warm fireplace light, inviting atmosphere",
"A futuristic drone delivering a package, city skyline background, realistic",
// Sanya
"A fashion photoshoot of a model in a desert, flowing red dress, dramatic lighting",
"A cute vector illustration of a corgi dog wearing sunglasses, flat design",
"A post-apocalyptic city overflown with nature, ruins and vines, concept art",
"A close-up of a human eye with a universe reflection, macro photography",
"A traditional Indian wedding procession, colorful attire, festive atmosphere"
];
async function generateImage(prompt, model) {
const workerUrl = WORKER_URL.endsWith("/") ? WORKER_URL.slice(0, -1) : WORKER_URL;
const endpoint = model;
const url = `${workerUrl}/${endpoint}`;
try {
console.log(`Generating: "${prompt.slice(0, 30)}..." with ${model}`);
// Using fetch (requires Node 18+)
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt, width: 1024, height: 1024, steps: 30 }),
});
if (!response.ok) {
console.error(`Failed to generate: ${response.status} ${response.statusText}`);
return null;
}
const result = await response.json();
if (result.success && result.url) {
return result.url;
} else {
console.error("API returned success:false or no URL");
return null;
}
} catch (error) {
console.error("Generation error:", error.message);
return null;
}
}
async function main() {
console.log("🌱 Starting Data Seeding...");
// 1. Create Users
const createdUsers = [];
for (const userData of USERS) {
try {
// Check if exists
const existing = await prisma.user.findUnique({ where: { email: userData.email } });
if (existing) {
console.log(`User ${userData.name} already exists.`);
createdUsers.push(existing);
} else {
const user = await prisma.user.create({
data: {
name: userData.name,
email: userData.email,
username: userData.username,
credits: 1000, // Give them plenty of credits
image: `https://api.dicebear.com/7.x/avataaars/svg?seed=${userData.username}` // Random avatar
}
});
console.log(`Created user: ${user.name}`);
createdUsers.push(user);
}
} catch (e) {
console.error(`Error creating user ${userData.name}:`, e.message);
}
}
// 2. Generate Images
console.log("\n🎨 Generating 50 Images...");
let promptIndex = 0;
// Distribute 5 images per user
for (const user of createdUsers) {
if (promptIndex >= PROMPTS.length) break;
const userPrompts = PROMPTS.slice(promptIndex, promptIndex + 5);
promptIndex += 5;
console.log(`\nProcessing ${user.name}...`);
for (const prompt of userPrompts) {
const model = MODELS[Math.floor(Math.random() * MODELS.length)]; // Randomly pick model
const imageUrl = await generateImage(prompt, model);
if (imageUrl) {
await prisma.generation.create({
data: {
prompt: prompt,
model: model,
width: 1024,
height: 1024,
imageUrl: imageUrl,
userId: user.id,
isPublic: true,
createdAt: new Date() // Current time
}
});
console.log(`Saved generation for prompt: "${prompt.slice(0, 20)}..."`);
} else {
console.log(`Skipping DB save due to generation failure for: "${prompt.slice(0, 20)}..."`);
}
// Small delay to be nice to the API
await new Promise(r => setTimeout(r, 1000));
}
}
console.log("\n✅ Seeding Complete!");
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});