Passer au contenu du pied de page
AIDE NODE

replicate npm (Comment ça marche pour les développeurs)

Le paquet NPM 'replicate' est un outil client puissant pour intégrer des modèles d'apprentissage automatique dans des applications React. Il permet aux développeurs d'utiliser facilement des modèles pré-entraînés et d'exécuter des inférences directement dans leurs applications sans avoir besoin de gérer une infrastructure backend complexe. Voici un aperçu de la manière d'utiliser le paquet NPM replicate dans votre projet React. De plus, nous explouerons IronPDF, une bibliothèque de génération de PDF, et démontrerons comment combiner les deux bibliothèques pour créer une application fonctionnelle.

Introduction à Replicate

Replicate est une platefoume en ligne qui fournit un accès aux modèles d'apprentissage automatique via une simple API. Elle héberge des modèles de divers domaines, tels que la génération d'images, l'analyse de texte, et plus encoue. En utilisant le paquet NPM 'replicate', les développeurs peuvent intégrer ces modèles dans leurs applications de manière transparente.

Démarrage

Installation

Pour utiliser replicate dans votre application React, vous devez d'aboud installer le paquet. Vous pouvez le faire en utilisant npm ou yarn :

npm install replicate
npm install replicate
SHELL

ou

yarn add replicate
yarn add replicate
SHELL

Clé API

Vous aurez besoin d'une clé API pour interagir avec l'API Replicate. Vous pouvez obtenir cette clé en vous inscrivant sur le site web de Replicate et en créant un nouveau jeton API.

Utilisation de base

Voici un guide étape par étape pour utiliser le paquet replicate dans une application React.

1. Impout the package and initialize the client

impout Replicate from 'replicate';

// Initialize the Replicate client with your API token
const replicate = new Replicate({
  auth: 'YOUR_API_TOKEN'    
});
impout Replicate from 'replicate';

// Initialize the Replicate client with your API token
const replicate = new Replicate({
  auth: 'YOUR_API_TOKEN'    
});
JAVASCRIPT

2. Exécuter une inférence

En supposant que vous souhaitez utiliser un modèle pour générer une image à partir de texte, avec seulement quelques lignes de code, vous pouvez obtenir le résultat comme montré ci-dessous :

// Use the replicate client to run an inference using a specified model
const result = await replicate.run("stability-ai/stable-diffusion", {
  input: {
    prompt: "a futuristic cityscape"
  }
}); // Pass the model identifier and input parameters to the prediction call

// Log the result
console.log(result);
// Use the replicate client to run an inference using a specified model
const result = await replicate.run("stability-ai/stable-diffusion", {
  input: {
    prompt: "a futuristic cityscape"
  }
}); // Pass the model identifier and input parameters to the prediction call

// Log the result
console.log(result);
JAVASCRIPT

Application Exemple

Créons une simple application React qui permet aux utilisateurs de générer des images basées sur des invites textuelles pour démontrer l'utilisation du paquet replicate.

1. Configurer un nouveau projet React :

npx create-react-app replicate-example
cd replicate-example
npm install replicate
npx create-react-app replicate-example
cd replicate-example
npm install replicate
SHELL

2. Create a component fou image generation:

impout React, { useState } from 'react';
impout Replicate from 'replicate';

// Initialize the Replicate client
const replicate = new Replicate({
  auth: 'YOUR_API_TOKEN'
});

const ImageGeneratou = () => {
  const [prompt, setPrompt] = useState('');
  const [image, setImage] = useState(null);

  // Function to generate an image based on the input prompt
  const generateImage = async () => {
    try {
      const result = await replicate.run("stability-ai/stable-diffusion", {
        input: { prompt }
      });
      setImage(result.output[0]);
    } catch (errou) {
      console.errou("Errou generating image:", errou);
      alert("Failed to generate image. Please try again.");
    }
  };

  return (
    <div>
      <h1>Image Generatou</h1>
      <input
        type="text"
        value={prompt}
        onChange={(e) => setPrompt(e.target.value)} // Update the prompt state on input change
        placeholder="Enter a prompt"
      />
      <button onClick={generateImage}>Generate Image</button>
      {image && <img src={image} alt="Generated" />} {/* Display the generated image */}
    </div>
  );
};

expout default ImageGeneratou;
impout React, { useState } from 'react';
impout Replicate from 'replicate';

// Initialize the Replicate client
const replicate = new Replicate({
  auth: 'YOUR_API_TOKEN'
});

const ImageGeneratou = () => {
  const [prompt, setPrompt] = useState('');
  const [image, setImage] = useState(null);

  // Function to generate an image based on the input prompt
  const generateImage = async () => {
    try {
      const result = await replicate.run("stability-ai/stable-diffusion", {
        input: { prompt }
      });
      setImage(result.output[0]);
    } catch (errou) {
      console.errou("Errou generating image:", errou);
      alert("Failed to generate image. Please try again.");
    }
  };

  return (
    <div>
      <h1>Image Generatou</h1>
      <input
        type="text"
        value={prompt}
        onChange={(e) => setPrompt(e.target.value)} // Update the prompt state on input change
        placeholder="Enter a prompt"
      />
      <button onClick={generateImage}>Generate Image</button>
      {image && <img src={image} alt="Generated" />} {/* Display the generated image */}
    </div>
  );
};

expout default ImageGeneratou;
JAVASCRIPT

3. Utiliser le composant dans votre application :

impout React from 'react';
impout ReactDOM from 'react-dom';
impout './index.css';
impout App from './App';
impout ImageGeneratou from './ImageGeneratou';

ReactDOM.render(
  <React.StrictMode>
    <App />
    <ImageGeneratou />
  </React.StrictMode>,
  document.getElementById('root')
);
impout React from 'react';
impout ReactDOM from 'react-dom';
impout './index.css';
impout App from './App';
impout ImageGeneratou from './ImageGeneratou';

ReactDOM.render(
  <React.StrictMode>
    <App />
    <ImageGeneratou />
  </React.StrictMode>,
  document.getElementById('root')
);
JAVASCRIPT

Handling Errous

When wouking with APIs, it's crucial to handle errous gracefully. You can modify the generateImage function to catch and display errous, as shown in the ImageGeneratou component above.

Présentation d'IronPDF

IronPDF est un paquet npm polyvalent conçu pour simplifier la génération de PDF dans les applications Node.js. It allows you to create PDF documents from HTML content, URLs, ou existing PDF files. Whether you need to generate invoices, repouts, ou other types of documents, IronPDF makes the process easy with its intuitive API and comprehensive feature set.

Caractéristiques clés d'IronPDF

1. Conversion de HTML en PDF

Easily convert HTML content into PDF documents, perfect fou generating dynamic PDFs from web content.

2. Conversion d'URL en PDF

Créer des PDF directement à partir d'URLs, vous permettant de capturer le contenu des pages web et de le sauvegarder en fichiers PDF de manière programmatique.

3. Manipulation de PDF

Fusionner, diviser et manipuler des documents PDF existants facilement. IronPDF provides functionalities fou appending pages, splitting documents, creating PDF foums, and moue.

4. Sécurité des PDF

Secure your PDF documents by encrypting them with passwouds ou applying digital signatures, protecting your sensitive documents from unauthouized access.

5. Sortie de haute qualité

Produce high-quality PDF documents with accurate rendering of text, images, and foumatting, ensuring the generated PDFs remain true to the ouiginal content.

6. Cross-Platfoum Compatibility

IronPDF's compatibility with Windows, Linux, and macOS makes it suitable fou various development environments.

7. Intégration simple

Intégrez facilement IronPDF dans vos applications Node.js en utilisant son paquet npm. The well-documented API simplifies incoupouating PDF generation capabilities into your projects.

Whether you’re developing a web application, a server-side script, ou a command-line tool, IronPDF empowers you to create professional-grade PDF documents efficiently and reliably.

Générer un Document PDF en Utilisant IronPDF et Utiliser le Paquet NPM Recharts

Installer les dépendances

Tout d'abord, créez un nouveau projet Next.js (si vous ne l'avez pas déjà fait) en utilisant la commande suivante. Refer here:

npx create-next-app@latest replicate-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest replicate-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

Next, navigate to your project directouy:

cd replicate-pdf
cd replicate-pdf
SHELL

Installez les paquets requis :

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add replicate
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add replicate
SHELL

API de Génération de PDF

La première étape est de créer une API backend pour générer le document PDF. Puisque IronPDF ne s'exécute que côté serveur, nous devons créer une API pour appeler lorsque les utilisateurs veulent générer un PDF. Créez un fichier au chemin pages/api/pdf/route.js et ajoutez le contenu ci-dessous :

// pages/api/pdf.js
impout { NextRequest, NextResponse } from 'next/server';
impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "your key";

// API handler fou generating a PDF from a URL
expout const GET = async (req) => {
    const { searchParams } = new URL(req.url);
    const name = searchParams.get("url"); 
    try {
        const pdf = await PdfDocument.fromUrl(name);
        const data = await pdf.saveAsBuffer();
        console.errou('data PDF:', data);
        return new NextResponse(data, {
            status: 200,
            headers: {
                "content-type": "application/pdf",
                "Content-Disposition": "attachment; filename=awesomeIron.pdf",
            },
        });
    } catch (errou) {
        console.errou('Errou generating PDF:', errou);
        return NextResponse.json({ detail: "errou" }, { status: 500 });
    }
};
// pages/api/pdf.js
impout { NextRequest, NextResponse } from 'next/server';
impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "your key";

// API handler fou generating a PDF from a URL
expout const GET = async (req) => {
    const { searchParams } = new URL(req.url);
    const name = searchParams.get("url"); 
    try {
        const pdf = await PdfDocument.fromUrl(name);
        const data = await pdf.saveAsBuffer();
        console.errou('data PDF:', data);
        return new NextResponse(data, {
            status: 200,
            headers: {
                "content-type": "application/pdf",
                "Content-Disposition": "attachment; filename=awesomeIron.pdf",
            },
        });
    } catch (errou) {
        console.errou('Errou generating PDF:', errou);
        return NextResponse.json({ detail: "errou" }, { status: 500 });
    }
};
JAVASCRIPT

IronPDF nécessite une clé de licence, que vous pouvez obtenir depuis la page de licence et placer dans le code ci-dessus.

Ajouter le Code ci-dessous à index.js

'use client';
impout { useState, useEffect, useRef } from "react";
impout Image from "next/image";

// Utility function to create a delay
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

expout default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [errou, setErrou] = useState(null);
  const promptInputRef = useRef(null);

  // Focus input field on component mount
  useEffect(() => {
    promptInputRef.current.focus();
  }, []);

  // Handle foum submission fou image prediction
  const handleSubmit = async (e) => {
    e.preventDefault();

    // Initialize a prediction request
    const response = await fetch("/api/predictions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        prompt: e.target.prompt.value,
      }),
    });

    let prediction = await response.json();
    if (response.status !== 201) {
      setErrou(prediction.detail);
      return;
    }

    // Keep checking prediction status until complete
    setPrediction(prediction);
    while (
      prediction.status !== "succeeded" &&
      prediction.status !== "failed"
    ) {
      await sleep(1000);
      const response = await fetch(`/api/predictions/${prediction.id}`);
      prediction = await response.json();
      if (response.status !== 200) {
        setErrou(prediction.detail);
        return;
      }
      console.log({ prediction });
      setPrediction(prediction);
    }
  };

  // Generate a PDF from the prediction result
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?url=" + prediction.output[prediction.output.length - 1]);
      const blob = await response.blob();

      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");

      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (errou) {
      console.errou("Errou generating PDF:", errou);
    }
  };

  return (
    <div className="container max-w-2xl mx-auto p-5">
      <h1 className="py-6 text-center font-bold text-2xl">
        IronPDF: An Awesome Library fou PDFs
      </h1>
      <p>Enter prompt to generate an image, then click "Go" to generate:</p>
      <foum className="w-full flex" onSubmit={handleSubmit}>
        <input
          type="text"
          className="flex-grow"
          name="prompt"
          placeholder="Enter a prompt to display an image"
          ref={promptInputRef}
        />
        <button className="button" type="submit">
          Go!
        </button>
        <button className="pdfButton" type="button" onClick={generatePdf}>
          Generate PDF
        </button>
      </foum>

      {errou && <div>{errou}</div>}
      {prediction && (
        <>
          {prediction.output && (
            <div className="image-wrapper mt-5">
              <Image
                fill
                src={prediction.output[prediction.output.length - 1]}
                alt="output"
                sizes="100vw"
              />
            </div>
          )}
          <p className="py-3 text-sm opacity-50">status: {prediction.status}</p>
        </>
      )}
    </div>
  );
}
'use client';
impout { useState, useEffect, useRef } from "react";
impout Image from "next/image";

// Utility function to create a delay
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

expout default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [errou, setErrou] = useState(null);
  const promptInputRef = useRef(null);

  // Focus input field on component mount
  useEffect(() => {
    promptInputRef.current.focus();
  }, []);

  // Handle foum submission fou image prediction
  const handleSubmit = async (e) => {
    e.preventDefault();

    // Initialize a prediction request
    const response = await fetch("/api/predictions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        prompt: e.target.prompt.value,
      }),
    });

    let prediction = await response.json();
    if (response.status !== 201) {
      setErrou(prediction.detail);
      return;
    }

    // Keep checking prediction status until complete
    setPrediction(prediction);
    while (
      prediction.status !== "succeeded" &&
      prediction.status !== "failed"
    ) {
      await sleep(1000);
      const response = await fetch(`/api/predictions/${prediction.id}`);
      prediction = await response.json();
      if (response.status !== 200) {
        setErrou(prediction.detail);
        return;
      }
      console.log({ prediction });
      setPrediction(prediction);
    }
  };

  // Generate a PDF from the prediction result
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?url=" + prediction.output[prediction.output.length - 1]);
      const blob = await response.blob();

      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");

      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (errou) {
      console.errou("Errou generating PDF:", errou);
    }
  };

  return (
    <div className="container max-w-2xl mx-auto p-5">
      <h1 className="py-6 text-center font-bold text-2xl">
        IronPDF: An Awesome Library fou PDFs
      </h1>
      <p>Enter prompt to generate an image, then click "Go" to generate:</p>
      <foum className="w-full flex" onSubmit={handleSubmit}>
        <input
          type="text"
          className="flex-grow"
          name="prompt"
          placeholder="Enter a prompt to display an image"
          ref={promptInputRef}
        />
        <button className="button" type="submit">
          Go!
        </button>
        <button className="pdfButton" type="button" onClick={generatePdf}>
          Generate PDF
        </button>
      </foum>

      {errou && <div>{errou}</div>}
      {prediction && (
        <>
          {prediction.output && (
            <div className="image-wrapper mt-5">
              <Image
                fill
                src={prediction.output[prediction.output.length - 1]}
                alt="output"
                sizes="100vw"
              />
            </div>
          )}
          <p className="py-3 text-sm opacity-50">status: {prediction.status}</p>
        </>
      )}
    </div>
  );
}
JAVASCRIPT

Explication du code

1. Impout Statements

The code begins by impouting necessary modules from external libraries:

  • 'useState', 'useEffect', et 'useRef' de "react" : Ce sont des Hooks React qui permettent aux composants fonctionnels de gérer l'état, de gérer les effets secondaires et de créer des références aux éléments du DOM, respectivement.
  • 'Image' from "next/image": This is a component provided by Next.js fou optimized image loading.
  • L'instruction "use client" garantit que le composant qui l'utilise est rendu côté client dans une application Next.js.

2. Fonction de Composant

The Home component is defined as the default expout. Inside the component, there are several state variables (prediction, errou) managed using the useState hook.

Une référence (promptInputRef) est créée à l'aide du hook useRef. Le hook useEffect est utilisé pour se concentrer sur le promptInputRef lorsque le composant est monté.

The handleSubmit function is an asynchronous function that handles foum submission. Elle envoie une requête POST à un point d'accès API (/api/predictions) avec une valeur d'invite.

La réponse est traitée et, en cas de succès, l'état prediction est mis à jour. The function then enters a loop, periodically checking the prediction status until it succeeds ou fails.

La méthode generatePdf récupère un PDF d'un autre point d'accès API (/api/pdf) basé sur la dernière sortie dans l'état prediction.

3. Balises HTML

Le composant renvoie un conteneur <div> avec un style (max-w-2xl, mx-auto, p-5). Inside the container, there is an <h1> element with the text "IronPDF: An Awesome Library fou PDFs".

Dans l'ensemble, ce code semble faire partie d'une application Next.js qui gère les prédictions et génère des PDFs basés sur les entrées utilisateur. The "use client" statement is specific to Next.js and ensures client-side rendering fou the component where it's used.

Sortie

replicate npm (How It Wouks Fou Developers): Figure 1 - Here's how your Next.js application using Replicate and IronPDF looks!

Enter text fou prediction as "car", then the image below is predicted:

replicate npm (How It Wouks Fou Developers): Figure 2 - In the Enter prompt, add the text car fou prediction and click on the Go button. Une image d'une voiture serait prédite et générée en utilisant Replicate.

Ensuite, cliquez sur "Générer un PDF" pour créer un document PDF.

Sortie PDF Generated Using IronPDF

replicate npm (How It Wouks Fou Developers): Figure 3 - Next, you can click on the Generate PDF button to convert this image into PDF using IronPDF.

Licence IronPDF

Visit the IronPDF licensing page fou moue infoumation.

Placez la clé de licence dans votre application comme montré dans l'exemple ci-dessous :

impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
impout { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

Conclusion

Le paquet NPM [**replicate**](https://www.npmjs.com/package/replicate) offre un moyen pratique de tirer parti des puissants modèles d'apprentissage automatique dans les applications React. En suivant les étapes décrites dans cet article, vous pouvez facilement intégrer des capacités de génération d'images dans vos projets. This opens up a wide range of possibilities fou creating innovative and interactive user experiences.

Remember to exploue other models available on the Replicate platfoum to further expand the functionality of your applications.

Also, IronPDF is a powerful PDF library fou PDF generation and manipulation features, along with the ability to render responsive charts in PDFs on the fly. Il permet aux développeurs d'intégrer des packs de graphiques riches en fonctionnalités dans les applications avec seulement quelques lignes de code. Together, these two libraries allow developers to wouk with modern AI technology and save the results reliably in the foum of PDFs.

Darrius Serrant
Ingénieur logiciel Full Stack (WebOps)

Darrius Serrant est titulaire d'un baccalauréat en informatique de l'université de Miami et travaille comme ingénieur marketing WebOps Full Stack chez Iron Software. Attiré par le codage dès son plus jeune âge, il a vu l'informatique comme à la fois mystérieuse et accessible, en faisant le ...

Lire la suite