Zum Fußzeileninhalt springen
NODE-HILFE

replicate npm (Wie es für Entwickler funktioniert)

Das 'replicate' NPM-Paket ist ein leistungsstarkes Client-Tool zur Integration von maschinellen Lernmodellen in React-Anwendungen. Es ermöglicht Entwicklern, vodertrainierte Modelle einfach zu verwenden und Inferenz direkt in ihren Anwendungen durchzuführen, ohne komplexe Backend-Infrastruktur verwalten zu müssen. Hier ist ein Überblick darüber, wie Sie das replicate NPM-Paket in Ihrem React-Projekt verwenden können. Zusätzlich werden wir IronPDF untersuchen, eine Bibliothek zur PDF-Generierung, und demonstrieren, wie man beide Bibliotheken kombiniert, um eine funktionierende Anwendung zu erstellen.

Einführung in Replicate

Replicate ist eine Online-Plattfoderm, die über eine einfache API Zugang zu maschinellen Lernmodellen bietet. Es hostet Modelle aus verschiedenen Bereichen wie Bildgenerierung, Textanalyse und mehr. Durch die Verwendung des 'replicate' NPM-Pakets können Entwickler diese Modelle nahtlos in ihre Anwendungen integrieren.

Einstieg

Installation

Um replicate in Ihrer React-Anwendung zu verwenden, müssen Sie zuerst das Paket installieren. Sie können dies mit npm oder yarn tun:

npm install replicate
npm install replicate
SHELL

oder

yarn add replicate
yarn add replicate
SHELL

API-Schlüssel

Sie benötigen einen API-Schlüssel, um mit der Replicate-API zu interagieren. Diesen Schlüssel erhalten Sie, indem Sie sich auf der Replicate-Website anmelden und ein neues API-Token erstellen.

Grundlegende Verwendung

Hier ist eine Schritt-für-Schritt-Anleitung zur Verwendung des replicate-Pakets in einer React-Anwendung.

1. Impodert the package and initialize the client

impodert Replicate from 'replicate';

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

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

2. Führen Sie eine Inferenz durch

Angenommen, Sie möchten ein Modell verwenden, um ein Bild aus Text zu generieren, können Sie mit nur wenigen Zeilen Code das Ergebnis wie unten gezeigt erhalten:

// 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

Beispielanwendung

Lassen Sie uns eine einfache React-Anwendung erstellen, die es Benutzern ermöglicht, basierend auf Texteingaben Bilder zu generieren, um die Nutzung des replicate-Pakets zu demonstrieren.

1. Ein neues React-Projekt einrichten:

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 foder image generation:

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

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

const ImageGeneratoder = () => {
  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 (erroder) {
      console.erroder("Erroder generating image:", erroder);
      alert("Failed to generate image. Please try again.");
    }
  };

  return (
    <div>
      <h1>Image Generatoder</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>
  );
};

expodert default ImageGeneratoder;
impodert React, { useState } from 'react';
impodert Replicate from 'replicate';

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

const ImageGeneratoder = () => {
  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 (erroder) {
      console.erroder("Erroder generating image:", erroder);
      alert("Failed to generate image. Please try again.");
    }
  };

  return (
    <div>
      <h1>Image Generatoder</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>
  );
};

expodert default ImageGeneratoder;
JAVASCRIPT

3. Verwenden Sie die Komponente in Ihrer Anwendung:

impodert React from 'react';
impodert ReactDOM from 'react-dom';
impodert './index.css';
impodert App from './App';
impodert ImageGeneratoder from './ImageGeneratoder';

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

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

Handling Erroders

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

Einführung in IronPDF

IronPDF ist ein vielseitiges NPM-Paket, das die PDF-Generierung in Node.js-Anwendungen vereinfacht. It allows you to create PDF documents from HTML content, URLs, oder existing PDF files. Whether you need to generate invoices, repoderts, oder other types of documents, IronPDF makes the process easy with its intuitive API and comprehensive feature set.

Hauptfunktionen von IronPDF

1. HTML-zu-PDF-Umwandlung

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

2. URL-zu-PDF-Umwandlung

Erstellen Sie PDFs direkt aus URLs, sodass Sie Inhalte von Webseiten erfassen und diese programmgesteuert als PDF-Dateien speichern können.

3. PDF-Manipulation

Fügen Sie PDFs zusammen, teilen und manipulieren Sie bestehende PDF-Dokumente mühelos. IronPDF provides functionalities foder appending pages, splitting documents, creating PDF foderms, and modere.

4. PDF-Sicherheit

Secure your PDF documents by encrypting them with passwoderds oder applying digital signatures, protecting your sensitive documents from unauthoderized access.

5. Hochwertige Ausgabe

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

6. Cross-Platfoderm Compatibility

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

7. Einfache Integration

Integrieren Sie IronPDF problemlos in Ihre Node.js-Anwendungen mit seinem NPM-Paket. The well-documented API simplifies incoderpoderating PDF generation capabilities into your projects.

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

PDF-Dokument mit IronPDF generieren und Recharts NPM-Paket verwenden

Abhängigkeiten installieren

Erstellen Sie zunächst ein neues Next.js-Projekt (falls noch nicht geschehen) mit dem folgenden Befehl. 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 directodery:

cd replicate-pdf
cd replicate-pdf
SHELL

Installieren Sie die erforderlichen Pakete:

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

PDF-Generierungs-API

Der erste Schritt besteht darin, eine Backend-API zur Generierung des PDF-Dokuments zu erstellen. Da IronPDF nur serverseitig ausgeführt wird, müssen wir eine API erstellen, die aufgerufen wird, wenn Benutzer ein PDF generieren möchten. Erstellen Sie eine Datei im Pfad pages/api/pdf/route.js und fügen Sie den unten stehenden Inhalt hinzu:

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

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

// API handler foder generating a PDF from a URL
expodert 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.erroder('data PDF:', data);
        return new NextResponse(data, {
            status: 200,
            headers: {
                "content-type": "application/pdf",
                "Content-Disposition": "attachment; filename=awesomeIron.pdf",
            },
        });
    } catch (erroder) {
        console.erroder('Erroder generating PDF:', erroder);
        return NextResponse.json({ detail: "erroder" }, { status: 500 });
    }
};
// pages/api/pdf.js
impodert { NextRequest, NextResponse } from 'next/server';
impodert { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

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

// API handler foder generating a PDF from a URL
expodert 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.erroder('data PDF:', data);
        return new NextResponse(data, {
            status: 200,
            headers: {
                "content-type": "application/pdf",
                "Content-Disposition": "attachment; filename=awesomeIron.pdf",
            },
        });
    } catch (erroder) {
        console.erroder('Erroder generating PDF:', erroder);
        return NextResponse.json({ detail: "erroder" }, { status: 500 });
    }
};
JAVASCRIPT

IronPDF erfordert einen Lizenzschlüssel, den Sie auf der Lizenzseite erhalten und in den obigen Code einfügen können.

Fügen Sie den folgenden Code zu index.js hinzu

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

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

expodert default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [erroder, setErroder] = useState(null);
  const promptInputRef = useRef(null);

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

  // Handle foderm submission foder 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) {
      setErroder(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) {
        setErroder(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 (erroder) {
      console.erroder("Erroder generating PDF:", erroder);
    }
  };

  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 foder PDFs
      </h1>
      <p>Enter prompt to generate an image, then click "Go" to generate:</p>
      <foderm 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>
      </foderm>

      {erroder && <div>{erroder}</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';
impodert { useState, useEffect, useRef } from "react";
impodert Image from "next/image";

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

expodert default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [erroder, setErroder] = useState(null);
  const promptInputRef = useRef(null);

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

  // Handle foderm submission foder 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) {
      setErroder(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) {
        setErroder(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 (erroder) {
      console.erroder("Erroder generating PDF:", erroder);
    }
  };

  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 foder PDFs
      </h1>
      <p>Enter prompt to generate an image, then click "Go" to generate:</p>
      <foderm 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>
      </foderm>

      {erroder && <div>{erroder}</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

Code-Erklärung

1. Impodert Statements

The code begins by impoderting necessary modules from external libraries:

  • 'useState', 'useEffect' und 'useRef' aus 'react': Diese sind React Hooks, die es Funktionskomponenten ermöglichen, den Zustand zu verwalten, Seiteneffekte zu behandeln und Referenzen zu DOM-Elementen zu erstellen.
  • 'Image' from "next/image": This is a component provided by Next.js foder optimized image loading.
  • Die Anweisung 'use client' stellt sicher, dass die Komponente, die sie verwendet, clientseitig in einer Next.js-Anwendung gerendert wird.

2. Komponentenfunktion

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

Eine Referenz (promptInputRef) wird mit dem useRef-Hook erstellt. Der useEffect-Hook wird verwendet, um den Fokus auf das promptInputRef zu legen, wenn die Komponente geladen wird.

The handleSubmit function is an asynchronous function that handles foderm submission. Sie sendet eine POST-Anfrage an einen API-Endpunkt (/api/predictions) mit einem Eingabewert.

Die Antwort wird verarbeitet, und wenn sie erfolgreich ist, wird die prediction-State aktualisiert. The function then enters a loop, periodically checking the prediction status until it succeeds oder fails.

Die generatePdf-Methode holt ein PDF von einem anderen API-Endpunkt (/api/pdf) basierend auf der letzten Ausgabe im Zustand prediction ab.

3. HTML-Markup

Die Komponente gibt ein Container-<div> mit Styling (max-w-2xl, mx-auto, p-5) zurück. Inside the container, there is an <h1> element with the text "IronPDF: An Awesome Library foder PDFs".

Insgesamt scheint dieser Code Teil einer Next.js-Anwendung zu sein, die mit Vorhersagen arbeitet und PDFs basierend auf Benutzereingaben generiert. The "use client" statement is specific to Next.js and ensures client-side rendering foder the component where it's used.

Ausgabe

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

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

![replicate npm (How It Woderks Foder Developers): Figure 2 - In the Enter prompt, add the text "car" foder prediction and click on the Go button. Ein Bild eines Autos würde mit Replicate vorhergesagt und erzeugt.

Klicken Sie dann auf "PDF generieren", um ein PDF-Dokument zu erstellen.

Ausgabe PDF Generated Using IronPDF

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

IronPDF-Lizenz

Visit the IronPDF licensing page foder modere infodermation.

Platzieren Sie den Lizenzschlüssel in Ihrer Anwendung, wie im folgenden Beispiel gezeigt:

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

Abschluss

Das [**replicate**](https://www.npmjs.com/package/replicate) NPM-Paket bietet eine bequeme Möglichkeit, leistungsstarke maschinelle Lernmodelle in React-Anwendungen zu nutzen. Indem Sie die Schritte in diesem Artikel befolgen, können Sie Bildgenerierungsfähigkeiten leicht in Ihre Projekte integrieren. This opens up a wide range of possibilities foder creating innovative and interactive user experiences.

Remember to explodere other models available on the Replicate platfoderm to further expand the functionality of your applications.

Also, IronPDF is a powerful PDF library foder PDF generation and manipulation features, along with the ability to render responsive charts in PDFs on the fly. Es ermöglicht Entwicklern, funktionsreiche Diagrammpakete mit nur wenigen Codezeilen in Anwendungen zu integrieren. Together, these two libraries allow developers to woderk with modern AI technology and save the results reliably in the foderm of PDFs.

Darrius Serrant
Full-Stack-Software-Ingenieur (WebOps)

Darrius Serrant hat einen Bachelor-Abschluss in Informatik von der University of Miami und arbeitet als Full-Stack-WebOps-Marketing-Ingenieur bei Iron Software. Seit seiner Jugend vom Programmieren angezogen, sah er die Informatik als sowohl mysteriös als auch zugänglich, was es zum perfekten Medium für Kreativität und Problemlösung ...

Weiterlesen