Comments (6)
@ruwaifatahir instead of this
return NextResponse.json({ result });
try this
return new Response(response, { headers: { 'content-type': 'image/jpeg' }, }) }
from huggingface.js.
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.
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:
- 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 usesrc/
directory? ... No / Yes
√ Would you like to use App Router? (recommended) ... No / Yes
√ Would you like to customize the default import alias? ... No / Yes
- 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"
}
- 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" } });
}
-
Start dev server:
npm run dev
. -
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.
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.
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.
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)
- [gguf types] Add missing types & make existing types stronger HOT 1
- [gguf] add support for legacy gguf v1 HOT 1
- [Conversation Widget] Bug on examples
- Finalize image-feature-extraction support HOT 4
- [Inference] Support for Messages API OpenAI API specs
- [Feature Request] Model inspector for other formats HOT 4
- Missing Type From the Inference Package HOT 1
- [Conversational] Property conversational does not exist on type HfInference HOT 3
- Safetensors sharded model inspector does not work in subdirs HOT 8
- Is 404 console.error expected for `fileExists ` HOT 4
- Sharded GGUF in subdir HOT 3
- fix `pipelineSnippet` for repos with custom pipelines HOT 2
- GGUF Sharded model metadata display might have a memory leak HOT 6
- GGUF: missing `split.no` metadata HOT 6
- [Question] What is the correct way to access commit diff results via http? HOT 1
- [ASR Widget] “Browse for file” is unresponsive HOT 1
- Inference API widget does not work anymore for token classification of POS HOT 3
- [Widget] "Model not loaded yet" error on page load
- Rm ArrayBuffer.resize polyfill when Firefox supports it by default HOT 4
- Feature Request: Get Commits List / Commits History by Repository ID using @huggingface/hub HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from huggingface.js.