Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <p class="help">
  <i>**Will need to enable Chrome flags, Chrome canary recommended.</i>
</p>
<h2>Prompt AI API & Summarize AI API</h2>
<p>Output:</p>
<div id="output">
</div>
<div class="controls">
  <input type="button" id ="prompt" value="1. Write a Poem" />
  <input type="button" id ="summarize" value="2. Summarize" />
</div>

<details>
  <summary>A made up Harry Potter excerpt</summary>
  <p id="sample">

The Transfiguration classroom fell silent when Neville Longbottom's experimental spell went terribly wrong. What began as an attempt to transform his textbook into a singing teapot instead caused every piece of furniture in the room to sprout legs and begin a chaotic dance.

Desks waltzing with chairs, inkwells spinning like ballerinas, and quills doing a jig across Professor McGonagall's meticulously organized desk. The room became a whirling carnival of enchanted objects, with McGonagall's normally stern expression transforming into a mix of shock and barely contained exasperation.

Hermione, ever the problem-solver, began muttering counterspells while Harry and Ron ducked to avoid a particularly enthusiastic pirouetting table. Draco Malfoy, caught in the center of the madness, shrieked as a chair attempted to use him as a dancing partner.

"Finite Incantatem!" McGonagall finally bellowed, her voice cutting through the musical mayhem. The objects froze mid-twirl, then crashed to the ground with a spectacular cacophony of thuds and clatters.

Neville turned five shades of red, apologetic and mortified. "Sorry, Professor," he mumbled, as a lone teacup lid spun defiantly on the floor.</p>
</details>

<h2>Language Detetction API</h2>
<div class="language-translation">
  <textarea id="input-text"></textarea>
  <input type="button" id ="detect" value="3. Detect" />
  <p>The Language detected is <span id="language">___</span> with Confidence <span id="confidence">___</span></p>
</div>
              
            
!

CSS

              
                * {
  font-family: Verdana;
}
.help {
  color: #aaa;
}
#output {
  background: antiquewhite;
    border: 2px dashed #aaa;
    border-radius: 8px;
    padding: 20px;
}

.controls {
  margin: 30px 0;
}

#language, #confidence {
  font-weight: bold;
  color: blueviolet;
}

#detect {
  display: block;
}
              
            
!

JS

              
                (async () => {
      // Define an asynchronous function to write a poem
      const writePoem = async () => {
        try {
          // Check if the language model capabilities are available
          const { available, defaultTemperature, defaultTopK, maxTopK } = await ai.languageModel.capabilities();

          // console.log ((await ai.languageModel.capabilities()).available);

          if (available !== "no") {
            // Create a session for the language model
            const session = await ai.languageModel.create();

            // Prompt the model and wait for the result
            document.getElementById("output").innerHTML = "Generating....";
            const result = await session.prompt("Write me a poem");

            if (result) {
              // Display the result in the output element
              document.getElementById("output").innerHTML = result;
            } else {
              console.log("No result received from the language model.");
            }
          } else {
            console.log("Language model is not available.");
          }
        } catch (error) {
          console.error("An error occurred:", error);
        }
      };

      // Define an asynchronous function to summarize text
      const summarize = async () => {
        try {
          // Check the summarizer's capabilities
          const canSummarize = await ai.summarizer.capabilities();
          let summarizer;

          // Check if the summarizer is available
          if (canSummarize && canSummarize.available !== 'no') {
            if (canSummarize.available === 'readily') {
              // If the summarizer is readily available, create an instance immediately
              summarizer = await ai.summarizer.create();
            } else {
              // If the summarizer requires a model download, create an instance and track download progress
              summarizer = await ai.summarizer.create();

              // // Add an event listener to monitor download progress
              // summarizer.addEventListener('downloadprogress', (e) => {
              //   console.log(`Download progress: ${e.loaded}/${e.total}`);
              // });

              // Wait for the summarizer to be ready after the download is complete
              await summarizer.ready;
            }
          } else {
            // Log a message if the summarizer is not available
            console.log("The summarizer is not available for use.");
          }

          // Get the text to summarize
          const someUserText = document.getElementById("sample").innerHTML;

          document.getElementById("output").innerHTML = "Summarizing....";
          const result = await summarizer.summarize(someUserText);
          document.getElementById("output").innerHTML = result;

        } catch (error) {
          // Handle and log any errors that occur
          console.error("An error occurred:", error);
        }
      };

      const languageDetection = async () => {
        try {
          // Check the language detection capabilities
          const canDetect = await translation.canDetect();
          console.log("Language detection capability:", canDetect);
          let detector;

          if (canDetect === "no") {
            // The language detector isn't usable.
            console.log("Language detector is not available.");
            return;
          }

          if (canDetect === "readily") {
            // The language detector can immediately be used.
            detector = await translation.createDetector();
            // detector = new i18nextBrowserLanguageDetector();
            console.log(detector);
          } else {
            // The language detector can be used after model download.
            detector = await translation.createDetector();
            detector.addEventListener("downloadprogress", (e) => {
              console.log(`Download progress: ${e.loaded}/${e.total}`);
            });
            await detector.ready; // Ensure the detector is ready
          }

          // Retrieve user text safely
          const userText = document.getElementById("input-text")?.value || "";
          if (!userText.trim()) {
            console.error("No input text found for detection.");
            return;
          }

          console.log("Input text:", userText);

          const detectionOutput = await detector.detect(userText);
          console.log("Hello");

          if (detectionOutput.length > 0) {
            const { detectedLanguage, confidence } = detectionOutput[0];
            document.getElementById("language").innerHTML = detectedLanguage;
            document.getElementById("confidence").innerHTML = `${(confidence * 100).toFixed(1)}%`;
            console.log("Detected Language:", detectedLanguage);
            console.log("Confidence:", confidence);
          } else {
            console.warn("No language detected.");
          }

          console.log("Language detection completed.");
        } catch (error) {
          // Handle and log any errors that occur
          console.error("An error occurred:", error);
        }
      };

// Global error handling
window.addEventListener('error', (event) => {
  console.error('Global error caught:', event.error);
});

window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled promise rejection:', event.reason);
});

// Trigger function with additional error catching
try {
  languageDetection().catch(promiseError => {
    console.error('Promise-level error:', promiseError);
  });
} catch (syncError) {
  console.error('Synchronous error in function call:', syncError);
}  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

      // Attach the click event listener to the prompt button
      const promptButton = document.getElementById("prompt");
      if (promptButton) {
        promptButton.addEventListener("click", writePoem);
      } else {
        console.error("Prompt button element not found.");
      }

      // Attach the click event listener to the Summarize button
      const summarizeButton = document.getElementById("summarize");
      if (summarizeButton) {
        summarizeButton.addEventListener("click", summarize);
      } else {
        console.error("summarize button element not found.");
      }

      // Attach the language detection API to click for detect button.
      const detectButton = document.getElementById("detect");
      // console.log(detectButton);
      if (detectButton) {
        detectButton.addEventListener("click", languageDetection);
      } else {
        console.error("language detetction element not found.");
      }

    })();
              
            
!
999px

Console