Giter Club home page Giter Club logo

Comments (6)

MuhammadUsamaAwan avatar MuhammadUsamaAwan commented on May 26, 2024 1

@ruwaifatahir instead of this

return NextResponse.json({ result });

try this

return new Response(response, { headers: { 'content-type': 'image/jpeg' }, }) }

from huggingface.js.

Bilalkhan4086 avatar Bilalkhan4086 commented on May 26, 2024

Yeah I also got the same issue

here is my code for api

import { NextRequest, NextResponse } from "next/server";
import { HfInference } from "@huggingface/inference";

const HF_ACCESS_TOKEN = "hf_...";

export async function GET(request: NextRequest) {
const inference = new HfInference(HF_ACCESS_TOKEN);
console.log("first");
const text = request.nextUrl.searchParams.get("text");
console.log("text", text);
if (!text) {
return NextResponse.json(
{
error: "Missing text parameter",
},
{ status: 400 }
);
}
// Get the classification pipeline. When called for the first time,
// this will load the pipeline and cache it for future use.
let rawImg;
try {
rawImg = await inference.textToImage({
model: "stabilityai/stable-diffusion-2",
inputs: text,
parameters: {
negative_prompt: "blurry",
},
});
console.log("objectURL");
} catch (error) {
console.log("error", error);
}
// Actually perform the classification

return new Response(rawImg, { headers: { "content-type": "image/jpeg" } });
}

from huggingface.js.

vvmnnnkv avatar vvmnnnkv commented on May 26, 2024

Hi @ruwaifatahir @Bilalkhan4086

I tried to reproduce the problem with a new next.js app, but couldn't.
Could you check how different your setup is, specifically @huggingface/inference package version in your project?

Here're my steps:

  1. Create new app:
    npx create-next-app@latest next-hf

√ Would you like to use TypeScript? ... No / Yes
√ Would you like to use ESLint? ... No / Yes
√ Would you like to use Tailwind CSS? ... No / Yes
√ Would you like to use src/ directory? ... No / Yes
√ Would you like to use App Router? (recommended) ... No / Yes
√ Would you like to customize the default import alias? ... No / Yes

  1. Enter next-hf folder and install the latest hf/inference package:
    npm i @huggingface/inference

Here're package versions I've got in package.json as a result:

  "dependencies": {
    "@huggingface/inference": "^2.6.1",
    "@types/node": "20.6.2",
    "@types/react": "18.2.21",
    "@types/react-dom": "18.2.7",
    "next": "13.4.19",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "typescript": "5.2.2"
  }
  1. Add simple src/app/api/route.ts file for route handler:
import { NextResponse } from "next/server";
import { HfInference } from "@huggingface/inference";

const HF_ACCESS_TOKEN = "hf_<my token>";

export async function GET(request: NextRequest) {
  const prompt = request.nextUrl.searchParams.get("prompt");
  const hf = new HfInference(HF_ACCESS_TOKEN);
  const result = await hf.textToImage({
    inputs: prompt,
    model: "stabilityai/stable-diffusion-2",
    parameters: {
      negative_prompt: "blurry",
    },
  });
  return new Response(result, { headers: { "content-type": "image/jpeg" } });
}
  1. Start dev server: npm run dev.

  2. Open URL in the browser to trigger api route, e.g.
    http://localhost:3000/api?prompt=green%20island%20in%20the%20ocean
    (The generated image loads)

from huggingface.js.

ruwaifatahir avatar ruwaifatahir commented on May 26, 2024

Hi @vvmnnnkv, Here is my package.json file

  "dependencies": {
    "@huggingface/inference": "^2.6.1",
    "@types/node": "20.5.6",
    "@types/react": "18.2.21",
    "@types/react-dom": "18.2.7",
    "autoprefixer": "10.4.15",
    "eslint": "8.48.0",
    "eslint-config-next": "13.4.19",
    "next": "13.4.19",
    "postcss": "8.4.28",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "tailwindcss": "3.3.3",
    "typescript": "5.2.2"
  } 

from huggingface.js.

ruwaifatahir avatar ruwaifatahir commented on May 26, 2024

Hi @Bilalkhan4086, I've found a workaround to generate an image from the API route.

You can make a direct call to hugging face endpoints from api route.

//src/app/api/creation/route.ts

import { NextResponse } from "next/server";
import { streamToBuffer } from "./utils";

// Define the URL and access token for the external API
const API_URL =
  "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2";

const HF_ACCESS_TOKEN = `Bearer ${process.env.HF_ACCESS_TOKEN}`;

// Define the payload type for POST requests
interface PostRequestPayload {
  prompt: string;
}

/**
 * Handle POST requests.
 * @param request - The incoming Request object.
 * @returns A NextResponse object containing the external API's response.
 */
export async function POST(request: Request): Promise<NextResponse> {
  // Parse the incoming request payload

  try {
    const { prompt }: PostRequestPayload = await request.json();

    // Fetch data from the external API
    const externalResponse = await fetch(API_URL, {
      headers: {
        Authorization: HF_ACCESS_TOKEN,
      },
      method: "POST",
      body: JSON.stringify({
        inputs: prompt,
        parameters: {
          negative_prompt: "ugly, disfigured, deformed",
        },
      }),
    });

    // Read the body of the external response as a blob
    const blob = await externalResponse.blob();

    // Convert the blob to a Buffer
    const bufferData = await streamToBuffer(blob.stream());

    // Create a new NextResponse object with the relevant properties from the external response
    const response = new NextResponse(bufferData, {
      status: externalResponse.status,
      statusText: externalResponse.statusText,
      headers: Object.fromEntries(externalResponse.headers),
    });

    return response;
  } catch (error) {
    console.error(error);
    return new NextResponse("Internal server error", { status: 500 });
  }
}
//src/app/api/creation/utils.ts

/**
 * Convert a ReadableStream to a Buffer.
 * @param readableStream - The ReadableStream to convert.
 * @returns A Buffer containing the stream's data.
 */
export async function streamToBuffer(
  readableStream: ReadableStream<Uint8Array>
): Promise<Buffer> {
  const chunks: Uint8Array[] = [];
  const reader = readableStream.getReader();

  let done = false;
  let value: Uint8Array | undefined;

  while (!done) {
    ({ done, value } = await reader.read());
    if (value) {
      chunks.push(value);
    }
  }

  return Buffer.concat(chunks);
}

from huggingface.js.

vvmnnnkv avatar vvmnnnkv commented on May 26, 2024

Hi @ruwaifatahir
I've used your package.json deps with new next.js app but still can't reproduce the problem.
It would be interesting to investigate your case, maybe you can share your code?

Also, if you just want to avoid type error, you can try to use generic hf.request method that doesn't check returned types:

  const result = await hf.request({
    inputs: prompt,
    model: "stabilityai/stable-diffusion-2",
    parameters: {
      negative_prompt: "blurry",
    },
  });

from huggingface.js.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.