ساختن پلتفرم AI Sticker Maker با AI/ML API، Next.js، React و Tailwind CSS با استفاده از OpenAI GPT-4o و DALL·E 3 Models.
Summarize this content to 400 words in Persian Lang حوصله ام سر رفت شما هم؟ 😴
هوم…🤔
در مورد ایجاد یک استیکر ساز هوش مصنوعی پلت فرم؟ صادقانه بگویم، این یک ایده واقعا جالب است. و هی، ما حتی ممکن است با ادغام Stripe به عنوان یک ارائه دهنده پرداخت، مقداری سود به دست آوریم. 💰 آره چرا که نه؟
بنابراین، بیایید شروع کنیم. یا حداقل به آن ضربه بزنید! 🚀
معرفی سریع 🧐
اول از همه، بیایید یک شبه کد را ترسیم کنیم یا یک طرح بسازیم (مگر اینکه سازنده واقعی باشید که از باسن کد می نویسید). باید چیزی شبیه به این باشد:
کاربر یک اعلان وارد می کند (توضیح متنی از نحوه ظاهر برچسب).
ما استیکر ساز هوش مصنوعی یک برچسب واقعا زیبا ایجاد می کند. تا-دا! 🥳
آسان-پیزی، اینطور نیست؟ 🍋
اما صبر کنید، اجازه دهید من توضیح دهم. ما قصد داریم از دو مدل استفاده کنیم: GPT-4o و از و 3، هر دو از OpenAI. آنها هیپ هستند، واقعا! 🔥
ما از AI/ML API، که دسترسی به بیش از 200 مدل هوش مصنوعی را با یک API فراهم می کند. بگذارید به طور خلاصه در مورد آن برای شما بگویم.
با AI/ML API آشنا شوید 🤖👇
AI/ML API یک پلتفرم تغییر دهنده بازی برای توسعه دهندگان و کارآفرینان SaaS است که به دنبال ادغام قابلیت های پیشرفته هوش مصنوعی در محصولات خود هستند. این یک نقطه دسترسی به بیش از حد را ارائه می دهد 200 مدل پیشرفته هوش مصنوعی، از NLP گرفته تا بینایی کامپیوتری را پوشش می دهد.
ویژگی های کلیدی برای توسعه دهندگان:
کتابخانه مدل گسترده: بیش از 200 مدل از پیش آموزش دیده برای نمونه سازی و استقرار سریع. 📚
گزینه های سفارشی سازی: مدلهای تنظیم دقیق متناسب با مورد خاص شما. 🎯
ادغام دوستدار توسعه دهندگان: API ها و SDK های RESTful برای ادغام یکپارچه در پشته شما. 🛠️
معماری بدون سرور: روی کدنویسی تمرکز کنید نه مدیریت زیرساخت. ☁️
شروع کنید برای رایگان (0 دلار آمریکا): aimlapi.com 🆓
Deep Dive into AI/ML API Documentation (بسیار مفصل، نمی توانم بیشتر موافقم): docs.aimlapi.com 📖
Tech Stack Ingredients 🥘
استفاده خواهیم کرد TypeScript، Next.js، واکنش نشان دهید، و Tailwind CSS برای ساخت و طراحی پلتفرم AI Sticker Maker ما.
TypeScript فقط یک زبان برنامه نویسی است – اما یک زبان واقعا عالی! 📝
Next.js چارچوب React برای وب است. این ما را قادر میسازد تا برنامههای وب با کیفیت بالا را با قدرت اجزای React ایجاد کنیم. 🌐
واکنش نشان دهید کتابخانه ای برای رابط های کاربری وب و بومی است. 🖥️
Tailwind CSS برای یک ظاهر طراحی شده بهترین است – فقط هر چیزی را که می خواهید بسازید، به طور جدی. 🎨
این فقط یک نمای کلی از آنچه قرار است استفاده کنیم بود. برای کسب اطلاعات بیشتر در مورد هر یک از آنها در اینجا احساس راحتی کنید:
TypeScript: typescriptlang.org 🦕
Next.js: nextjs.org ⏭️
واکنش نشان دهید: react.dev ⚛️
Tailwind CSS: tailwindcss.com 🌬️
آشپزی شروع شد 🍳
دستمان را کثیف کنیم! ابتدا یک پوشه ایجاد کنید. ترمینال خود را باز کنید و این را وارد کنید:
mkdir aiml-tutorial
cd aiml-tutorial
اکنون، بیایید یک برنامه Next.js جدید ایجاد کنیم:
npx create-next-app@latest
از شما چند سوال خواهد پرسید:
✔ نام پروژه شما چیست؟ در اینجا، شما باید نام برنامه خود را وارد کنید. به عنوان مثال: aistickermaker. برای بقیه سوالات به سادگی ضربه بزنید enter.
در اینجا چیزی است که خواهید دید:
✔ 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 your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for `next dev`? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes
برای نکته: با خیال راحت انتخاب کنید Yes یا No بر اساس ترجیحات شما من قضاوت نمی کنم! 😜
بیایید پروژه را با VSCode باز کنیم:
code .
اکنون، Visual Studio Code باید مستقیماً با این برنامه راه اندازی شود. زمان شروع کدنویسی است! 💻
پیاده سازی API ها 🛠️
اول از همه، اجازه دهید APIهایی را برای تقویت درخواست کاربر و تولید برچسب ایجاد کنیم. برو به app پوشه، سپس یک پوشه جدید به نام ایجاد کنید apiو در داخل آن دو پوشه جدید ایجاد کنید: enhancePrompt و generateSticker. برای هر یک، یک را ایجاد کنید route.ts فایل
را enhancePrompt نقطه پایان 🧙♂️
حال، بیایید با آن شروع کنیم enhancePrompt نقطه پایانی باز کنید route.ts داخل enhancePrompt پوشه و کد زیر را وارد کنید:
import { NextResponse } from ‘next/server’;
const systemPrompt = `
You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user’s input.
Instructions:
Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.
Example: If the user says “A girl with pink hair,” elaborate by adding features like “short wavy pink hair with soft, pastel hues.”
Style & Theme:
Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like “adorable,” “cartoonish,” “sticker-friendly,” or “chibi-like” to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:
If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:
Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:
Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, “A light pastel background with small, floating hearts” or “Holding a tiny, sparkling star.”
Colors:
Emphasize the color scheme based on the user’s description, making sure it’s consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:
Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:
The tone should be light, imaginative, and fun, matching the playful nature of stickers.
Example:
User Input:
“A girl with pink hair wearing a hoodie.”
Enhanced Prompt:
“An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look.”
`;
export async function POST(request: Request) {
try {
const { userPrompt } = await request.json();
console.log(“/api/enhancePrompt/route.ts userPrompt: “, userPrompt);
// Make the API call to the external service
const response = await fetch(‘https://api.aimlapi.com/chat/completions’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
},
body: JSON.stringify({
model: ‘gpt-4o-mini’,
messages: [
{
role: ‘system’,
content: systemPrompt
},
{
role: ‘user’,
content: userPrompt
}
]
})
});
console.log(“response: “, response);
if (!response.ok) {
// If the API response isn’t successful, return an error response
return NextResponse.json({ error: “Failed to fetch completion data” }, { status: response.status });
}
const data = await response.json();
console.log(“data: “, data);
const assistantResponse = data.choices[0]?.message?.content || “No response available”;
// Return the assistant’s message content
return NextResponse.json({ message: assistantResponse });
} catch (error) {
console.error(“Error fetching the data:”, error);
return NextResponse.json({ error: “An error occurred while processing your request.” }, { status: 500 });
}
}
در اینجا اعلان جدا شده است:
You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user’s input.
Instructions:
Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.
Example: If the user says “A girl with pink hair,” elaborate by adding features like “short wavy pink hair with soft, pastel hues.”
Style & Theme:
Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like “adorable,” “cartoonish,” “sticker-friendly,” or “chibi-like” to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:
If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:
Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:
Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, “A light pastel background with small, floating hearts” or “Holding a tiny, sparkling star.”
Colors:
Emphasize the color scheme based on the user’s description, making sure it’s consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:
Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:
The tone should be light, imaginative, and fun, matching the playful nature of stickers.
Example:
User Input:
“A girl with pink hair wearing a hoodie.”
Enhanced Prompt:
“An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look.”
اینجا چه خبر است؟ 🤔
واردات NextResponse: برای رسیدگی به پاسخ های HTTP ما به آرامی.
تعریف کردن POST تابع: اینجاست که وقتی کسی به این نقطه پایانی میرسد، جادو اتفاق میافتد.
واکشی userPrompt: ما در حال گرفتن درخواست ارائه شده توسط کاربر هستیم.
فراخوانی API AI/ML API: ما درخواستی برای بهبود درخواست کاربر با استفاده از GPT-4o داریم.
رسیدگی به پاسخ ها: بررسی می کنیم که آیا پاسخ درست است، داده ها را تجزیه می کنیم و پاسخ دستیار را استخراج می کنیم.
رسیدگی به خطا: چون هیچکس دوست ندارد اشتباهات کنترل نشده مهمانی را خراب کند.
در اینجا یک مثال واقعی از این است که چگونه هوش مصنوعی اعلان کاربر را افزایش می دهد. 🐼🍦🌈
شما فقط یک اعلان وارد کردید:
A cute panda eating ice cream under a rainbow
هوش مصنوعی آن را تقویت می کند تا جزئیات بیشتری داشته باشد و از نظر بصری غنی تر شود. در نتیجه، شما باید پاسخی مانند:
An adorable, chibi-like panda with big, sparkling eyes and a joyful expression, savoring a colorful scoop of ice cream. The panda is fluffy and round, with classic black-and-white markings, sitting contentedly. The ice cream cone features vibrant, swirling flavors in pastel pink, mint green, and sunny yellow. Above, a playful, cartoonish rainbow arcs across a soft blue sky, adding a cheerful splash of color. The design is sticker-friendly with minimalistic lines and soft shading, ensuring a cute and delightful aesthetic perfect for capturing the joyful scene.
خوب، بیایید دوباره به داخل دیگ کد شیرجه بزنیم و به پختن برچسب AI خود ادامه دهیم! 🍲
را generateSticker نقطه پایان 🖼️
بنابراین، ما خودمان را داریم enhancePrompt نقطه پایانی به خوبی می جوشد. وقت آن است که چیزها را با آن چاشنی کنید generateSticker نقطه پایانی سر به سمت api/generateSticker پوشه و باز کنید route.ts. هر چیزی را که در آنجا هست (احتمالاً هیچ چیز) با این کد جدید جایگزین کنید:
// api/generateSticker/route.ts
import { NextResponse } from ‘next/server’;
export async function POST(request: Request) {
try {
const { userPrompt } = await request.json();
console.log(“/api/generateSticker/route.ts userPrompt: “, userPrompt);
// Make the API call to the external service
const response = await fetch(‘https://api.aimlapi.com/images/generations’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
},
body: JSON.stringify({
provider: ‘openai’,
prompt: userPrompt,
model: ‘dall-e-3’,
n: 1,
quality: ‘hd’,
response_format: ‘url’,
size: ‘1024×1024’,
style: ‘vivid’
})
});
console.log(“response: “, response);
if (!response.ok) {
// If the API response isn’t successful, return an error response
return NextResponse.json({ error: “Failed to fetch completion data” }, { status: response.status });
}
const data = await response.json();
console.log(“data: “, data);
const assistantResponse = data.data[0]?.url || “No response available”;
console.log(“assistantResponse: “, assistantResponse);
// Return the assistant’s message content
return NextResponse.json({ message: assistantResponse });
} catch (error) {
console.error(“Error fetching the data:”, error);
return NextResponse.json({ error: “An error occurred while processing your request.” }, { status: 500 });
}
}
اینجا چه خبر است؟ 🤔
واردات NextResponse: برای رسیدگی به پاسخ های HTTP ما به آرامی.
تعریف کردن POST تابع: این جایی است که وقتی کسی به این نقطه پایانی می رسد، جادو اتفاق می افتد.
واکشی userPrompt: ما در حال گرفتن درخواست ارائه شده توسط کاربر هستیم.
فراخوانی API AI/ML API: ما درخواستی برای ایجاد یک تصویر بر اساس اعلان با استفاده از DALL·E 3 داریم.
رسیدگی به پاسخ ها: بررسی می کنیم که آیا پاسخ درست است، داده ها را تجزیه می کنیم و URL تصویر را استخراج می کنیم.
رسیدگی به خطا: چون هیچکس دوست ندارد اشتباهات کنترل نشده مهمانی را خراب کند.
بیایید دستور بالا را با panda در عمل! 🚀
اینم برچسب پاندای ناز ما! 🐼🍦🌈
نمونه های دیگر 😍
اعلان:
A girl with short white+grey hair wearing a oversize shirt
اعلان:
A girl with short black+pink hair wearing a oversize pink shirt
به نظر می رسد، واقعا WOW! 🤩
ما نیاز به یک فرانتند داریم، بچه ها! 😅
ساخت Frontend 🎨
زمان برای قرار دادن چهره در برنامه ما! بیایید یک رابط کاربری ایجاد کنیم که در آن کاربران بتوانند درخواست خود را وارد کنند و یک برچسب جدید براق دریافت کنند.
را page.tsx فایل 📄
حرکت به app/page.tsx و با کد زیر آن را به روز کنید:
// app/page.tsx
‘use client’;
import Image from “next/image”;
import { useState } from ‘react’;
import { faArrowUp, faDownload, faTimes } from ‘@fortawesome/free-solid-svg-icons’;
import { FontAwesomeIcon } from ‘@fortawesome/react-fontawesome’;
import Notification from ‘./utils/notify’;
import { Analytics } from “@vercel/analytics/react”
export default function Home() {
const [notification, setNotification] = useState<{ message: string; type: ‘error’ | ‘success’ | ‘info’ } | null>(null); // notification message
const [loading, setLoading] = useState(false);
const [prompt, setPrompt] = useState(”);
const [stickerUrl, setStickerUrl] = useState(“”);
const loader = () => (
<svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” viewBox=”0 0 24 24″>
<circle cx={4} cy={12} r={3} fill=”currentColor”>
<animate id=”svgSpinners3DotsScale0″ attributeName=”r” begin=”0;svgSpinners3DotsScale1.end-0.25s” dur=”0.75s” values=”3;.2;3″ />
</circle>
<circle cx={12} cy={12} r={3} fill=”currentColor”>
<animate attributeName=”r” begin=”svgSpinners3DotsScale0.end-0.6s” dur=”0.75s” values=”3;.2;3″ />
</circle>
<circle cx={20} cy={12} r={3} fill=”currentColor”>
<animate id=”svgSpinners3DotsScale1″ attributeName=”r” begin=”svgSpinners3DotsScale0.end-0.45s” dur=”0.75s” values=”3;.2;3″ />
</circle>
</svg>
);
const enhanceUserPrompt = async (prompt: string) => {
setNotification({ message: ‘Enhancing user prompt…’, type: ‘info’ });
// Make the API call to the /api/enhancePrompt route and return the enhanced prompt
const response = await fetch(‘/api/enhancePrompt’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({ userPrompt: prompt }),
});
if (!response.ok) {
throw new Error(‘Failed to fetch completion data’);
}
const data = await response.json();
return data.message;
};
const generateCuteSticker = async (prompt: string) => {
setNotification({ message: ‘Generating cute sticker…’, type: ‘info’ });
// Make the API call to the /api/generateSticker route and return the generated sticker URL
const response = await fetch(‘/api/generateSticker’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({ userPrompt: prompt }),
});
if (!response.ok) {
throw new Error(‘Failed to fetch completion data’);
}
const data = await response.json();
return data.message;
};
const generateSticker = async () => {
if (!prompt) return;
setLoading(true);
setNotification({ message: ‘Processing request…’, type: ‘info’ });
try {
// Enhance user prompt
const enhancedPrompt = await enhanceUserPrompt(prompt);
if (!enhancedPrompt) {
setNotification({ message: ‘Failed to enhance user prompt.’, type: ‘error’ });
return;
}
// Generate cute sticker
const sticker = await generateCuteSticker(enhancedPrompt);
if (!sticker) {
setNotification({ message: ‘Failed to generate cute sticker.’, type: ‘error’ });
return;
}
setStickerUrl(sticker);
console.log(‘Sticker URL:’, sticker);
setNotification({ message: ‘Cute sticker generated successfully!’, type: ‘success’ });
} catch (error) {
console.error(‘An unexpected error occurred:’, error);
setNotification({ message: ‘An unexpected error occurred.’, type: ‘error’ });
} finally {
setLoading(false);
}
};
const handleDownload = () => {
if (!stickerUrl) return;
const link = document.createElement(‘a’);
link.href = stickerUrl;
link.download = ‘cute-sticker.png’; // You can set a default filename
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const handleClose = () => {
setStickerUrl(“”);
setPrompt(“”);
};
return (
<div className=”flex flex-col items-center justify-center min-h-screen text-white p-4 bg-[#212121e6]”>
<Analytics />
{notification && (
<Notification
message={notification.message}
type={notification.type}
onClose={() => setNotification(null)}
/>
)}
<div className=”mb-6 inline-flex justify-center text-2xl font-semibold leading-9″>
<h1>Let’s Generate Cutesy AI Sticker!</h1>
</div>
<div className=”lg:w-[60%] w-full mx-auto flex items-center p-2 mb-8 shadow-lg gap-4 bg-[#2e2e2e] rounded-full”>
<input
type=”text”
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder=”A girl with short pink hair wearing a oversize hoodie…”
className=”placeholder:text-[#aeaeae] bg-transparent focus:outline-none text-white outline-none w-full px-4″
disabled={loading}
/>
<button
disabled={prompt === ” || loading}
onClick={generateSticker}
className={`flex items-center justify-center w-12 h-10 rounded-full shadow ${
prompt === ” ? ‘cursor-not-allowed bg-[#4e4e4e] text-black’ : ‘cursor-pointer bg-[#eeeeee] text-black’}`}
>
{!loading
? <FontAwesomeIcon icon={faArrowUp} />
: <span className=’flex justify-center items-center text-black text-xl’>{loader()}</span>
}
</button>
</div>
{/* Modal */}
{stickerUrl && (
<div className=”fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50″>
<div className=”bg-[#2e2e2e] rounded-md p-4 relative w-11/12 max-w-md”>
{/* Download Button */}
<button
onClick={handleDownload}
className=”absolute top-4 right-4 flex items-center justify-center w-8 h-8 bg-[#4e4e4e] rounded-full hover:bg-[#5e5e5e] transition”
title=”Download”
>
<FontAwesomeIcon icon={faDownload} className=”text-white” />
</button>
{/* Close Button */}
<button
onClick={handleClose}
className=”absolute top-4 left-4 flex items-center justify-center w-8 h-8 bg-[#4e4e4e] rounded-full hover:bg-[#5e5e5e] transition”
title=”Close”
>
<FontAwesomeIcon icon={faTimes} className=”text-white” />
</button>
{/* Sticker Image */}
<div className=”flex justify-center items-center”>
<Image
src={stickerUrl}
alt=”Generated Sticker”
width={300}
height={300}
className=”rounded-md”
/>
</div>
</div>
</div>
)}
</div>
);
}
شکستن آن 🧩
لودر: ما از لودر بسیار ساده اما خوب استفاده می کنیم. three horizontal dots with some nice animaton:
const loader = () => (
<svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” viewBox=”0 0 24 24″>
<circle cx={4} cy={12} r={3} fill=”currentColor”>
<animate id=”svgSpinners3DotsScale0″ attributeName=”r” begin=”0;svgSpinners3DotsScale1.end-0.25s” dur=”0.75s” values=”3;.2;3″ />
</circle>
<circle cx={12} cy={12} r={3} fill=”currentColor”>
<animate attributeName=”r” begin=”svgSpinners3DotsScale0.end-0.6s” dur=”0.75s” values=”3;.2;3″ />
</circle>
<circle cx={20} cy={12} r={3} fill=”currentColor”>
<animate id=”svgSpinners3DotsScale1″ attributeName=”r” begin=”svgSpinners3DotsScale0.end-0.45s” dur=”0.75s” values=”3;.2;3″ />
</circle>
</svg>
);
مدیریت دولتی: با استفاده از useState برای رسیدگی به اعلانها، وضعیت بارگیری، درخواست کاربر و URL برچسب.
توابع:
enhanceUserPrompt: با ما تماس می گیرد /api/enhancePrompt نقطه پایانی برای بیشتر کردن درخواست کاربر… خوب، برانگیختن.
generateCuteSticker: ضربه می زند /api/generateSticker نقطه پایانی برای دریافت آن برچسب شایان ستایش.
generateSticker: وقتی کاربر روی دکمه جادویی کلیک می کند، کل فرآیند را هماهنگ می کند.
handleDownload: به کاربر اجازه می دهد استیکر جدید خود را دانلود کند.
handleClose: مدال استیکر را می بندد.
اجزای رابط کاربری:
فیلد ورودی: جایی که کاربر عجیب ترین رویاهای برچسب خود را تایپ می کند.
دکمه تولید: باعث ایجاد استیکر می شود.
مدال: برچسب را با گزینه هایی برای دانلود یا بستن نمایش می دهد.
اطلاعیه ها: پیام هایی را برای اطلاع کاربر از آنچه در حال وقوع است ظاهر می کند.
A Sprinkle of FontAwesome 🌟
ما از FontAwesome برای نمادها استفاده می کنیم. حتما نصبش کنید:
npm i –save @fortawesome/fontawesome-svg-core
npm i –save @fortawesome/free-solid-svg-icons
npm i –save @fortawesome/free-regular-svg-icons
npm i –save @fortawesome/free-brands-svg-icons
npm i –save @fortawesome/react-fontawesome@latest
همچنین میتوانید اسناد FontAwesome را برای جزئیات بیشتر بررسی کنید. یا نمادهای دیگر را جستجو کنید نمادهای جستجو.
رسیدگی به اعلان ها 🔔
آن مؤلفه اعلان را که وارد کردیم به خاطر دارید؟ بیایید آن را ایجاد کنیم.
ایجاد مؤلفه اعلان 📢
یک پوشه جدید به نام ایجاد کنید utils داخل شما app دایرکتوری داخل utils، یک فایل به نام ایجاد کنید notify.tsx و چسباندن:
// app/utils/notify.tsx
import React, { useEffect } from ‘react’;
type NotificationProps = {
message: string;
type: ‘error’ | ‘success’ | ‘info’;
onClose: () => void;
};
const Notification: React.FC<NotificationProps> = ({ message, type, onClose }) => {
useEffect(() => {
const timer = setTimeout(() => {
onClose();
}, 3000); // Auto-close after 3 seconds
return () => clearTimeout(timer);
}, [onClose]);
const bgColor = type === ‘error’ ? ‘bg-red-500’ : type === ‘success’ ? ‘bg-green-500’ : ‘bg-blue-500’;
return (
<div className={`fixed top-10 left-1/2 transform -translate-x-1/2 ${bgColor} text-white px-4 py-2 rounded-md shadow-lg z-50`}>
<p>{message}</p>
</div>
);
};
export default Notification;
این برای چیست؟ 🎈
هدف: برای نمایش پیامهای موقت به کاربر، مانند «تولید برچسب زیبا…» یا «خطایی رخ داده است».
ویژگی بستن خودکار: بعد از 3 ثانیه ناپدید می شود، درست مثل انگیزه من در صبح های دوشنبه.
یک ظاهر طراحی شده: رنگ را بر اساس نوع اعلان تغییر می دهد.
پیکربندی دامنه های تصویر 🖼️
از آنجایی که ما در حال واکشی تصاویر از سرورهای OpenAI هستیم، Next.js باید بداند که بارگیری آنها اشکالی ندارد. باز کن next.config.ts و اضافه کنید:
// next.config.ts
import type { NextConfig } from “next”;
const nextConfig: NextConfig = {
/* config options here */
images: {
remotePatterns: [
{
protocol: ‘https’,
hostname: ‘oaidalleapiprodscus.blob.core.windows.net’,
port: ”,
},
],
},
};
export default nextConfig;
چرا این کار را انجام دهید؟ 🤷♂️
زیرا Next.js کمی بیش از حد محافظ است (مثل والد هلیکوپتر) و تصاویر را از دامنه های خارجی بارگیری نمی کند مگر اینکه شما به طور خاص اجازه دهید. این تنظیم به Next.js میگوید: “خیلی خوب است، این تصاویر با من هستند.”
متغیرهای محیطی 🔑
اکنون، قبل از اینکه برنامه خود را با هیجان اجرا کنید و تعجب کنید که چرا کار نمی کند، اجازه دهید متغیرهای محیطی خود را تنظیم کنیم.
تنظیم کلید AI/ML API 🗝️
یک فایل به نام ایجاد کنید .env.local در ریشه پروژه خود و اضافه کنید:
NEXT_PUBLIC_AIML_API_KEY=your_api_key_here
جایگزین کنید your_api_key_here با کلید AI/ML API واقعی شما. اگر ندارید، ممکن است لازم باشد در AI/ML API ثبت نام کنید و آن را بگیرید. این کاملا است رایگان برای شروع!
در اینجا یک آموزش سریع درباره نحوه دریافت کلید API آورده شده است: چگونه کلید API را از AI/ML API دریافت کنید. آموزش گام به گام سریع با اسکرین شات برای درک بهتر.
هشدار: این کلید را مخفی نگه دارید! آن را به صورت عمومی به اشتراک نگذارید یا آن را به Git متعهد نکنید. با آن مانند رمز عبور نتفلیکس خود رفتار کنید.
آن را آتش بزنید! 🚀
وقت آن است که این کودک را در عمل ببینیم.
اجرای سرور توسعه 🏃♀️
در ترمینال خود، اجرا کنید:
npm run dev
با این کار سرور توسعه راه اندازی می شود. مرورگر خود را باز کرده و به آن بروید http://localhost:3000.
شما باید پلتفرم AI Sticker Maker خود را ببینید. 🌟
تست کردن آن 🧪
یک Prompt را وارد کنید: یه چیزی شبیه “دختری با موهای کوتاه سفید + خاکستری با پیراهن بزرگ”. وحشی شو!
روی دکمه کلیک کنید: دکمه تولید را فشار دهید و شاهد آشکار شدن جادو باشید.
منتظرش باش…: اعلانهایی را خواهید دید که شما را در جریان قرار میدهند.
Voilà!: برچسب ایجاد شده توسط هوش مصنوعی شما باید ظاهر شود. در شکوه آن غرق شوید.
عیب یابی 🛠️
“واکشی داده های تکمیل ناموفق بود”: کلید API خود را دوباره بررسی کنید و مطمئن شوید که به درستی تنظیم شده است.
تصاویر بارگیری نمی شوند: از خود اطمینان حاصل کنید next.config.ts فایل مطابق شکل بالا تنظیم شده است.
خرابی برنامه: کنسول خود را باز کنید و ببینید چه خطاهایی ظاهر می شود. گوگل دوست شماست!
در حال اتمام 🎁
تبریک می گویم! شما به تازگی یک برچسب AI ساخته اید که هم سرگرم کننده و هم کاربردی است. نه تنها در دنیای هوش مصنوعی و Next.js جستجو کردید، بلکه چیزی ساختید که می تواند لبخند را به چهره مردم بیاورد.
بعد چه می شود؟ 🚧
یک ظاهر طراحی شده: ظاهر و احساس را سفارشی کنید. آن را به همان اندازه که دوست دارید افسانه یا مینیمالیستی کنید.
ویژگی ها: حساب های کاربری، گالری استیکر یا حتی یک ویژگی برای ایجاد بسته های برچسب اضافه کنید.
کسب درآمد: Stripe را ادغام کنید و شروع به شارژ برچسب های ممتاز کنید. زمان درست کردن مولا است!
افکار نهایی 💭
ساختن این برنامه مانند ساختن یک ساندویچ با لایههای خوبی از فناوری بود. ما مدلهای هوش مصنوعی را به عنوان پرکننده، Next.js بهعنوان نان، و طنز به عنوان سس مخفی داریم.
به یاد داشته باشید، دنیا صدف (یا برچسب شما) است. به آزمایش ادامه دهید، به ساختن ادامه دهید، و مهمتر از همه، از آن لذت ببرید!
کد نویسی مبارک! 🎉
پیاده سازی کامل در Github AI Sticker Maker در دسترس است.
این کاملا رایگان برای شروع است! آن را امتحان کنید اکنون کلیک کنید
این آموزش رو هم ببینید، خیلی جالبه! ساختن یک برنامه افزودنی کروم از ابتدا با AI/ML API، Deepgram Aura و ادغام IndexedDB
اگر سؤالی دارید یا نیاز به کمک بیشتری دارید، دریغ نکنید که از طریق ایمیل به آدرس ایمیل تماس بگیرید abdibrokhim@gmail.com.
حوصله ام سر رفت شما هم؟ 😴
هوم…🤔
در مورد ایجاد یک استیکر ساز هوش مصنوعی پلت فرم؟ صادقانه بگویم، این یک ایده واقعا جالب است. و هی، ما حتی ممکن است با ادغام Stripe به عنوان یک ارائه دهنده پرداخت، مقداری سود به دست آوریم. 💰 آره چرا که نه؟
بنابراین، بیایید شروع کنیم. یا حداقل به آن ضربه بزنید! 🚀
معرفی سریع 🧐
اول از همه، بیایید یک شبه کد را ترسیم کنیم یا یک طرح بسازیم (مگر اینکه سازنده واقعی باشید که از باسن کد می نویسید). باید چیزی شبیه به این باشد:
- کاربر یک اعلان وارد می کند (توضیح متنی از نحوه ظاهر برچسب).
- ما استیکر ساز هوش مصنوعی یک برچسب واقعا زیبا ایجاد می کند. تا-دا! 🥳
آسان-پیزی، اینطور نیست؟ 🍋
اما صبر کنید، اجازه دهید من توضیح دهم. ما قصد داریم از دو مدل استفاده کنیم: GPT-4o و از و 3، هر دو از OpenAI. آنها هیپ هستند، واقعا! 🔥
ما از AI/ML API، که دسترسی به بیش از 200 مدل هوش مصنوعی را با یک API فراهم می کند. بگذارید به طور خلاصه در مورد آن برای شما بگویم.
با AI/ML API آشنا شوید 🤖👇
AI/ML API یک پلتفرم تغییر دهنده بازی برای توسعه دهندگان و کارآفرینان SaaS است که به دنبال ادغام قابلیت های پیشرفته هوش مصنوعی در محصولات خود هستند. این یک نقطه دسترسی به بیش از حد را ارائه می دهد 200 مدل پیشرفته هوش مصنوعی، از NLP گرفته تا بینایی کامپیوتری را پوشش می دهد.
ویژگی های کلیدی برای توسعه دهندگان:
- کتابخانه مدل گسترده: بیش از 200 مدل از پیش آموزش دیده برای نمونه سازی و استقرار سریع. 📚
- گزینه های سفارشی سازی: مدلهای تنظیم دقیق متناسب با مورد خاص شما. 🎯
- ادغام دوستدار توسعه دهندگان: API ها و SDK های RESTful برای ادغام یکپارچه در پشته شما. 🛠️
- معماری بدون سرور: روی کدنویسی تمرکز کنید نه مدیریت زیرساخت. ☁️
شروع کنید برای رایگان (0 دلار آمریکا): aimlapi.com 🆓
Deep Dive into AI/ML API Documentation (بسیار مفصل، نمی توانم بیشتر موافقم): docs.aimlapi.com 📖
Tech Stack Ingredients 🥘
استفاده خواهیم کرد TypeScript، Next.js، واکنش نشان دهید، و Tailwind CSS برای ساخت و طراحی پلتفرم AI Sticker Maker ما.
- TypeScript فقط یک زبان برنامه نویسی است – اما یک زبان واقعا عالی! 📝
- Next.js چارچوب React برای وب است. این ما را قادر میسازد تا برنامههای وب با کیفیت بالا را با قدرت اجزای React ایجاد کنیم. 🌐
- واکنش نشان دهید کتابخانه ای برای رابط های کاربری وب و بومی است. 🖥️
- Tailwind CSS برای یک ظاهر طراحی شده بهترین است – فقط هر چیزی را که می خواهید بسازید، به طور جدی. 🎨
این فقط یک نمای کلی از آنچه قرار است استفاده کنیم بود. برای کسب اطلاعات بیشتر در مورد هر یک از آنها در اینجا احساس راحتی کنید:
- TypeScript: typescriptlang.org 🦕
- Next.js: nextjs.org ⏭️
- واکنش نشان دهید: react.dev ⚛️
- Tailwind CSS: tailwindcss.com 🌬️
آشپزی شروع شد 🍳
دستمان را کثیف کنیم! ابتدا یک پوشه ایجاد کنید. ترمینال خود را باز کنید و این را وارد کنید:
mkdir aiml-tutorial
cd aiml-tutorial
اکنون، بیایید یک برنامه Next.js جدید ایجاد کنیم:
npx create-next-app@latest
از شما چند سوال خواهد پرسید:
✔ نام پروژه شما چیست؟ در اینجا، شما باید نام برنامه خود را وارد کنید. به عنوان مثال: aistickermaker
. برای بقیه سوالات به سادگی ضربه بزنید enter
.
در اینجا چیزی است که خواهید دید:
✔ 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 your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for `next dev`? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes
برای نکته: با خیال راحت انتخاب کنید Yes
یا No
بر اساس ترجیحات شما من قضاوت نمی کنم! 😜
بیایید پروژه را با VSCode باز کنیم:
code .
اکنون، Visual Studio Code باید مستقیماً با این برنامه راه اندازی شود. زمان شروع کدنویسی است! 💻
پیاده سازی API ها 🛠️
اول از همه، اجازه دهید APIهایی را برای تقویت درخواست کاربر و تولید برچسب ایجاد کنیم. برو به app
پوشه، سپس یک پوشه جدید به نام ایجاد کنید api
و در داخل آن دو پوشه جدید ایجاد کنید: enhancePrompt
و generateSticker
. برای هر یک، یک را ایجاد کنید route.ts
فایل
را enhancePrompt
نقطه پایان 🧙♂️
حال، بیایید با آن شروع کنیم enhancePrompt
نقطه پایانی باز کنید route.ts
داخل enhancePrompt
پوشه و کد زیر را وارد کنید:
import { NextResponse } from 'next/server';
const systemPrompt = `
You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.
Instructions:
Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.
Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:
Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:
If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:
Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:
Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:
Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:
Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:
The tone should be light, imaginative, and fun, matching the playful nature of stickers.
Example:
User Input:
"A girl with pink hair wearing a hoodie."
Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."
`;
export async function POST(request: Request) {
try {
const { userPrompt } = await request.json();
console.log("/api/enhancePrompt/route.ts userPrompt: ", userPrompt);
// Make the API call to the external service
const response = await fetch('https://api.aimlapi.com/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{
role: 'system',
content: systemPrompt
},
{
role: 'user',
content: userPrompt
}
]
})
});
console.log("response: ", response);
if (!response.ok) {
// If the API response isn't successful, return an error response
return NextResponse.json({ error: "Failed to fetch completion data" }, { status: response.status });
}
const data = await response.json();
console.log("data: ", data);
const assistantResponse = data.choices[0]?.message?.content || "No response available";
// Return the assistant's message content
return NextResponse.json({ message: assistantResponse });
} catch (error) {
console.error("Error fetching the data:", error);
return NextResponse.json({ error: "An error occurred while processing your request." }, { status: 500 });
}
}
در اینجا اعلان جدا شده است:
You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.
Instructions:
Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.
Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:
Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:
If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:
Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:
Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:
Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:
Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:
The tone should be light, imaginative, and fun, matching the playful nature of stickers.
Example:
User Input:
"A girl with pink hair wearing a hoodie."
Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."
اینجا چه خبر است؟ 🤔
-
واردات
NextResponse
: برای رسیدگی به پاسخ های HTTP ما به آرامی. -
تعریف کردن
POST
تابع: اینجاست که وقتی کسی به این نقطه پایانی میرسد، جادو اتفاق میافتد. -
واکشی
userPrompt
: ما در حال گرفتن درخواست ارائه شده توسط کاربر هستیم. - فراخوانی API AI/ML API: ما درخواستی برای بهبود درخواست کاربر با استفاده از GPT-4o داریم.
- رسیدگی به پاسخ ها: بررسی می کنیم که آیا پاسخ درست است، داده ها را تجزیه می کنیم و پاسخ دستیار را استخراج می کنیم.
- رسیدگی به خطا: چون هیچکس دوست ندارد اشتباهات کنترل نشده مهمانی را خراب کند.
در اینجا یک مثال واقعی از این است که چگونه هوش مصنوعی اعلان کاربر را افزایش می دهد. 🐼🍦🌈
شما فقط یک اعلان وارد کردید:
A cute panda eating ice cream under a rainbow
هوش مصنوعی آن را تقویت می کند تا جزئیات بیشتری داشته باشد و از نظر بصری غنی تر شود. در نتیجه، شما باید پاسخی مانند:
An adorable, chibi-like panda with big, sparkling eyes and a joyful expression, savoring a colorful scoop of ice cream. The panda is fluffy and round, with classic black-and-white markings, sitting contentedly. The ice cream cone features vibrant, swirling flavors in pastel pink, mint green, and sunny yellow. Above, a playful, cartoonish rainbow arcs across a soft blue sky, adding a cheerful splash of color. The design is sticker-friendly with minimalistic lines and soft shading, ensuring a cute and delightful aesthetic perfect for capturing the joyful scene.
خوب، بیایید دوباره به داخل دیگ کد شیرجه بزنیم و به پختن برچسب AI خود ادامه دهیم! 🍲
را generateSticker
نقطه پایان 🖼️
بنابراین، ما خودمان را داریم enhancePrompt
نقطه پایانی به خوبی می جوشد. وقت آن است که چیزها را با آن چاشنی کنید generateSticker
نقطه پایانی سر به سمت api/generateSticker
پوشه و باز کنید route.ts
. هر چیزی را که در آنجا هست (احتمالاً هیچ چیز) با این کد جدید جایگزین کنید:
// api/generateSticker/route.ts
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
try {
const { userPrompt } = await request.json();
console.log("/api/generateSticker/route.ts userPrompt: ", userPrompt);
// Make the API call to the external service
const response = await fetch('https://api.aimlapi.com/images/generations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
},
body: JSON.stringify({
provider: 'openai',
prompt: userPrompt,
model: 'dall-e-3',
n: 1,
quality: 'hd',
response_format: 'url',
size: '1024x1024',
style: 'vivid'
})
});
console.log("response: ", response);
if (!response.ok) {
// If the API response isn't successful, return an error response
return NextResponse.json({ error: "Failed to fetch completion data" }, { status: response.status });
}
const data = await response.json();
console.log("data: ", data);
const assistantResponse = data.data[0]?.url || "No response available";
console.log("assistantResponse: ", assistantResponse);
// Return the assistant's message content
return NextResponse.json({ message: assistantResponse });
} catch (error) {
console.error("Error fetching the data:", error);
return NextResponse.json({ error: "An error occurred while processing your request." }, { status: 500 });
}
}
اینجا چه خبر است؟ 🤔
-
واردات
NextResponse
: برای رسیدگی به پاسخ های HTTP ما به آرامی. -
تعریف کردن
POST
تابع: این جایی است که وقتی کسی به این نقطه پایانی می رسد، جادو اتفاق می افتد. -
واکشی
userPrompt
: ما در حال گرفتن درخواست ارائه شده توسط کاربر هستیم. - فراخوانی API AI/ML API: ما درخواستی برای ایجاد یک تصویر بر اساس اعلان با استفاده از DALL·E 3 داریم.
- رسیدگی به پاسخ ها: بررسی می کنیم که آیا پاسخ درست است، داده ها را تجزیه می کنیم و URL تصویر را استخراج می کنیم.
- رسیدگی به خطا: چون هیچکس دوست ندارد اشتباهات کنترل نشده مهمانی را خراب کند.
بیایید دستور بالا را با panda
در عمل! 🚀
اینم برچسب پاندای ناز ما! 🐼🍦🌈
نمونه های دیگر 😍
اعلان:
A girl with short white+grey hair wearing a oversize shirt
اعلان:
A girl with short black+pink hair wearing a oversize pink shirt
به نظر می رسد، واقعا WOW! 🤩
ما نیاز به یک فرانتند داریم، بچه ها! 😅
ساخت Frontend 🎨
زمان برای قرار دادن چهره در برنامه ما! بیایید یک رابط کاربری ایجاد کنیم که در آن کاربران بتوانند درخواست خود را وارد کنند و یک برچسب جدید براق دریافت کنند.
را page.tsx
فایل 📄
حرکت به app/page.tsx
و با کد زیر آن را به روز کنید:
// app/page.tsx
'use client';
import Image from "next/image";
import { useState } from 'react';
import { faArrowUp, faDownload, faTimes } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import Notification from './utils/notify';
import { Analytics } from "@vercel/analytics/react"
export default function Home() {
const [notification, setNotification] = useState<{ message: string; type: 'error' | 'success' | 'info' } | null>(null); // notification message
const [loading, setLoading] = useState(false);
const [prompt, setPrompt] = useState('');
const [stickerUrl, setStickerUrl] = useState("");
const loader = () => (
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
<circle cx={4} cy={12} r={3} fill="currentColor">
<animate id="svgSpinners3DotsScale0" attributeName="r" begin="0;svgSpinners3DotsScale1.end-0.25s" dur="0.75s" values="3;.2;3" />
</circle>
<circle cx={12} cy={12} r={3} fill="currentColor">
<animate attributeName="r" begin="svgSpinners3DotsScale0.end-0.6s" dur="0.75s" values="3;.2;3" />
</circle>
<circle cx={20} cy={12} r={3} fill="currentColor">
<animate id="svgSpinners3DotsScale1" attributeName="r" begin="svgSpinners3DotsScale0.end-0.45s" dur="0.75s" values="3;.2;3" />
</circle>
</svg>
);
const enhanceUserPrompt = async (prompt: string) => {
setNotification({ message: 'Enhancing user prompt...', type: 'info' });
// Make the API call to the /api/enhancePrompt route and return the enhanced prompt
const response = await fetch('/api/enhancePrompt', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userPrompt: prompt }),
});
if (!response.ok) {
throw new Error('Failed to fetch completion data');
}
const data = await response.json();
return data.message;
};
const generateCuteSticker = async (prompt: string) => {
setNotification({ message: 'Generating cute sticker...', type: 'info' });
// Make the API call to the /api/generateSticker route and return the generated sticker URL
const response = await fetch('/api/generateSticker', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userPrompt: prompt }),
});
if (!response.ok) {
throw new Error('Failed to fetch completion data');
}
const data = await response.json();
return data.message;
};
const generateSticker = async () => {
if (!prompt) return;
setLoading(true);
setNotification({ message: 'Processing request...', type: 'info' });
try {
// Enhance user prompt
const enhancedPrompt = await enhanceUserPrompt(prompt);
if (!enhancedPrompt) {
setNotification({ message: 'Failed to enhance user prompt.', type: 'error' });
return;
}
// Generate cute sticker
const sticker = await generateCuteSticker(enhancedPrompt);
if (!sticker) {
setNotification({ message: 'Failed to generate cute sticker.', type: 'error' });
return;
}
setStickerUrl(sticker);
console.log('Sticker URL:', sticker);
setNotification({ message: 'Cute sticker generated successfully!', type: 'success' });
} catch (error) {
console.error('An unexpected error occurred:', error);
setNotification({ message: 'An unexpected error occurred.', type: 'error' });
} finally {
setLoading(false);
}
};
const handleDownload = () => {
if (!stickerUrl) return;
const link = document.createElement('a');
link.href = stickerUrl;
link.download = 'cute-sticker.png'; // You can set a default filename
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const handleClose = () => {
setStickerUrl("");
setPrompt("");
};
return (
<div className="flex flex-col items-center justify-center min-h-screen text-white p-4 bg-[#212121e6]">
<Analytics />
{notification && (
<Notification
message={notification.message}
type={notification.type}
onClose={() => setNotification(null)}
/>
)}
<div className="mb-6 inline-flex justify-center text-2xl font-semibold leading-9">
<h1>Let's Generate Cutesy AI Sticker!</h1>
</div>
<div className="lg:w-[60%] w-full mx-auto flex items-center p-2 mb-8 shadow-lg gap-4 bg-[#2e2e2e] rounded-full">
<input
type="text"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="A girl with short pink hair wearing a oversize hoodie..."
className="placeholder:text-[#aeaeae] bg-transparent focus:outline-none text-white outline-none w-full px-4"
disabled={loading}
/>
<button
disabled={prompt === '' || loading}
onClick={generateSticker}
className={`flex items-center justify-center w-12 h-10 rounded-full shadow ${
prompt === '' ? 'cursor-not-allowed bg-[#4e4e4e] text-black' : 'cursor-pointer bg-[#eeeeee] text-black'}`}
>
{!loading
? <FontAwesomeIcon icon={faArrowUp} />
: <span className='flex justify-center items-center text-black text-xl'>{loader()}</span>
}
</button>
</div>
{/* Modal */}
{stickerUrl && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-[#2e2e2e] rounded-md p-4 relative w-11/12 max-w-md">
{/* Download Button */}
<button
onClick={handleDownload}
className="absolute top-4 right-4 flex items-center justify-center w-8 h-8 bg-[#4e4e4e] rounded-full hover:bg-[#5e5e5e] transition"
title="Download"
>
<FontAwesomeIcon icon={faDownload} className="text-white" />
</button>
{/* Close Button */}
<button
onClick={handleClose}
className="absolute top-4 left-4 flex items-center justify-center w-8 h-8 bg-[#4e4e4e] rounded-full hover:bg-[#5e5e5e] transition"
title="Close"
>
<FontAwesomeIcon icon={faTimes} className="text-white" />
</button>
{/* Sticker Image */}
<div className="flex justify-center items-center">
<Image
src={stickerUrl}
alt="Generated Sticker"
width={300}
height={300}
className="rounded-md"
/>
</div>
</div>
</div>
)}
</div>
);
}
شکستن آن 🧩
-
لودر: ما از لودر بسیار ساده اما خوب استفاده می کنیم.
three horizontal dots with some nice animaton
:
const loader = () => (
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
<circle cx={4} cy={12} r={3} fill="currentColor">
<animate id="svgSpinners3DotsScale0" attributeName="r" begin="0;svgSpinners3DotsScale1.end-0.25s" dur="0.75s" values="3;.2;3" />
</circle>
<circle cx={12} cy={12} r={3} fill="currentColor">
<animate attributeName="r" begin="svgSpinners3DotsScale0.end-0.6s" dur="0.75s" values="3;.2;3" />
</circle>
<circle cx={20} cy={12} r={3} fill="currentColor">
<animate id="svgSpinners3DotsScale1" attributeName="r" begin="svgSpinners3DotsScale0.end-0.45s" dur="0.75s" values="3;.2;3" />
</circle>
</svg>
);
-
مدیریت دولتی: با استفاده از
useState
برای رسیدگی به اعلانها، وضعیت بارگیری، درخواست کاربر و URL برچسب. -
توابع:
-
enhanceUserPrompt
: با ما تماس می گیرد/api/enhancePrompt
نقطه پایانی برای بیشتر کردن درخواست کاربر… خوب، برانگیختن. -
generateCuteSticker
: ضربه می زند/api/generateSticker
نقطه پایانی برای دریافت آن برچسب شایان ستایش. -
generateSticker
: وقتی کاربر روی دکمه جادویی کلیک می کند، کل فرآیند را هماهنگ می کند. -
handleDownload
: به کاربر اجازه می دهد استیکر جدید خود را دانلود کند. -
handleClose
: مدال استیکر را می بندد.
-
-
اجزای رابط کاربری:
- فیلد ورودی: جایی که کاربر عجیب ترین رویاهای برچسب خود را تایپ می کند.
- دکمه تولید: باعث ایجاد استیکر می شود.
- مدال: برچسب را با گزینه هایی برای دانلود یا بستن نمایش می دهد.
- اطلاعیه ها: پیام هایی را برای اطلاع کاربر از آنچه در حال وقوع است ظاهر می کند.
A Sprinkle of FontAwesome 🌟
ما از FontAwesome برای نمادها استفاده می کنیم. حتما نصبش کنید:
npm i --save @fortawesome/fontawesome-svg-core
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/free-regular-svg-icons
npm i --save @fortawesome/free-brands-svg-icons
npm i --save @fortawesome/react-fontawesome@latest
همچنین میتوانید اسناد FontAwesome را برای جزئیات بیشتر بررسی کنید. یا نمادهای دیگر را جستجو کنید نمادهای جستجو.
رسیدگی به اعلان ها 🔔
آن مؤلفه اعلان را که وارد کردیم به خاطر دارید؟ بیایید آن را ایجاد کنیم.
ایجاد مؤلفه اعلان 📢
یک پوشه جدید به نام ایجاد کنید utils
داخل شما app
دایرکتوری داخل utils
، یک فایل به نام ایجاد کنید notify.tsx
و چسباندن:
// app/utils/notify.tsx
import React, { useEffect } from 'react';
type NotificationProps = {
message: string;
type: 'error' | 'success' | 'info';
onClose: () => void;
};
const Notification: React.FC<NotificationProps> = ({ message, type, onClose }) => {
useEffect(() => {
const timer = setTimeout(() => {
onClose();
}, 3000); // Auto-close after 3 seconds
return () => clearTimeout(timer);
}, [onClose]);
const bgColor = type === 'error' ? 'bg-red-500' : type === 'success' ? 'bg-green-500' : 'bg-blue-500';
return (
<div className={`fixed top-10 left-1/2 transform -translate-x-1/2 ${bgColor} text-white px-4 py-2 rounded-md shadow-lg z-50`}>
<p>{message}</p>
</div>
);
};
export default Notification;
این برای چیست؟ 🎈
- هدف: برای نمایش پیامهای موقت به کاربر، مانند «تولید برچسب زیبا…» یا «خطایی رخ داده است».
- ویژگی بستن خودکار: بعد از 3 ثانیه ناپدید می شود، درست مثل انگیزه من در صبح های دوشنبه.
- یک ظاهر طراحی شده: رنگ را بر اساس نوع اعلان تغییر می دهد.
پیکربندی دامنه های تصویر 🖼️
از آنجایی که ما در حال واکشی تصاویر از سرورهای OpenAI هستیم، Next.js باید بداند که بارگیری آنها اشکالی ندارد. باز کن next.config.ts
و اضافه کنید:
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'oaidalleapiprodscus.blob.core.windows.net',
port: '',
},
],
},
};
export default nextConfig;
چرا این کار را انجام دهید؟ 🤷♂️
زیرا Next.js کمی بیش از حد محافظ است (مثل والد هلیکوپتر) و تصاویر را از دامنه های خارجی بارگیری نمی کند مگر اینکه شما به طور خاص اجازه دهید. این تنظیم به Next.js میگوید: “خیلی خوب است، این تصاویر با من هستند.”
متغیرهای محیطی 🔑
اکنون، قبل از اینکه برنامه خود را با هیجان اجرا کنید و تعجب کنید که چرا کار نمی کند، اجازه دهید متغیرهای محیطی خود را تنظیم کنیم.
تنظیم کلید AI/ML API 🗝️
یک فایل به نام ایجاد کنید .env.local
در ریشه پروژه خود و اضافه کنید:
NEXT_PUBLIC_AIML_API_KEY=your_api_key_here
جایگزین کنید your_api_key_here
با کلید AI/ML API واقعی شما. اگر ندارید، ممکن است لازم باشد در AI/ML API ثبت نام کنید و آن را بگیرید. این کاملا است رایگان برای شروع!
در اینجا یک آموزش سریع درباره نحوه دریافت کلید API آورده شده است: چگونه کلید API را از AI/ML API دریافت کنید. آموزش گام به گام سریع با اسکرین شات برای درک بهتر.
هشدار: این کلید را مخفی نگه دارید! آن را به صورت عمومی به اشتراک نگذارید یا آن را به Git متعهد نکنید. با آن مانند رمز عبور نتفلیکس خود رفتار کنید.
آن را آتش بزنید! 🚀
وقت آن است که این کودک را در عمل ببینیم.
اجرای سرور توسعه 🏃♀️
در ترمینال خود، اجرا کنید:
npm run dev
با این کار سرور توسعه راه اندازی می شود. مرورگر خود را باز کرده و به آن بروید http://localhost:3000
.
شما باید پلتفرم AI Sticker Maker خود را ببینید. 🌟
تست کردن آن 🧪
-
یک Prompt را وارد کنید: یه چیزی شبیه “دختری با موهای کوتاه سفید + خاکستری با پیراهن بزرگ”. وحشی شو!
-
روی دکمه کلیک کنید: دکمه تولید را فشار دهید و شاهد آشکار شدن جادو باشید.
-
منتظرش باش…: اعلانهایی را خواهید دید که شما را در جریان قرار میدهند.
-
Voilà!: برچسب ایجاد شده توسط هوش مصنوعی شما باید ظاهر شود. در شکوه آن غرق شوید.
عیب یابی 🛠️
- “واکشی داده های تکمیل ناموفق بود”: کلید API خود را دوباره بررسی کنید و مطمئن شوید که به درستی تنظیم شده است.
-
تصاویر بارگیری نمی شوند: از خود اطمینان حاصل کنید
next.config.ts
فایل مطابق شکل بالا تنظیم شده است. - خرابی برنامه: کنسول خود را باز کنید و ببینید چه خطاهایی ظاهر می شود. گوگل دوست شماست!
در حال اتمام 🎁
تبریک می گویم! شما به تازگی یک برچسب AI ساخته اید که هم سرگرم کننده و هم کاربردی است. نه تنها در دنیای هوش مصنوعی و Next.js جستجو کردید، بلکه چیزی ساختید که می تواند لبخند را به چهره مردم بیاورد.
بعد چه می شود؟ 🚧
- یک ظاهر طراحی شده: ظاهر و احساس را سفارشی کنید. آن را به همان اندازه که دوست دارید افسانه یا مینیمالیستی کنید.
- ویژگی ها: حساب های کاربری، گالری استیکر یا حتی یک ویژگی برای ایجاد بسته های برچسب اضافه کنید.
- کسب درآمد: Stripe را ادغام کنید و شروع به شارژ برچسب های ممتاز کنید. زمان درست کردن مولا است!
افکار نهایی 💭
ساختن این برنامه مانند ساختن یک ساندویچ با لایههای خوبی از فناوری بود. ما مدلهای هوش مصنوعی را به عنوان پرکننده، Next.js بهعنوان نان، و طنز به عنوان سس مخفی داریم.
به یاد داشته باشید، دنیا صدف (یا برچسب شما) است. به آزمایش ادامه دهید، به ساختن ادامه دهید، و مهمتر از همه، از آن لذت ببرید!
کد نویسی مبارک! 🎉
پیاده سازی کامل در Github AI Sticker Maker در دسترس است.
این کاملا رایگان برای شروع است! آن را امتحان کنید اکنون کلیک کنید
این آموزش رو هم ببینید، خیلی جالبه! ساختن یک برنامه افزودنی کروم از ابتدا با AI/ML API، Deepgram Aura و ادغام IndexedDB
اگر سؤالی دارید یا نیاز به کمک بیشتری دارید، دریغ نکنید که از طریق ایمیل به آدرس ایمیل تماس بگیرید abdibrokhim@gmail.com
.