跳至頁尾內容
NODE 說明

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

replicate NPM套件是一個強大的客戶端工具,可以將機器學習模型整合到React應用中。 它允許開發者輕鬆使用預訓練模型,並直接在其應用內運行推理,而無需管理複雜的後端架構。 這裡是一個如何在您的React項目中使用replicate NPM包的概述。 此外,我們將探索IronPDF,這是一個PDF生成程式庫,並演示如何將這兩個程式庫結合以建立一個功能性應用。

Replicate介紹

Replicate是一個線上平台,通過簡單API提供機器學習模型的存取。 它托管各種領域的模型,如圖像生成、文字分析等。 通過使用'replicate' NPM包,開發者可以無縫地將這些模型整合到他們的應用中。

快速入門

安裝

要在您的React應用中使用replicate,首先需要安裝。 您可以使用npm或yarn來完成這個操作:

npm install replicate
npm install replicate
SHELL

or

yarn add replicate
yarn add replicate
SHELL

API金鑰

您將需要一個API金鑰來與Replicate API互動。 您可以通過在Replicate網站註冊並建立新的API token來獲得這個金鑰。

基本用法

這是一個在React應用中使用replicate包的逐步指南。

1. 匯入包並初始化客戶端

import Replicate from 'replicate';

// Initialize the Replicate client with your API token
const replicate = new Replicate({
  auth: 'YOUR_API_TOKEN'    
});
import 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. 為圖像生成建立一個元件:

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

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

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

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

export default ImageGenerator;
import React, { useState } from 'react';
import Replicate from 'replicate';

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

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

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

export default ImageGenerator;
JAVASCRIPT

3. 在您的應用中使用該元件:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ImageGenerator from './ImageGenerator';

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

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

處理錯誤

在使用API時,優雅地處理錯誤是至關重要的。 您可以修改ImageGenerator元件所示。

介紹IronPDF

IronPDF是一個多功能npm包,旨在簡化Node.js應用中的PDF生成。 它允許您從HTML內容URLs或現有的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. 簡單整合

輕鬆使用其npm包將IronPDF整合到您的Node.js應用中。 文件詳盡的API簡化了在項目中加入PDF生成功能的過程。

無論您是在開發網路應用、伺服器端腳本還是命令行工具,IronPDF都能高效、可靠地幫助您建立專業級的PDF文件。

使用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

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

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僅在伺服器端運行,我們需要在使用者希望生成PDF時建立一個可調用的API。 在路徑pages/api/pdf/route.js建立一個文件,並新增以下內容:

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

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

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

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

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

IronPDF需要一個授權金鑰,您可以從授權頁獲取並放置到上面的程式碼中。

將以下程式碼新增到index.js

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

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

export default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [error, setError] = useState(null);
  const promptInputRef = useRef(null);

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

  // Handle form submission for 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) {
      setError(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) {
        setError(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 (error) {
      console.error("Error generating PDF:", error);
    }
  };

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

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

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

export default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [error, setError] = useState(null);
  const promptInputRef = useRef(null);

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

  // Handle form submission for 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) {
      setError(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) {
        setError(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 (error) {
      console.error("Error generating PDF:", error);
    }
  };

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

      {error && <div>{error}</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. 匯入語句

程式碼從外部程式庫匯入必要的模組開始:

  • "react":這些是React Hooks,允許函式元件管理狀態、處理副作用以及建立DOM元素的引用。
  • 'Image' 來自"next/image":這是由Next.js提供的用於優化圖像載入的元件。
  • "use client"語句確保在Next.js應用中,使用該語句的元件是在客戶端側渲染的。

2. 元件函式

Home元件被定義為預設匯出。 在該元件內,有幾個狀態變數(useState鉤子管理。

使用promptInputRef)。 使用promptInputRef

handleSubmit函式是一個處理表單提交的異步函式。 它將帶有提示值的POST請求發送到API端點(/api/predictions)。

響應被處理,如果成功,則更新prediction狀態。 然後函式進入一個迴圈,定期檢查預測狀態,直到成功或失敗。

/api/pdf)獲取PDF。

3. HTML標記

該元件返回一個具有樣式的容器 <div>。 容器內有一個帶有文字"IronPDF: An Awesome Library for PDFs"的<h1>元素。

整體上,這段程式碼看起來是Next.js應用的一部分,用於基於使用者輸入的預測和生成PDF。 "use client"語句特定於Next.js,確保元件在其所用的地方進行客戶端渲染。

輸出

replicate npm(開發者如何運作):圖1 - 這就是您的Next.js應用使用Replicate和IronPDF的樣子!

輸入用於預測的文字為"car",然後下方圖像被預測:

replicate npm(開發者如何運作):圖2 - 在輸入提示中,新增文字car以進行預測並點擊Go按鈕。 使用Replicate會預測並生成一個汽車的圖像。

然後點擊"生成PDF"按鈕以建立PDF文件。

使用IronPDF生成的輸出PDF

replicate npm(開發者如何運作):圖3 - 接下來,您可以點擊生成PDF按鈕,使用IronPDF將此圖像轉換為PDF。

IronPDF 授權

存取IronPDF授權頁以獲取更多資訊。

在您的應用中放置授權金鑰,如下面範例所示:

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
import { 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中即時呈現響應式圖表。 它使開發者僅用幾行程式碼即可將功能豐富的圖表包整合到應用中。 這兩個程式庫結合在一起,使開發者可以使用現代AI技術,並以PDF形式可靠地保存結果。

Darrius Serrant
全端軟體工程師(WebOps)

Darrius Serrant擁有邁阿密大學的電腦科學學士學位,並在Iron Software擔任全端WebOps行銷工程師。從小就對程式設計有興趣,他認為計算既神秘又易於理解,成為創意和問題解決的完美媒介。

在Iron Software,Darrius喜歡創造新事物並簡化複雜的概念,使其更易於理解。作為我們的常駐開發人員之一,他還志願教學,將他的專業知識傳授給下一代。

對Darrius來說,他的工作是有意義的,因為它有價值且對社會有真正的影響。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話