跳過到頁腳內容
NODE 說明

replicate npm(開發者的使用方法)

' replicate ' NPM 套件是一個功能強大的用戶端工具,用於將機器學習模型整合到 React 應用程式中。 它允許開發人員輕鬆使用預訓練模型,並直接在應用程式中運行推理,而無需管理複雜的後端基礎架構。 以下概述如何在 React 專案中使用replicate NPM 套件。 此外,我們將探索 PDF 生成庫IronPDF ,並示範如何將這兩個庫結合起來以建立一個功能齊全的應用程式。

複製簡介

Replicate是一個線上平台,它透過簡單的 API 提供對機器學習模型的存取。 它託管了來自各個領域的模型,例如圖像生成、文字分析等等。 透過使用"replicate"NPM 套件,開發人員可以無縫地將這些模型整合到他們的應用程式中。

開始

安裝

要在你的 React 應用程式中使用replicate ,你首先需要安裝該軟體套件。 您可以使用 npm 或 yarn 來實現:

npm install replicate
npm install replicate
SHELL

yarn add replicate
yarn add replicate
SHELL

API金鑰

您需要一個 API 金鑰才能與 Replicate API 互動。 您可以透過在Replicate 網站上註冊並建立新的 API 令牌來取得此金鑰。

基本用法

以下是使用 React 應用程式中replicate套件的逐步指南。

1. 導入軟體包並初始化客戶端

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

範例應用

讓我們創建一個簡單的 React 應用程序,允許用戶根據文字提示生成圖像,以演示 replicate 包的用法。

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.創建一個用於圖像生成的組件:

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

錯誤處理

在使用 API 時,優雅地處理錯誤至關重要。 您可以修改generateImage函數來捕獲和顯示錯誤,如上面的ImageGenerat或元件所示。

介紹 IronPDF。

IronPDF是一個功能強大的 npm 包,旨在簡化 Node.js 應用程式中的 PDF 生成。 它允許您從HTML 內容URL或現有 PDF 文件建立 PDF 文件。 無論您需要產生發票、報告還是其他類型的文檔,IronPDF 憑藉其直覺的API和全面的功能集,都能讓這個過程變得輕鬆簡單。

IronPDF 的主要功能

1.HTML 至 PDF 轉換

輕鬆將 HTML 內容轉換為 PDF 文檔,非常適合從網頁內容產生動態 PDF。

2. URL 轉 PDF

直接從 URL 建立 PDF,使您能夠捕獲網頁內容並以程式設計方式將其儲存為 PDF 檔案。

3. PDF 處理

輕鬆合併、分割和操作現有 PDF 文件。 IronPDF 提供追加頁面、分割文件、建立 PDF 表單等功能。

4.PDF安全性

使用密碼加密套用數位簽章來保護您的 PDF 文檔,防止敏感文檔被未經授權的存取。

5. 高品質輸出

產生高品質的 PDF 文件,準確呈現文字、圖像和格式,確保產生的 PDF 與原始內容保持一致。

6. 跨平台相容性

IronPDF 與 Windows、Linux 和 macOS 相容,使其適用於各種開發環境。

7. 簡易集成

使用 IronPDF 的 npm 套件,即可輕鬆地將其整合到您的 Node.js 應用程式中。 完善的 API 文件簡化了將 PDF 生成功能整合到專案中的過程。

無論您是開發 Web 應用程式、伺服器端腳本或命令列工具,IronPDF 都能協助您有效率且可靠地建立專業級 PDF 文件。

使用 IronPDF 產生 PDF 文件並使用 Recharts NPM 套件

安裝依賴項

首先,使用以下命令建立一個新的 Next.js 專案(如果您還沒有建立)。 請參考此處

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

接下來,導航到您的專案目錄:

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

第一步是建立後端 API 來產生 PDF 文件。 由於 IronPDF 只能在伺服器端運行,我們需要建立一個 API,以便在使用者想要產生 PDF 時呼叫。 在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. 進口聲明

程式碼首先從外部庫導入必要的模組:

  • 來自&quot;react&quot;&#39;useState&#39;&#39;useEffect&#39;&#39;useRef&#39; :這些是 React Hooks,分別允許函數元件管理狀態、處理副作用和建立對 DOM 元素的參考。
  • &#39;Image&#39;來自&quot;next/image&quot; : 這是 Next.js 提供的一個元件,用於最佳化圖片載入。
  • &quot;use client&quot;語句確保使用它的元件在Next.js應用程式的客戶端進行渲染。

2. 組件功能

Home組件被定義為預設導出組件。 元件內部有幾個狀態變數( predictionerr或 ),使用useState hook 進行管理。

使用useRef鉤子建立參考( promptInputRef )。 useEffect hook 用於在元件掛載時聚焦到promptInputRef

handleSubmit函數是一個非同步函數,用於處理表單提交。 它會向 API 端點( /api/predictions )發送 POST 請求,並帶有提示值。

回應被處理,如果成功,則更新prediction狀態。 然後函數進入循環,定期檢查預測狀態,直到預測成功或失敗。

generatePdf方法根據prediction狀態中的最後一個輸出,從另一個 API 端點( /api/pdf )取得 PDF。

3. HTML 標記

該元件會傳回容器<div>帶有樣式( max-w-2xlmx-autop-5 )。 容器內有一個<h1>包含文字"IronPDF:一個很棒的 PDF 庫"的元素。

總的來說,這段程式碼似乎是 Next.js 應用程式的一部分,用於處理預測並根據使用者輸入生成 PDF。 "use client"語句是Next.js特有的,它確保使用該語句的元件進行客戶端渲染。

輸出

! replicate npm(開發者使用方法):圖 1 - 這是使用 Replicate 和 IronPDF 的 Next.js 應用程式的樣子!

輸入要預測的文字"car",則會預測出下圖:

複製 npm(開發者使用方法):圖 2 - 在 Enter 提示中,新增文字car進行預測,然後按一下 Go 按鈕。 使用 Replicate 可以預測並產生汽車影像。

然後點選"生成 PDF"以建立 PDF 文件。

使用 IronPDF 產生輸出 PDF 文件

複製 npm(開發者使用方法):圖 3 - 接下來,您可以點擊產生 PDF按鈕,使用 IronPDF 將此圖像轉換為 PDF。

IronPDF 授權。

請造訪IronPDF許可頁面以了解更多資訊。

請按照以下範例所示,將許可證密鑰放入您的應用程式中:

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 應用程式中利用強大的機器學習模型的便捷方法。 按照本文所述的步驟,您可以輕鬆地將圖像生成功能整合到您的專案中。 這為創造創新和互動式的使用者體驗開闢了廣闊的可能性。

請記住探索Replicate平台上的其他模型,以進一步擴展應用程式的功能。

此外, IronPDF是一個功能強大的 PDF 庫,具有 PDF 生成和操作功能,以及在 PDF 中即時渲染響應式圖表的功能。 它使開發人員能夠僅用幾行程式碼將功能豐富的圖表包整合到應用程式中。 這兩個函式庫結合起來,可以讓開發者使用現代人工智慧技術,並將結果可靠地儲存為 PDF 檔案。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。