Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

I have the following ExtendScript: // Polyfill for String.trim() in ExtendScript if…

  1. User

    I have the following ExtendScript:

    // Polyfill for String.trim() in ExtendScript if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; }

    // ExtendScript for After Effects

    // Begin undo group for script actions app.beginUndoGroup("Create SubRip Comps");

    // ... rest of your script ...

    // Prompt user to select a SubRip (.srt) file var srtFile = File.openDialog("Select a SubRip (.srt) file"); if (srtFile != null) { srtFile.open("r"); var srtContent = srtFile.read(); srtFile.close();

    // Parse the SubRip file content
    var entries = parseSRT(srtContent);
    
    if (entries.length > 0) {
        // Create a main composition to hold all subtitle comps
        var mainCompName = "Subtitles_Comp";
        var mainCompDuration = entries[entries.length - 1].endTime;
        var mainCompWidth = 1920;
        var mainCompHeight = 1080;
        var mainCompPixelAspect = 1.0;
        var mainCompFrameRate = 30; // Adjust as needed
    
        var mainComp = app.project.items.addComp(
            mainCompName,
            mainCompWidth,
            mainCompHeight,
            mainCompPixelAspect,
            mainCompDuration,
            mainCompFrameRate
        );
    
        // Locate the existing "WHITEBACKGROUND" composition in the project
        var whiteBG = findCompByName("WHITEBACKGROUND");
        if (whiteBG == null) {
            alert('The "WHITEBACKGROUND" composition was not found in the project.');
        }
    
        // Process each subtitle entry
        for (var i = 0; i < entries.length; i++) {
            var entry = entries[i];
    
            // Remove "{txt}" from the text for naming
            var cleanText = entry.text.replace("{txt}", "").trim();
    
            // Create a new composition for each subtitle
            var subtitleComp = app.project.items.addComp(
                cleanText,
                mainCompWidth,
                mainCompHeight,
                mainCompPixelAspect,
                entry.duration,
                mainCompFrameRate
            );
    
            // Add the text layer
            var textLayer = subtitleComp.layers.addText(cleanText);
            var textProp = textLayer.property("Source Text");
            var textDocument = textProp.value;
    
            // Check for "{txt}" to set specific text properties
            if (entry.text.indexOf("{txt}") !== -1) {
                textDocument.font = "MxPlus_IBM_XGA-AI_12x20"; // Use the correct font name
                textDocument.fontSize = 45;
                textDocument.leading = 54;
                textDocument.fillColor = hexToRgb("#24254D");
                textDocument.tracking = 0;
                textDocument.justification = ParagraphJustification.LEFT_JUSTIFY;
            }
    
            textProp.setValue(textDocument);
            textLayer.property("Position").setValue([623, 706]);
    
            // Add the "WHITEBACKGROUND" precomp beneath the text layer
            if (whiteBG != null) {
                var bgLayer = subtitleComp.layers.add(whiteBG);
                bgLayer.moveBefore(textLayer);
            }
    
            // Place the subtitle comp into the main comp at the correct time
            var compLayer = mainComp.layers.add(subtitleComp);
            compLayer.startTime = entry.startTime;
            // No need to set inPoint and outPoint
        }
    } else {
        alert("No valid entries found in the SubRip file.");
    }
    

    }

    // End undo group app.endUndoGroup();

    // Function to parse SRT content into entries function parseSRT(data) { var regex = /(\d+)\s+([\d:,]+)\s+-->\s+([\d:,]+)\s+([\s\S]*?)(?=\n{2,}|$)/g; var entries = []; var match;

    while ((match = regex.exec(data)) !== null) {
        var index = parseInt(match[1], 10);
        var startTime = timeToSeconds(match[2]);
        var endTime = timeToSeconds(match[3]);
        var text = match[4].replace(/\r\n|\r|\n/g, "\n").trim();
    
        entries.push({
            index: index,
            startTime: startTime,
            endTime: endTime,
            duration: endTime - startTime,
            text: text
        });
    }
    
    return entries;
    

    }

    // Convert time in "HH:MM:SS,ms" to seconds function timeToSeconds(t) { var parts = t.split(','); var timeParts = parts[0].split(':'); var hours = parseFloat(timeParts[0]); var minutes = parseFloat(timeParts[1]); var seconds = parseFloat(timeParts[2]); var milliseconds = parseFloat(parts[1]) / 1000;

    return hours * 3600 + minutes * 60 + seconds + milliseconds;
    

    }

    // Convert hex color to RGB array (values between 0 and 1) function hexToRgb(hex) { var bigint = parseInt(hex.replace("#", ""), 16); var r = ((bigint >> 16) & 255) / 255; var g = ((bigint >> 8) & 255) / 255; var b = (bigint & 255) / 255; return [r, g, b]; }

    // Find a composition item by name in the project panel function findCompByName(name) { for (var i = 1; i <= app.project.numItems; i++) { if (app.project.item(i) instanceof CompItem && app.project.item(i).name === name) { return app.project.item(i); } } return null; }

    There are two problems:

    1. WHITEBACKGROUND is overlaid on top of the text layer, put it at the bottom

    2. It still is not adding the comp into the main comp, which is "FULL1-FIRSTHOUR" if a subtitle has a timeframe of "00:01:43,333 --> 00:01:44,466", then that means after effects will place the comp into the project's 00:01:43,333.

  2. Assistant

    To address the two issues you've encountered in your ExtendScript for After Effects, we'll make some adjustments to your script:

    1. WHITEBACKGROUND Layer Order: Currently, the WHITEBACKGROUND layer is appearing above the text layer, which obscures the text. This happens because of the order in which layers are added to a composition in After Effects—the topmost layer in the timeline panel appears in front of lower layers in the composition panel.

    2. Adding Subtitle Comps to "FULL1-FIRSTHOUR": Instead of creating a new main composition called Subtitles_Comp, you want to place the subtitle comps directly into the existing FULL1-FIRSTHOUR composition at the correct timestamps.

    Below is the updated script with the necessary modifications to resolve both issues:

    // Polyfill for String.trim() in ExtendScript
    if (typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }
    
    // ExtendScript for After Effects
    
    // Begin undo group for script actions
    app.beginUndoGroup("Create SubRip Comps");
    
    // ... rest of your script ...
    
    // Prompt user to select a SubRip (.srt) file
    var srtFile = File.openDialog("Select a SubRip (.srt) file");
    if (srtFile != null) {
        srtFile.open("r");
        var srtContent = srtFile.read();
        srtFile.close();
    
        // Parse the SubRip file content
        var entries = parseSRT(srtContent);
    
        if (entries.length > 0) {
            // **Find the existing "FULL1-FIRSTHOUR" composition in the project**
            var mainCompName = "FULL1-FIRSTHOUR";
            var mainComp = findCompByName(mainCompName);
    
            if (mainComp == null) {
                alert('The "' + mainCompName + '" composition was not found in the project.');
            } else {
                // Optionally adjust the mainComp's duration if needed
                var mainCompDuration = Math.max(mainComp.duration, entries[entries.length - 1].endTime);
                if (mainComp.duration < mainCompDuration) {
                    mainComp.duration = mainCompDuration;
                }
    
                var mainCompWidth = mainComp.width;
                var mainCompHeight = mainComp.height;
                var mainCompPixelAspect = mainComp.pixelAspect;
                var mainCompFrameRate = mainComp.frameRate;
    
                // Locate the existing "WHITEBACKGROUND" composition in the project
                var whiteBG = findCompByName("WHITEBACKGROUND");
                if (whiteBG == null) {
                    alert('The "WHITEBACKGROUND" composition was not found in the project.');
                }
    
                // Process each subtitle entry
                for (var i = 0; i < entries.length; i++) {
                    var entry = entries[i];
    
                    // Remove "{txt}" from the text for naming
                    var cleanText = entry.text.replace("{txt}", "").trim();
    
                    // Create a new composition for each subtitle
                    var subtitleComp = app.project.items.addComp(
                        cleanText,
                        mainCompWidth,
                        mainCompHeight,
                        mainCompPixelAspect,
                        entry.duration,
                        mainCompFrameRate
                    );
    
                    // **Add the "WHITEBACKGROUND" precomp first**
                    if (whiteBG != null) {
                        var bgLayer = subtitleComp.layers.add(whiteBG);
                        // Position or scale bgLayer if needed
                    }
    
                    // **Add the text layer after the background layer so it appears on top**
                    var textLayer = subtitleComp.layers.addText(cleanText);
                    var textProp = textLayer.property("Source Text");
                    var textDocument = textProp.value;
    
                    // Check for "{txt}" to set specific text properties
                    if (entry.text.indexOf("{txt}") !== -1) {
                        textDocument.font = "MxPlus_IBM_XGA-AI_12x20"; // Use the correct font name
                        textDocument.fontSize = 45;
                        textDocument.leading = 54;
                        textDocument.fillColor = hexToRgb("#24254D");
                        textDocument.tracking = 0;
                        textDocument.justification = ParagraphJustification.LEFT_JUSTIFY;
                    }
    
                    textProp.setValue(textDocument);
                    textLayer.property("Position").setValue([623, 706]);
    
                    // Place the subtitle comp into the main comp at the correct time
                    var compLayer = mainComp.layers.add(subtitleComp);
                    compLayer.startTime = entry.startTime;
                    // No need to set inPoint and outPoint; it will inherit from the comp's duration
                }
            }
        } else {
            alert("No valid entries found in the SubRip file.");
        }
    }
    
    // End undo group
    app.endUndoGroup();
    
    // Function to parse SRT content into entries
    function parseSRT(data) {
        var regex = /(\d+)\s+([\d:,]+)\s+-->\s+([\d:,]+)\s+([\s\S]*?)(?=\n{2,}|$)/g;
        var entries = [];
        var match;
    
        while ((match = regex.exec(data)) !== null) {
            var index = parseInt(match[1], 10);
            var startTime = timeToSeconds(match[2]);
            var endTime = timeToSeconds(match[3]);
            var text = match[4].replace(/\r\n|\r|\n/g, "\n").trim();
    
            entries.push({
                index: index,
                startTime: startTime,
                endTime: endTime,
                duration: endTime - startTime,
                text: text
            });
        }
    
        return entries;
    }
    
    // Convert time in "HH:MM:SS,ms" to seconds
    function timeToSeconds(t) {
        var parts = t.split(',');
        var timeParts = parts[0].split(':');
        var hours = parseFloat(timeParts[0]);
        var minutes = parseFloat(timeParts[1]);
        var seconds = parseFloat(timeParts[2]);
        var milliseconds = parseFloat(parts[1]) / 1000;
    
        return hours * 3600 + minutes * 60 + seconds + milliseconds;
    }
    
    // Convert hex color to RGB array (values between 0 and 1)
    function hexToRgb(hex) {
        var bigint = parseInt(hex.replace("#", ""), 16);
        var r = ((bigint >> 16) & 255) / 255;
        var g = ((bigint >> 8) & 255) / 255;
        var b = (bigint & 255) / 255;
        return [r, g, b];
    }
    
    // Find a composition item by name in the project panel
    function findCompByName(name) {
        for (var i = 1; i <= app.project.numItems; i++) {
            if (app.project.item(i) instanceof CompItem && app.project.item(i).name === name) {
                return app.project.item(i);
            }
        }
        return null;
    }
    

    Explanation of Changes:

    1. Adjusting Layer Order for WHITEBACKGROUND

    In After Effects, layers at the top of the layer stack appear in front of layers below them. In your original script, you first added the text layer and then added the WHITEBACKGROUND layer:

    // Original code snippet
    // Add the text layer
    var textLayer = subtitleComp.layers.addText(cleanText);
    
    // Add the "WHITEBACKGROUND" precomp beneath the text layer
    if (whiteBG != null) {
        var bgLayer = subtitleComp.layers.add(whiteBG);
        bgLayer.moveBefore(textLayer);
    }
    

    Even though you moved the bgLayer before the textLayer, After Effects still renders layers from top to bottom, so the bgLayer ends up being below the textLayer in the layer stack but rendered behind it visually.

    To fix this, we adjust the code to add the bgLayer first and then add the textLayer:

    // Adjusted code snippet
    // Add the "WHITEBACKGROUND" precomp first
    if (whiteBG != null) {
        var bgLayer = subtitleComp.layers.add(whiteBG);
        // Position or scale bgLayer if needed
    }
    
    // Add the text layer after the background layer so it appears on top
    var textLayer = subtitleComp.layers.addText(cleanText);
    

    By adding the background layer first and then the text layer, the text layer will naturally be on top of the background layer in the layer stack, and thus rendered in front.

    2. Adding Subtitle Comps to "FULL1-FIRSTHOUR"

    In your original script, you created a new composition named Subtitles_Comp and added the subtitle comps to this new comp:

    // Original code snippet
    // Create a main composition to hold all subtitle comps
    var mainCompName = "Subtitles_Comp";
    var mainCompDuration = entries[entries.length - 1].endTime;
    // ... rest of comp creation code ...
    

    Instead, we need to find the existing FULL1-FIRSTHOUR composition and use it as the mainComp. Modify your script to use the findCompByName function to locate the existing comp:

    // Modified code snippet
    // Find the existing "FULL1-FIRSTHOUR" composition in the project
    var mainCompName = "FULL1-FIRSTHOUR";
    var mainComp = findCompByName(mainCompName);
    
    if (mainComp == null) {
        alert('The "' + mainCompName + '" composition was not found in the project.');
    } else {
        // Proceed with adding subtitle comps to mainComp
        // Adjust the mainCompDuration if necessary
    }
    

    By doing this, your script now adds the subtitle comps directly into the FULL1-FIRSTHOUR composition at the correct timestamps based on the SRT file.

    Additional Considerations:

    • Adjusting Main Composition Duration: If your subtitles extend beyond the current duration of FULL1-FIRSTHOUR, you might need to adjust the composition's duration to accommodate all subtitles.

      var mainCompDuration = Math.max(mainComp.duration, entries[entries.length - 1].endTime);
      if (mainComp.duration < mainCompDuration) {
          mainComp.duration = mainCompDuration;
      }
      
    • Positioning and Scaling Layers: Ensure that your WHITEBACKGROUND layer and text layers are correctly positioned and scaled within the subtitle composition. You may need to adjust their positions or apply transforms to get the desired appearance.

    • Font Availability: The font "MxPlus_IBM_XGA-AI_12x20" must be installed on your system for After Effects to use it. If it's not installed, After Effects will substitute it with a default font.

    • Error Handling: The script now includes alerts if the WHITEBACKGROUND or FULL1-FIRSTHOUR comps are not found, which helps in debugging if something is missing in the project.

    By making these changes, your script should now:

    • Properly layer the WHITEBACKGROUND beneath the text layer in each subtitle comp.
    • Add the subtitle comps into the FULL1-FIRSTHOUR composition at the correct times corresponding to the timestamps in your SRT file.

    Feel free to adjust the script further to suit any additional requirements or to fine-tune the subtitle appearance.