Как массово переводить изображения с помощью Google Translate?Javascript

Форум по Javascript
Ответить
Anonymous
 Как массово переводить изображения с помощью Google Translate?

Сообщение Anonymous »

Я хотел получить бесплатный перевод с Google Translate на изображениях.
Это сценарий, который я придумал. Я не рекомендую вставлять сценарии незнакомцев в консоль вашего браузера, прежде чем читать ее и понять. hl = en & tab = tt & sl = auto & tl = en & op = translate
и откройте консоль и пройдя скрипт в.

Код: Выделить всё

(function() {
// Function to click element by XPath
function clickElementByXPath(xpath) {
const element = document.evaluate(
xpath,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;

if (element) {
element.click();
console.log("Element clicked successfully:", xpath);
return true;
} else {
console.error("Element not found with XPath:", xpath);
return false;
}
}

// Function to paste from clipboard
async function pasteFromClipboard() {
try {
await navigator.clipboard.read();
document.execCommand('paste');
console.log("Image pasted successfully");
} catch (err) {
console.error("Failed to paste from clipboard:", err);
}
}

// Function to wait for element to appear
function waitForElement(xpath, timeout = 30000) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const checkElement = () => {
const element = document.evaluate(
xpath,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;

if (element) {
resolve(element);
} else if (Date.now() - startTime > timeout) {
reject(new Error(`Timeout waiting for element: ${xpath}`));
} else {
setTimeout(checkElement, 100);
}
};
checkElement();
});
}

// Function to process a single image
async function processImage(file, index) {
console.log(`Processing file: ${file.name}`);

// Find the drag and drop element
const dragDropElement = document.evaluate(
// @@@ Drag and Drop xPath
'/html/body/c-wiz/div/div[2]/c-wiz/div[5]/c-wiz',
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;

if (dragDropElement) {
// Create a FileList object
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
const fileList = dataTransfer.files;

// Create and dispatch dragenter event
const dragEnterEvent = new DragEvent('dragenter', { bubbles: true });
Object.defineProperty(dragEnterEvent, 'dataTransfer', {value: dataTransfer});
dragDropElement.dispatchEvent(dragEnterEvent);

// Create and dispatch dragover event
const dragOverEvent = new DragEvent('dragover', { bubbles: true });
Object.defineProperty(dragOverEvent, 'dataTransfer', {value: dataTransfer});
dragDropElement.dispatchEvent(dragOverEvent);

// Create and dispatch drop event
const dropEvent = new DragEvent('drop', { bubbles: true });
Object.defineProperty(dropEvent, 'dataTransfer', {value: dataTransfer});
dragDropElement.dispatchEvent(dropEvent);

// Wait for translation to complete
console.log("Waiting for download button...");
// @@@ Download translated image Buttone xPath
await waitForElement("/html/body/c-wiz/div/div[2]/c-wiz/div[5]/c-wiz/div[2]/c-wiz/div/div[1]/div[2]/div[2]/button");
clickElementByXPath("/html/body/c-wiz/div/div[2]/c-wiz/div[5]/c-wiz/div[2]/c-wiz/div/div[1]/div[2]/div[2]/button");

// Wait for download to complete (approximation)
console.log("Waiting for download to complete...");
await new Promise(resolve => setTimeout(resolve, 5000));

// Click the clear button
// @@@ close button xPath
clickElementByXPath("/html/body/c-wiz/div/div[2]/c-wiz/div[5]/c-wiz/div[2]/c-wiz/div/div[1]/div[2]/span[3]/button");

// Wait before next image
await new Promise(resolve =>  setTimeout(resolve, 2000));
console.log(`Finished processing: ${file.name}`);
} else {
console.error("Drag and drop element not found");
}
}

// Function to handle file selection and processing
async function handleFiles(files) {
for (let i = 0; i < files.length; i++) {
try {
const file = files[i];
if (!file.type.startsWith('image/')) {
console.log(`Skipping non-image file: ${file.name}`);
continue;
}
await processImage(file, i);
} catch (error) {
console.error(`Error processing file ${files[i].name}:`, error);
}
}
console.log('All files processed.');
}

// Function to copy image to clipboard with unique identifier
async function copyImageToClipboard(file, index) {
const blob = await file.arrayBuffer().then(buffer => new Blob([buffer], {type: file.type}));

// Create a new filename with a unique identifier
const fileExtension = file.name.split('.').pop();
const newFileName = `image_${index + 1}_${Date.now()}.${fileExtension}`;

// Create a new File object with the unique name
const newFile = new File([blob], newFileName, {type: file.type});

const item = new ClipboardItem({ [file.type]: newFile });
await navigator.clipboard.write([item]);
console.log(`Image ${newFileName} copied to clipboard`);
}

// Function to trigger file selection
function triggerFileSelection() {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.multiple = true;
fileInput.accept = 'image/*';
fileInput.style.display = 'none';
document.body.appendChild(fileInput);

fileInput.addEventListener('change', function(event) {
const files = event.target.files;
if (files.length > 0) {
handleFiles(files);
} else {
console.log('No files selected.');
}
document.body.removeChild(fileInput);
});

fileInput.click();
}

// Create a button to trigger the file selection
const selectButton = document.createElement('button');
selectButton.textContent = 'Select Images';
selectButton.style.position = 'fixed';
selectButton.style.top = '10px';
selectButton.style.left = '10px';
selectButton.style.zIndex = '1000';
document.body.appendChild(selectButton);

selectButton.addEventListener('click', triggerFileSelection);

console.log('Script injected. Click the "Select Images" button to start.');
})();
Сценарий может сломаться в любой точке, скорее всего, xpaths изменяются.

Подробнее здесь: https://stackoverflow.com/questions/794 ... -translate
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»