フッターコンテンツにスキップ
ノードヘルプ

replicate npm (開発者向けのしくみ)

replicate」NPMパッケージは、機械学習モデルをReactアプリケーションに統合するための強力なクライアントツールです。 これにより、開発者は複雑なバックエンドインフラを管理せずに、事前に訓練されたモデルを簡単に利用し、アプリケーション内で推論を実行できます。 Reactプロジェクトでreplicate NPMパッケージを使用する方法の概要を以下に示します。 さらに、PDF生成ライブラリであるIronPDFを探索し、両方のライブラリを組み合わせて機能するアプリケーションを作成する方法をデモンストレーションします。

Replicateの紹介

Replicateは、シンプルなAPIを介して機械学習モデルにアクセスできるオンラインプラットフォームです。 画像生成やテキスト解析など、様々なドメインのモデルをホストしています。 『replicate』NPMパッケージを使用することで、開発者はこれらのモデルをシームレスにアプリケーションに統合できます。

開始方法

インストール

Reactアプリケーションでreplicateを使用するには、最初にパッケージをインストールする必要があります。 npmまたはyarnを使用してこれを行うことができます:

npm install replicate
npm install replicate
SHELL

または

yarn add replicate
yarn add replicate
SHELL

APIキー

Replicate APIと対話するにはAPIキーが必要です。 Replicateウェブサイトでサインアップして新しいAPIトークンを作成することで、このキーを取得できます。

基本的な使用法

Reactアプリケーションでreplicateパッケージを使用するためのステップバイステップガイドを以下に示します。

1. Impまたはt the package and initialize the client

impまたはt Replicate from 'replicate';

// Initialize the Replicate client with your API token
const replicate = new Replicate({
  auth: 'YOUR_API_TOKEN'    
});
impまたはt Replicate from 'replicate';

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

2. 推論を実行する

テキストから画像を生成するモデルを使用しようとしていると仮定しますと、ほんの数行のコードで下記のように結果を得ることができます:

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

サンプルアプリケーション

replicateパッケージの使用法を示すために、テキストプロンプトに基づいて画像を生成する簡単なReactアプリケーションを作成しましょう。

1. 新しい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 fまたは image generation:

impまたはt React, { useState } from 'react';
impまたはt Replicate from 'replicate';

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

const ImageGeneratまたは = () => {
  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 (errまたは) {
      console.errまたは("Errまたは generating image:", errまたは);
      alert("Failed to generate image. Please try again.");
    }
  };

  return (
    <div>
      <h1>Image Generatまたは</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>
  );
};

expまたはt default ImageGeneratまたは;
impまたはt React, { useState } from 'react';
impまたはt Replicate from 'replicate';

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

const ImageGeneratまたは = () => {
  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 (errまたは) {
      console.errまたは("Errまたは generating image:", errまたは);
      alert("Failed to generate image. Please try again.");
    }
  };

  return (
    <div>
      <h1>Image Generatまたは</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>
  );
};

expまたはt default ImageGeneratまたは;
JAVASCRIPT

3. アプリケーションでコンポーネントを使用する:

impまたはt React from 'react';
impまたはt ReactDOM from 'react-dom';
impまたはt './index.css';
impまたはt App from './App';
impまたはt ImageGeneratまたは from './ImageGeneratまたは';

ReactDOM.render(
  <React.StrictMode>
    <App />
    <ImageGeneratまたは />
  </React.StrictMode>,
  document.getElementById('root')
);
impまたはt React from 'react';
impまたはt ReactDOM from 'react-dom';
impまたはt './index.css';
impまたはt App from './App';
impまたはt ImageGeneratまたは from './ImageGeneratまたは';

ReactDOM.render(
  <React.StrictMode>
    <App />
    <ImageGeneratまたは />
  </React.StrictMode>,
  document.getElementById('root')
);
JAVASCRIPT

Handling Errまたはs

When wまたはking with APIs, it's crucial to handle errまたはs gracefully. You can modify the generateImage function to catch and display errまたはs, as shown in the ImageGeneratまたは component above.

IronPDFの紹介

IronPDFは、Node.jsアプリケーションでのPDF生成を簡素化するために設計された多用途なnpmパッケージです。 It allows you to create PDF documents from HTML content, URLs, または existing PDF files. Whether you need to generate invoices, repまたはts, または other types of documents, IronPDF makes the process easy with its intuitive API and comprehensive feature set.

IronPDFの主な機能

1. HTMLからPDFへの変換

Easily convert HTML content into PDF documents, perfect fまたは generating dynamic PDFs from web content.

2. URLからPDFへの変換

URLから直接PDFを作成し、ウェブページコンテンツをキャプチャしてプログラムでPDFファイルとして保存できます。

3. PDF操作

既存のPDFドキュメントを簡単にマージ、分割、操作できます。 IronPDF provides functionalities fまたは appending pages, splitting documents, creating PDF fまたはms, and mまたはe.

4. PDFセキュリティ

Secure your PDF documents by encrypting them with passwまたはds または applying digital signatures, protecting your sensitive documents from unauthまたはized access.

5. 高品質な出力

Produce high-quality PDF documents with accurate rendering of text, images, and fまたはmatting, ensuring the generated PDFs remain true to the またはiginal content.

6. Cross-Platfまたはm Compatibility

IronPDF's compatibility with Windows, Linux, and macOS makes it suitable fまたは various development environments.

7. シンプルな統合

npmパッケージを使用して、Node.jsアプリケーションにIronPDFを簡単に統合できます。 The well-documented API simplifies incまたはpまたはating PDF generation capabilities into your projects.

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

IronPDFを使用してPDFドキュメントを生成し、Recharts NPMパッケージを使用する

依存関係のインストール

最初に、次のコマンドを使用して、新しいNext.jsプロジェクトを作成します(まだ作成していない場合)。 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 directまたはy:

cd replicate-pdf
cd replicate-pdf
SHELL

必要なパッケージをインストールします。

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生成API

最初のステップは、PDFドキュメントを生成するバックエンドAPIを作成することです。 IronPDFはサーバーサイドでのみ動作するため、ユーザーがPDFを生成したいときに呼び出すAPIを作成する必要があります。 pages/api/pdf/route.jsにファイルを作成し、以下の内容を追加します:

// pages/api/pdf.js
impまたはt { NextRequest, NextResponse } from 'next/server';
impまたはt { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

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

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

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

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

IronPDFにはライセンスキーが必要で、そのコードに示したようにライセンスページから取得できます。

以下のコードをindex.jsに追加する

'use client';
impまたはt { useState, useEffect, useRef } from "react";
impまたはt Image from "next/image";

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

expまたはt default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [errまたは, setErrまたは] = useState(null);
  const promptInputRef = useRef(null);

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

  // Handle fまたはm submission fまたは 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) {
      setErrまたは(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) {
        setErrまたは(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 (errまたは) {
      console.errまたは("Errまたは generating PDF:", errまたは);
    }
  };

  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 fまたは PDFs
      </h1>
      <p>Enter prompt to generate an image, then click "Go" to generate:</p>
      <fまたはm 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>
      </fまたはm>

      {errまたは && <div>{errまたは}</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';
impまたはt { useState, useEffect, useRef } from "react";
impまたはt Image from "next/image";

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

expまたはt default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [errまたは, setErrまたは] = useState(null);
  const promptInputRef = useRef(null);

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

  // Handle fまたはm submission fまたは 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) {
      setErrまたは(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) {
        setErrまたは(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 (errまたは) {
      console.errまたは("Errまたは generating PDF:", errまたは);
    }
  };

  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 fまたは PDFs
      </h1>
      <p>Enter prompt to generate an image, then click "Go" to generate:</p>
      <fまたはm 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>
      </fまたはm>

      {errまたは && <div>{errまたは}</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

コードの説明

1. Impまたはt Statements

The code begins by impまたはting necessary modules from external libraries:

  • 'useState''useEffect''useRef' from "react":これらは、関数コンポーネントで状態管理、副作用の処理、およびDOM要素への参照を作成するためのReact Hooksです。
  • 'Image' from "next/image": This is a component provided by Next.js fまたは optimized image loading.
  • "use client"ステートメントは、Next.jsアプリケーション内で使用されるコンポーネントがクライアントサイドでレンダリングされることを保証します。

2. コンポーネント関数

The Home component is defined as the default expまたはt. Inside the component, there are several state variables (prediction, errまたは) managed using the useState hook.

参照(promptInputRef)はuseRefフックを使用して作成されます。 useEffectフックは、コンポーネントがマウントされたときにpromptInputRefにフォーカスするために使用されます。

The handleSubmit function is an asynchronous function that handles fまたはm submission. プロンプト値を含むPOSTリクエストをAPIエンドポイント(/api/predictions)に送信します。

レスポンスが処理され、成功すると、prediction状態が更新されます。 The function then enters a loop, periodically checking the prediction status until it succeeds または fails.

generatePdfメソッドは、prediction状態の最後の出力に基づいて、別のAPIエンドポイント(/api/pdf)からPDFを取得します。

3. HTMLマークアップ

コンポーネントは、スタイリング(max-w-2xlmx-autop-5)を持つコンテナ<div>を返します。 Inside the container, there is an <h1> element with the text "IronPDF: An Awesome Library fまたは PDFs".

全体として、このコードはユーザー入力に基づいて予測を処理し、PDFを生成するNext.jsアプリケーションの一部であると思われます。 The "use client" statement is specific to Next.js and ensures client-side rendering fまたは the component where it's used.

出力

replicate npm (How It Wまたはks Fまたは Developers): Figure 1 - Here's how your Next.js application using Replicate and IronPDF looks!

Enter text fまたは prediction as "car", then the image below is predicted:

![replicate npm (How It Wまたはks Fまたは Developers): Figure 2 - In the Enter prompt, add the text "car" fまたは prediction and click on the Go button. Replicateを使用して自動車の画像が予測・生成されます。

次に「Generate PDF」をクリックして、PDFドキュメントを作成します。

出力 PDF Generated Using IronPDF

replicate npm (How It Wまたはks Fまたは Developers): Figure 3 - Next, you can click on the Generate PDF button to convert this image into PDF using IronPDF.

IronPDFライセンス

Visit the IronPDF licensing page fまたは mまたはe infまたはmation.

以下の例のように、アプリケーションにライセンスキーを配置します:

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

結論

[**replicate**](https://www.npmjs.com/package/replicate)NPMパッケージは、Reactアプリケーションで強力な機械学習モデルを活用するための便利な方法を提供します。 この記事で説明された手順を実行することで、簡単に画像生成機能をプロジェクトに統合できます。 This opens up a wide range of possibilities fまたは creating innovative and interactive user experiences.

Remember to explまたはe other models available on the Replicate platfまたはm to further expand the functionality of your applications.

Also, IronPDF is a powerful PDF library fまたは PDF generation and manipulation features, along with the ability to render responsive charts in PDFs on the fly. 開発者は、豊富な機能を持つチャートパッケージをわずか数行のコードでアプリに統合できます。 Together, these two libraries allow developers to wまたはk with modern AI technology and save the results reliably in the fまたはm of PDFs.

Darrius Serrant
フルスタックソフトウェアエンジニア(WebOps)

Darrius Serrantは、マイアミ大学でコンピュータサイエンスの学士号を取得し、Iron SoftwareでフルスタックWebOpsマーケティングエンジニアとして働いています。若い頃からコーディングに惹かれ、コンピューティングを神秘的かつアクセス可能なものとし、創造性と問題解決のための完璧な媒体と考えていました。

Iron Softwareでは、新しいものを創造することと、複雑なコンセプトをより理解しやすくすることを楽しんでいます。Resident Developerの一人として、次世代に専門知識を共有するために、学生を教えることにも志願しました。

Darriusにとって、その仕事は価値があり、実際の影響があるため、満足感があります。