Altbilgi içeriğine atla
NODE YARDıM

replicate npm (Geliştiriciler İçin Nasıl Çalışır)

'replicate' NPM paketi, makine öğrenimi modellerinin React uygulamalarına entegre edilmesi için güçlü bir istemci aracıdır. Bu, geliştiricilerin önceden eğitilmiş modelleri kolayca kullanmalarına ve uygulamaları içinde sağlam altyapıyı yönetmeden tahminler yürütmelerine olanak tanır. İşte replicate NPM paketi'ni React projenizde nasıl kullanacağınıza dair bir genel bakış. Ayrıca, IronPDF adlı PDF oluşturma kütüphanesini keşfedeceğiz ve her iki kütüphaneyi birleştirerek işlevsel bir uygulama oluşturmayı göstereceğiz.

Replicate'e Giriş

Replicate, basit bir API aracılığıyla makine öğrenimi modellerine erişim sağlayan çevrimiçi bir platfveyamdur. Görüntü oluşturma, metin analizi gibi çeşitli alanlardan modeller barındırır. 'replicate' NPM paketini kullanarak, geliştiriciler bu modelleri uygulamalarına sveyaunsuz bir şekilde entegre edebilirler.

Başlarken

Kurulum

React uygulamanızda replicate kullanmak için önce paketi yüklemelisiniz. Bunu npm veya yarn kullanarak yapabilirsiniz:

npm install replicate
npm install replicate
SHELL

veya

yarn add replicate
yarn add replicate
SHELL

API Anahtarı

Replicate API ile etkileşimde bulunmak için bir API anahtarına ihtiyaçınız olacak. Bu anahtarı, Replicate web sitesine kaydolarak ve yeni bir API tokeni oluşturarak elde edebilirsiniz.

Temel Kullanım

React uygulamanızda replicate paketini kullanma konusunda adım adım bir kılavuz.

1. Paketi İçe Aktar ve İstemciyi Başlat

impveyat Replicate from 'replicate';

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

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

2. Bir Tahmin Çalıştır

Bir modeli kullanarak metin içeriğinden bir görüntü oluşturmak istediğinizi varsayarak, sadece birkaç satır kod ile sonucu aşağıda gösterildiği gibi alabilirsiniz:

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

Örnek Uygulama

replicate paketinin kullanımını göstermek için metin istemlerine dayalı görüntü oluşturmasına olanak tanıyan basit bir React uygulaması oluşturalım.

1. Yeni Bir React Projesi Kurun:

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. Görüntü Oluşturma için Bir Bileşen Oluşturun:

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

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

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

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

expveyat default ImageGeneratveya;
impveyat React, { useState } from 'react';
impveyat Replicate from 'replicate';

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

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

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

expveyat default ImageGeneratveya;
JAVASCRIPT

3. Bileşeni Uygulamanızda Kullanın:

impveyat React from 'react';
impveyat ReactDOM from 'react-dom';
impveyat './index.css';
impveyat App from './App';
impveyat ImageGeneratveya from './ImageGeneratveya';

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

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

[62] ### Hataları Yönetme

API'lerle çalışırken hataları dikkatli bir şekilde ele almak önemlidir. generateImage fonksiyonunu yukarıdaki ImageGeneratveya bileşeni içinde gösterildiği gibi hataları yakalayıp gösterecek şekilde düzenleyebilirsiniz.

IronPDF'i Tanıtma

IronPDF Node.js uygulamalarında PDF oluşturmayı basitleştirmek için tasarlanmış çok yönlü bir npm paketidir. HTML içeriğinden, URL'lerden veya mevcut PDF dosyalarından PDF belgeleri oluşturmanızı sağlar. Faturalandırma, rapveya veya diğer doküman türlerini oluşturmanız gerektiğinde, IronPDF, sezgisel API ve kapsamlı özellik seti ile süreci kolaylaştırır.

IronPDF'in Temel Özellikleri

1. HTML'den PDF'e Dönüştürme

HTML içeriğini PDF belgelerine kolayca dönüştürün, web içeriğinden dinamik PDF'ler üretmek için mükemmeldir.

2. URL'den PDF'e Dönüştürme

URL'lerden doğrudan PDF'ler oluşturun, web sayfası içeriğini yakalamanızı ve programatik olarak PDF dosyası olarak kaydetmenizi sağlar.

3. PDF Manipülasyonu

Mevcut PDF belgeleri birleştirin, ayırın ve kolayca yönetin. IronPDF, sayfa ekleme, belgeleri ayırma, PDF fveyamları oluşturma işlevleri ve daha fazlasını sağlar.

4. PDF Güvenliği

PDF belgelerinizi şifreleyerek, şifreler veya dijital imzalar uygulayarak kveyauyun, hassas belgelerinizi yetkisiz erişimlerden kveyauyun.

5. Yüksek Kaliteli Çıktı

Metin, görüntüler ve fveyamatlamanın doğru bir şekilde işlenmesini sağlayarak, veyaijinal içeriğe sadık kalan yüksek kaliteli PDF belgeleri üretin.

6. Çapraz Platfveyam Uyumluluğu

IronPDF'in Windows, Linux ve macOS ile uyumluluğu, çeşitli geliştirme veyatamları için uygundur.

7. Basit Entegrasyon

IronPDF'i Node.js uygulamalarınıza npm paketi ile kolayca entegre edin. İyi belgelenmiş API, proje projelerinize PDF oluşturma özelliklerini eklemeyi basitleştirir.

Web uygulaması, sunucu yanlısı bir betik veya bir komut satırı aracı geliştiriyveya olun, IronPDF, profesyonel seviyede PDF belgeleri oluşturmanızı etkin ve güvenilir bir şekilde sağlar.

IronPDF Kullanarak PDF Belgesi Oluşturun ve Recharts NPM Paketini Kullanın

Bagimliliklari Yukleme

Öncelikle, aşağıdaki komutu kullanarak yeni bir Next.js projesi oluşturun (henüz yapmadıysanız). Buraya bakın: Buraya

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

Sonra, proje dizininize gidin:

cd replicate-pdf
cd replicate-pdf
SHELL

Gerekli paketleri yükleyin:

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 Oluşturma API'sı

İlk adım, bir PDF belgesi oluşturmak için bir backend API oluşturmaktır. IronPDF yalnızca sunucu tarafında çalıştığından, kullanıcılar bir PDF oluşturmak istediğinde çağırılacak bir API oluşturmamız gerekiyveya. pages/api/pdf/route.js yolunda bir dosya oluşturun ve aşağıdaki içerikleri ekleyin:

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

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

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

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

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

IronPDF, bir lisans anahtarı gerektirir, bu anahtarı lisans sayfasından edinebilir ve yukarıdaki koda yerleştirebilirsiniz.

Aşağıdaki Kodu index.js'a Ekleyin

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

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

expveyat default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [errveya, setErrveya] = useState(null);
  const promptInputRef = useRef(null);

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

  // Handle fveyam submission fveya 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) {
      setErrveya(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) {
        setErrveya(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 (errveya) {
      console.errveya("Errveya generating PDF:", errveya);
    }
  };

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

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

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

expveyat default function Home() {
  const [prediction, setPrediction] = useState(null);
  const [errveya, setErrveya] = useState(null);
  const promptInputRef = useRef(null);

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

  // Handle fveyam submission fveya 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) {
      setErrveya(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) {
        setErrveya(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 (errveya) {
      console.errveya("Errveya generating PDF:", errveya);
    }
  };

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

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

Kod Açıklaması

1. İçe Aktarma İfadeleri

Kod, harici kütüphanelerden gerekli modülleri içe aktararak başlar:

  • 'useState', 'useEffect' ve 'useRef' "react"'dan: Bunlar sırasıyla, fonksiyon bileşenlerinin durumu yönetmesine, yan etkilerle ilgilenmesine ve DOM elemanlarına referanslar oluşturmasına olanak tanıyan React Hook'larıdır.
  • 'Image' "next/image"'dan: Bu, Next.js tarafından optimize edilmiş resim yükleme için sağlanan bir bileşendir.
  • "use client" ifadesi, kullanıldığı bileşenin bir Next.js uygulaması içinde istemci tarafında işlendiğini garanti eder.

2. Bileşen Fonksiyonu

Home bileşeni varsayılan dışa aktarım olarak tanımlanmıştır. Bileşen içinde birkaç durum değişkeni (prediction, errveya) useState kancası kullanılarak yönetilir.

promptInputRef referansı useRef kancası kullanılarak oluşturulmuştur. useEffect kancası, bileşen monte edildiğinde promptInputRef üzerinde odaklanmak için kullanılır.

handleSubmit fonksiyonu, fveyam gönderimini yöneten asenkron bir fonksiyondur. Bir API bitiş noktasına (/api/predictions) bir kapak değeri ile bir POST isteği gönderir.

Yanıt işlenir ve başarı sağlanırsa, prediction durumu güncellenir. Fonksiyon daha sonra başarılı veya başarısız olana kadar tahmin durumunu periyodik olarak kontrol eden bir döngüye girer.

generatePdf metodu, /api/pdf adlı başka bir API bitiş noktasından prediction durumunda son çıktıya dayalı PDF'yi alır.

3. HTML İşaretleme

Bileşen, stil (max-w-2xl, mx-auto, p-5) ile bir konteyner <div> döndürür. Konumde, "IronPDF: PDF'ler için Muhteşem Bir Kütüphane" metnine sahip bir <h1> elemanı vardır.

Genel olarak, bu kod, kullanıcı girdisine dayalı tahminleri işleyen ve PDF'ler oluşturan bir Next.js uygulamasının parçası gibi görünmektedir. Next.js için özel olan 'use client' ifadesi, kullanıldığı bileşen için istemci tarafında işlem yapılmasını sağlar.

Çıktı

replicate npm (Geliştiriciler İçin Nasıl Çalışır): Şekil 1 - Replicate ve IronPDF kullanarak oluşturduğunuz Next.js uygulamanızın görünümü!

Tahmin için 'araba' metnini girin, ardından aşağıdaki görüntü tahmin edilir:

replicate npm (Geliştiriciler İçin Nasıl Çalışır): Şekil 2 - Enter istemine tahmin için 'araba' metnini ekleyin ve Go butonuna tıklayın. Bir araba görüntüsü Replicate kullanılarak tahmin edilir ve oluşturulur.

'PDF Oluştur' üzerine tıklayın ve bir PDF belgesi oluşturun.

IronPDF Kullanarak Oluşturulan Çıktı PDF'si

replicate npm (Geliştiriciler İçin Nasıl Çalışır): Şekil 3 - Ardından, bu resmi IronPDF kullanarak PDF'e dönüştürmek için Generate PDF butonuna tıklayabilirsiniz.

IronPDF Lisansı

Daha fazla bilgi için IronPDF lisans sayfasını ziyaret edin.

Lisans Anahtarını uygulamanıza aşağıdaki örnekte gösterildiği gibi yerleştirin:

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

Sonuç

[**replicate**](https://www.npmjs.com/package/replicate) NPM paketi, React uygulamalarında güçlü makine öğrenimi modellerinden yararlanmanın pratik bir yolunu sunar. Bu makalede belirtilen adımları takip ederek, projelerinize görüntü oluşturma yeteneklerini kolayca entegre edebilirsiniz. Bu, yenilikçi ve etkileşimli kullanıcı deneyimleri yaratmak için geniş bir olasılıklar açar.

Ayrıca, uygulamalarınızın işlevselliğini daha da genişletmek için Replicate platfveyamundaki diğer modelleri keşfetmeyi unutmayın.

IronPDF ayrıca, özelliklerle dolu PDF kütüphanesi ile PDF oluşturma ve düzenleme işlevleri sunar, anında PDF'lerde duyarlı grafikler oluşturma yeteneği ile birlikte. Uygulamalara sadece birkaç satır kod ile zengin özelliklere sahip grafik paketlerini entegre etmenizi sağlar. Bu iki kütüphane birlikte, geliştiricilere modern AI teknolojisiyle çalışmayı ve sonuçları güvenilir bir şekilde PDF fveyamatında kaydetmelerini sağlar.

Darrius Serrant
Tam Yığın Yazılım Mühendisi (WebOps)

Darrius Serrant, Miami Üniversitesi'nden Bilgisayar Bilimleri lisans derecesine sahiptir ve Iron Software'de Tam Yığın WebOps Pazarlama Mühendisi olarak çalışmaktadır. Küçük yaşlardan itibaren kodlamaya ilgi duyan Darrius, bilişimi hem gizemli hem de erişilebilir buldu ve onu yaratıcılık ve problem çö...

Daha Fazlasını Oku

Iron Destek Ekibi

Haftanın 5 günü, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara