Write a node.js dataset downloader for e621.net. Firstly it will ask the user for tags and download destination, then it will calculate total amount of media with tags and ask the user the amount he wants to download(or "all"). Then it will create a folder in download destination named after the tags and download all media here.
Assistant
Certainly! Below is a Node.js script that serves as a dataset downloader for e621.net. The script performs the following steps:
Prompts the user for their e621 username, API key, desired tags, and download destination.
Calculates the total number of media files matching the specified tags.
Asks the user how many files they wish to download (or "all").
Creates a folder in the specified destination named after the tags.
Downloads the media files into the created folder.
Please note: To use the e621 API, you need to have an account and generate an API key. This is required due to the site's policies. Make sure to use your own credentials and adhere to e621's terms of service.
Script: e621_downloader.js
javascript
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
/**
* Prompts the user for input.
* @param {string} question - The question to display to the user.
* @returns {Promise<string>} - The user's input.
*/
function getUserInput(question) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return new Promise(resolve => {
rl.question(question, (input) => {
rl.close();
resolve(input.trim());
});
});
}
/**
* Retrieves the total number of posts matching the tags.
* @param {string} tags - The tags to search for.
* @param {string} username - e621 username.
* @param {string} apiKey - e621 API key.
* @returns {Promise<number>} - Total number of posts.
*/
async function getPostCount(tags, username, apiKey) {
try {
const response = await axios.get('https://e621.net/posts.json', {
params: {
tags: tags,
limit: 0 // We can set limit to 0 to only get the count
},
auth: {
username: username,
password: apiKey
},
headers: {
'User-Agent': `e621Downloader/1.0 (by ${username} on e621)`
}
});
const totalPosts = response.data.total_posts;
return totalPosts;
} catch (error) {
console.error('Error fetching post count:', error.response ? error.response.data : error.message);
return null;
}
}
/**
* Downloads the specified number of posts with the given tags.
* @param {string} tags - Tags for searching posts.
* @param {number} limit - Number of posts to download.
* @param {string} destination - Destination folder path.
* @param {string} username - e621 username.
* @param {string} apiKey - e621 API key.
*/
async function downloadPosts(tags, limit, destination, username, apiKey) {
let page = 1;
let downloaded = 0;
while (downloaded < limit) {
const remaining = limit - downloaded;
const batchSize = remaining > 320 ? 320 : remaining; // e621 limit per request
try {
const response = await axios.get('https://e621.net/posts.json', {
params: {
tags: tags,
limit: batchSize,
page: page
},
auth: {
username: username,
password: apiKey
},
headers: {
'User-Agent': `e621Downloader/1.0 (by ${username} on e621)`
}
});
const posts = response.data.posts;
if (posts.length === 0) {
console.log('No more posts found.');
break;
}
for (let post of posts) {
const fileUrl = post.file.url;
if (!fileUrl) continue; // Skip if file URL is not available
const filename = path.basename(fileUrl);
const filePath = path.join(destination, filename);
// Check if file already exists
if (fs.existsSync(filePath)) {
console.log(`${filename} already exists, skipping.`);
continue;
}
// Download the file
try {
const fileResponse = await axios.get(fileUrl, {
responseType: 'stream',
headers: {
'User-Agent': `e621Downloader/1.0 (by ${username} on e621)`
}
});
const writer = fs.createWriteStream(filePath);
fileResponse.data.pipe(writer);
await new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
console.log(`Downloaded ${filename}`);
} catch (error) {
console.error(`Failed to download ${fileUrl}`, error.message);
}
downloaded++;
if (downloaded >= limit) {
break;
}
}
page++;
} catch (error) {
console.error('Error fetching posts:', error.response ? error.response.data : error.message);
break;
}
}
}
/**
* Main function to run the script.
*/
async function main() {
try {
// Prompt user for e621 credentials and download preferences
const username = await getUserInput('Enter your e621 username: ');
const apiKey = await getUserInput('Enter your e621 API key: ');
const tags = await getUserInput('Enter tags (space-separated): ');
const destination = await getUserInput('Enter download destination folder: ');
// Create folder named after the tags
const tagsFolderName = tags.replace(/\s+/g, '_');
const downloadFolder = path.join(destination, tagsFolderName);
if (!fs.existsSync(downloadFolder)) {
fs.mkdirSync(downloadFolder, { recursive: true });
console.log(`Created folder: ${downloadFolder}`);
} else {
console.log(`Folder already exists: ${downloadFolder}`);
}
// Get total amount of media with tags
const totalPosts = await getPostCount(tags, username, apiKey);
if (totalPosts === null) {
console.error('Failed to get total posts count.');
return;
}
console.log(`Total posts found: ${totalPosts}`);
// Ask user for the number of posts to download
let amountInput = await getUserInput('Enter the amount you want to download (or "all"): ');
let amount;
if (amountInput.toLowerCase() === 'all') {
amount = totalPosts;
} else {
amount = parseInt(amountInput);
if (isNaN(amount) || amount <= 0) {
console.error('Invalid amount entered.');
return;
}
if (amount > totalPosts) {
amount = totalPosts;
console.log(`Only ${totalPosts} posts available. Adjusted download amount to ${amount}.`);
}
}
// Start downloading
console.log(`Starting download of ${amount} posts...`);
await downloadPosts(tags, amount, downloadFolder, username, apiKey);
console.log('Download completed.');
} catch (error) {
console.error('An error occurred:', error.message);
}
}
main();
Instructions to Run the Script
Install Node.js: Ensure you have Node.js installed on your system. You can download it from nodejs.org.
Save the Script: Copy the script above and save it as e621_downloader.js in a directory of your choice.
Install Required Packages:
Open your terminal or command prompt, navigate to the directory where you saved the script, and run:
bash
npm install axios
This installs the axios package needed for HTTP requests.
Run the Script:
In the terminal, run:
bash
node e621_downloader.js
Follow the Prompts:
Enter your e621 username: This is your account username on e621.net.
Enter your e621 API key: You can find or generate your API key in your e621 account settings.
Enter tags: Input the tags you're interested in, separated by spaces (e.g., dragon solo rating:s).
Enter download destination folder: Provide the path to the folder where you want to save the downloads (e.g., C:\Users\YourName\Downloads or /home/yourname/Downloads).
Wait for Download Completion:
The script will display progress messages as it downloads each file. Once completed, you'll find all the media files in the created folder named after your tags.
Important Notes
Authentication: e621 requires authentication for API access. Always keep your API key secure and do not share it publicly.
Rate Limits: Be mindful of e621's API rate limits. Excessive requests may lead to your IP being temporarily banned.
Content Warning: e621 contains content that may be NSFW (Not Safe for Work). Ensure that you're compliant with all local laws and regulations regarding the material you download.
Error Handling: The script includes basic error handling. If you encounter issues, check the error messages for guidance.
Customization
User-Agent: If you plan to distribute this script or run it frequently, consider customizing the User-Agent string to include proper contact information.
Batch Size: The script fetches posts in batches, respecting e621's limit per request. Adjustments can be made to the batchSize variable if needed.
File Overwrite: The script checks if a file already exists before downloading to prevent duplicates.
I hope this helps you download the dataset you're interested in! If you have any questions or need further assistance, feel free to ask.