ערכות ה-SDK של Firebase AI Logic נותנות לכם גישה למודלים של Imagen 3 (דרך Imagen API) כדי שתוכלו ליצור תמונות מהנחיית טקסט. בעזרת היכולת הזו תוכלו לבצע פעולות כמו:
- יצירת תמונות מהנחיות שנכתבות בשפה טבעית
- יצירת תמונות במגוון רחב של פורמטים וסגנונות
- רינדור של טקסט בתמונות
חשוב לזכור ש-Firebase AI Logic עדיין לא תומך בכל התכונות שזמינות לדגמי Imagen. מידע נוסף זמין בקטע יכולות ותכונות נתמכות בהמשך הדף.
לפני שמתחילים
לוחצים על ספק Gemini API כדי להציג בדף הזה תוכן וקוד ספציפיים לספק. |
אם עדיין לא עשיתם זאת, כדאי לעיין במדריך למתחילים, שבו מוסבר איך מגדירים את פרויקט Firebase, מחברים את האפליקציה ל-Firebase, מוסיפים את ה-SDK, מאתחלים את שירות הקצה העורפי של ספק ה-API שבחרתם ויוצרים מכונה של ImagenModel
.
מודלים שתומכים ביכולת הזו
יצירת תמונות נתמכת במודלים Imagen 3.
שימו לב ש-Firebase AI Logic תומך גם ביצירת תמונות על ידי מודלים של Gemini – בקרוב תהיה תיעוד בנושא.
יצירת תמונות ממידע שמוזן בטקסט בלבד
אתם יכולים לבקש ממודל Imagen ליצור תמונות על ידי הוספת הנחיה עם טקסט. אפשר ליצור תמונה אחת או כמה תמונות.
יצירת תמונה אחת ממידע קלט של טקסט בלבד
לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה. |
אפשר לבקש ממודל Imagen ליצור תמונה אחת על ידי הוספת הנחיה עם טקסט.
חשוב ליצור מכונה של ImagenModel
ולקרוא ל-generateImages
.
Swift
import FirebaseAI
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create an `ImagenModel` instance with a model that supports your use case
let model = ai.imagenModel(modelName: "imagen-3.0-generate-002")
// Provide an image generation prompt
let prompt = "An astronaut riding a horse"
// To generate an image, call `generateImages` with the text prompt
let response = try await model.generateImages(prompt: prompt)
// Handle the generated image
guard let image = response.images.first else {
fatalError("No image in the response.")
}
let uiImage = UIImage(data: image.data)
Kotlin
// Using this SDK to access Imagen models is a Preview release and requires opt-in
@OptIn(PublicPreviewAPI::class)
suspend fun generateImage() {
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
val imagenModel = Firebase.googleAI.imagenModel("imagen-3.0-generate-002")
// Provide an image generation prompt
val prompt = "An astronaut riding a horse"
// To generate an image, call `generateImages` with the text prompt
val imageResponse = imagenModel.generateImages(prompt)
// Handle the generated image
val image = imageResponse.images.first()
val bitmapImage = image.asBitmap()
}
Java
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
ImagenModel imagenModel = FirebaseAI.getInstance(GenerativeBackend.googleAI()).imagenModel(
/* modelName */ "imagen-3.0-generate-002");
ImagenModelFutures model = ImagenModelFutures.from(imagenModel);
// Provide an image generation prompt
String prompt = "An astronaut riding a horse";
// To generate an image, call `generateImages` with the text prompt
Futures.addCallback(model.generateImages(prompt), new FutureCallback<ImagenGenerationResponse<ImagenInlineImage>>() {
@Override
public void onSuccess(ImagenGenerationResponse<ImagenInlineImage> result) {
if (result.getImages().isEmpty()) {
Log.d("TAG", "No images generated");
}
Bitmap bitmap = result.getImages().get(0).asBitmap();
// Use the bitmap to display the image in your UI
}
@Override
public void onFailure(Throwable t) {
// ...
}
}, Executors.newSingleThreadExecutor());
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create an `ImagenModel` instance with an Imagen 3 model that supports your use case
const imagenModel = getImagenModel(ai, { model: "imagen-3.0-generate-002" });
// Provide an image generation prompt
const prompt = "An astronaut riding a horse.";
// To generate an image, call `generateImages` with the text prompt
const response = await imagenModel.generateImages(prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (response.filteredReason) {
console.log(response.filteredReason);
}
if (response.images.length == 0) {
throw new Error("No images in the response.")
}
const image = response.images[0];
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
final model =
FirebaseAI.googleAI().imagenModel(model: 'imagen-3.0-generate-002');
// Provide an image generation prompt
const prompt = 'An astronaut riding a horse.';
// To generate an image, call `generateImages` with the text prompt
final response = await model.generateImages(prompt);
if (response.images.isNotEmpty) {
final image = response.images[0];
// Process the image
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
עדיין אין תמיכה ב-Imagen ב-Unity, אבל כדאי לבדוק שוב בקרוב.
איך בוחרים מודל שמתאים לתרחיש לדוגמה ולסוג האפליקציה שלכם
יצירת כמה תמונות ממידע שמוזן בטקסט בלבד
לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה. |
כברירת מחדל, מודלים של Imagen 3 יוצרים רק תמונה אחת לכל בקשה.
עם זאת, אפשר לבקש ממודל Imagen ליצור כמה תמונות לכל בקשה על ידי ציון הערך ImagenGenerationConfig
בזמן יצירת המכונה ImagenModel
.
חשוב ליצור מכונה של ImagenModel
ולקרוא ל-generateImages
.
Swift
import FirebaseAI
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create an `ImagenModel` instance with a model that supports your use case
let model = ai.imagenModel(
modelName: "imagen-3.0-generate-002",
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
generationConfig: ImagenGenerationConfig(numberOfImages: 4)
)
// Provide an image generation prompt
let prompt = "An astronaut riding a horse"
// To generate images, call `generateImages` with the text prompt
let response = try await model.generateImages(prompt: prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if let filteredReason = response.filteredReason {
print(filteredReason)
}
// Handle the generated images
let uiImages = response.images.compactMap { UIImage(data: $0.data) }
Kotlin
// Using this SDK to access Imagen models is a Preview release and requires opt-in
@OptIn(PublicPreviewAPI::class)
suspend fun generateImage() {
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
val imagenModel = Firebase.googleAI.imagenModel(
modelName = "imagen-3.0-generate-002",
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
generationConfig = ImagenGenerationConfig(numberOfImages = 4)
)
// Provide an image generation prompt
val prompt = "An astronaut riding a horse"
// To generate images, call `generateImages` with the text prompt
val imageResponse = imagenModel.generateImages(prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (imageResponse.filteredReason != null) {
Log.d(TAG, "FilteredReason: ${imageResponse.filteredReason}")
}
for (image in imageResponse.images) {
val bitmap = image.asBitmap()
// Use the bitmap to display the image in your UI
}
}
Java
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
ImagenGenerationConfig imagenGenerationConfig = new ImagenGenerationConfig.Builder()
.setNumberOfImages(4)
.build();
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
ImagenModel imagenModel = FirebaseAI.getInstance(GenerativeBackend.googleAI()).imagenModel(
/* modelName */ "imagen-3.0-generate-002",
/* imageGenerationConfig */ imagenGenerationConfig);
ImagenModelFutures model = ImagenModelFutures.from(imagenModel);
// Provide an image generation prompt
String prompt = "An astronaut riding a horse";
// To generate images, call `generateImages` with the text prompt
Futures.addCallback(model.generateImages(prompt), new FutureCallback<ImagenGenerationResponse<ImagenInlineImage>>() {
@Override
public void onSuccess(ImagenGenerationResponse<ImagenInlineImage> result) {
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (result.getFilteredReason() != null){
Log.d("TAG", "FilteredReason: " + result.getFilteredReason());
}
// Handle the generated images
List<ImagenInlineImage> images = result.getImages();
for (ImagenInlineImage image : images) {
Bitmap bitmap = image.asBitmap();
// Use the bitmap to display the image in your UI
}
}
@Override
public void onFailure(Throwable t) {
// ...
}
}, Executors.newSingleThreadExecutor());
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create an `ImagenModel` instance with an Imagen 3 model that supports your use case
const imagenModel = getImagenModel(
ai,
{
model: "imagen-3.0-generate-002",
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
generationConfig: {
numberOfImages: 4
}
}
);
// Provide an image generation prompt
const prompt = "An astronaut riding a horse.";
// To generate images, call `generateImages` with the text prompt
const response = await imagenModel.generateImages(prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (response.filteredReason) {
console.log(response.filteredReason);
}
if (response.images.length == 0) {
throw new Error("No images in the response.")
}
const images = response.images[0];
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
final model =
FirebaseAI.googleAI().imagenModel(
model: 'imagen-3.0-generate-002',
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
generationConfig: ImagenGenerationConfig(numberOfImages: 4),
);
// Provide an image generation prompt
const prompt = 'An astronaut riding a horse.';
// To generate images, call `generateImages` with the text prompt
final response = await model.generateImages(prompt);
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (response.filteredReason != null) {
print(response.filteredReason);
}
if (response.images.isNotEmpty) {
final images = response.images;
for(var image in images) {
// Process the image
}
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
עדיין אין תמיכה ב-Imagen ב-Unity, אבל כדאי לבדוק שוב בקרוב.
איך בוחרים מודל שמתאים לתרחיש לדוגמה ולסוג האפליקציה שלכם
הדרישות והתכונות הנתמכות
המודלים של Imagen 3 מציעים הרבה תכונות שקשורות ליצירת תמונות. בקטע הזה מוסבר מה נתמך כשמשתמשים במודלים עם Firebase AI Logic.
היכולות והתכונות הנתמכות
Firebase AI Logic תומך בתכונות האלה של דגמי Imagen 3.
יצירת אנשים ופנים (בתנאי שפרויקט Firebase שלכם קיבל אישור מ-Google Cloud)
יצירת טקסט בתוך תמונות שנוצרו
הוספת סימן מים לתמונות שנוצרו
הגדרת פרמטרים ליצירת תמונות, כמו מספר התמונות שנוצרות, יחס גובה-רוחב והוספת סימן מים
הגדרת הגדרות הבטיחות
Firebase AI Logic לא תומך בתכונות המתקדמות האלה של דגמי Imagen 3.
חשוב לזכור שרוב התכונות האלה מחייבות אתכם להופיע ברשימת משתמשים שאושרו, גם אם אתם משתמשים במודלים של Imagen בצד השרת.
תכונות של עריכה או מניפולציה של תמונות, כולל התאמת תמונות לרזולוציה גבוהה יותר
הוספת תמונות לבקשה למודלים (למשל, לצורך למידת few-shot)
אימות של סימני מים דיגיטליים באמצעות ערכות ה-SDK
כדי לוודא שלתמונה יש סימן מים, אפשר להעלות אותה ל-Vertex AI Studio באמצעות הכרטיסייה Media.יצירת 'תמונות חיות' מטקסט (יצירת קובץ MP4)
יצירת תמונות באמצעות סגנון מוגדר מראש
הפעלת
includeSafetyAttributes
, כלומר אי אפשר להחזיר את הערכיםsafetyAttributes.categories
ו-safetyAttributes.scores
השבתת שיפור ההנחיה (הפרמטר
enhancePrompt
). המשמעות היא שכלי לשכתוב הנחיות שמבוסס על LLM תמיד יוסיף באופן אוטומטי פרטים נוספים להנחיה שסופקה כדי לספק תמונות באיכות גבוהה יותר שמשקפות טוב יותר את ההנחיה שסופקה.כתיבת תמונה שנוצרה ישירות ב-Google Cloud Storage כחלק מהתגובה מהמודל (הפרמטר
storageUri
). במקום זאת, התמונות תמיד מוחזר בתגובה כבייט של תמונה בקידוד base64.
אם רוצים להעלות תמונה שנוצרה ב-Cloud Storage, אפשר להשתמש ב-Cloud Storage for Firebase.
מפרטים ומגבלות
מגבלות (לכל בקשה) | Imagen 3 | Imagen 3 Fast |
---|---|---|
המספר המקסימלי של אסימוני קלט | 480 אסימונים | 480 אסימונים |
מספר התמונות המקסימלי בפלט | 4 תמונות | 4 תמונות |
רזולוציות תמונות פלט נתמכות (פיקסלים) |
|
|
מה עוד אפשר לעשות?
-
כדאי להתחיל לחשוב על ההכנות לסביבת הייצור (ראו רשימת המשימות לסביבת הייצור), כולל:
- הגדרת Firebase App Check כדי להגן על Gemini API מפני ניצול לרעה על ידי לקוחות לא מורשים.
- שילוב Firebase Remote Config כדי לעדכן ערכים באפליקציה (כמו שם הדגם) בלי לפרסם גרסה חדשה של האפליקציה.
איך שולטים ביצירת תוכן
- הסבר על תכנון הנחיות, כולל שיטות מומלצות, אסטרטגיות והנחיות לדוגמה.
- להגדיר את הפרמטרים של מודל Imagen כמו יחס גובה-רוחב, יצירת אנשים והוספת סימני מים.
- שימוש בהגדרות הבטיחות כדי לשנות את הסבירות לקבלת תשובות שעשויות להיחשב כמזיקות.
מידע נוסף על המודלים הנתמכים
כאן תוכלו לקרוא מידע נוסף על המודלים הזמינים לתרחישי שימוש שונים, על המכסות ועל התמחור שלהם.שליחת משוב על חוויית השימוש ב-Firebase AI Logic