Action

translate

Posted by tsmith, Last update 3 days ago

This action translates selected text between English (EN) and French (FR), auto-detecting the source language.

The translation is appended below the original text in the editor. Additionally, all translations are logged in a dedicated “Translation Log” draft, which includes:

  1. A timestamp (yyyymmdd-hhmm format) for each translation.
  2. The original text and its translated version, with language abbreviations (EN or FR).
  3. A structured and readable format for easy reference.

This action streamlines translations and keeps a record for future use.

Steps

  • script

    let f = async () => {
        // Get the selected text
        const [st, len] = editor.getSelectedRange();
        const selection = editor.getSelectedText().trim();
    
        if (!selection || selection.length === 0) {
            alert("No text selected for translation.");
            return false;
        }
    
        // Build a prompt for language detection
        const detectPrompt = `Identify whether this text is in English or French: "${selection}"`;
    
        // Create OpenAI API object and use for language detection
        let ai = new OpenAI();
        let detectedLanguage = await ai.quickChatResponse(detectPrompt);
    
        if (!detectedLanguage || detectedLanguage.trim().length === 0) {
            alert("Unable to detect the language.");
            return false;
        }
    
        // Determine target language based on detection
        detectedLanguage = detectedLanguage.toLowerCase();
        let targetLanguage = "French";
        if (detectedLanguage.includes("french")) {
            targetLanguage = "English";
        }
    
        // Build a prompt for translation
        const translatePrompt = `Translate the following text into ${targetLanguage}: "${selection}"`;
    
        // Get translation
        let translation = await ai.quickChatResponse(translatePrompt);
    
        if (translation && translation.trim().length > 0) {
            translation = translation.trim().replace(/^"+|"+$/g, '');
    
            // Append translation below the selected text
            const updatedText = `${selection}\n${translation}\n`;
            editor.setSelectedText(updatedText);
            editor.setSelectedRange(st, updatedText.length);
    
            // Log the translation
            logTranslation(selection, translation, targetLanguage);
    
            return true;
        } else {
            alert("Unable to retrieve translation.");
            return false;
        }
    };
    
    function logTranslation(original, translated, targetLanguage) {
        const logTitle = "Translation Log";
    
        // Find or create the log draft
        let logDraft = Draft.query(logTitle, "all").find(d => d.title === logTitle);
        if (!logDraft) {
            logDraft = Draft.create();
            logDraft.title = logTitle;
            logDraft.content = `${logTitle}\n\n`;
            logDraft.addTag("log");
            logDraft.update();
        }
    
        // Get current date/time
        let now = new Date();
        let formattedDate = now.toISOString().slice(0, 10).replace(/-/g, "");
        let formattedTime = now.toTimeString().slice(0, 5).replace(":", "");
        let timestamp = `${formattedDate}-${formattedTime}`;
    
        // Language abbreviations
        const languageMap = { French: "FR", English: "EN" };
        const originalLanguage = targetLanguage === "French" ? "EN" : "FR";
        const targetAbbr = languageMap[targetLanguage];
    
        // Build formatted log entry
        let logEntry = `**${timestamp}**\n*Original (${originalLanguage})*: ${original}\n*Translated (${targetAbbr})*: ${translated}\n---\n`;
    
        // Ensure title stays at the top
        let logBody = logDraft.content.split("\n\n").slice(1).join("\n\n");
        logDraft.content = `${logTitle}\n\n${logEntry}${logBody}`.trim();
        logDraft.update();
    
        console.log("Translation logged successfully.");
    }
    
    // Run the function
    (async () => {
        if (!await f()) {
            context.cancel();
        }
    })();
    

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.