اسناد (مانند PDF) را با استفاده از Gemini API تجزیه و تحلیل کنید

می‌توانید از یک مدل Gemini بخواهید فایل‌های سند (مانند فایل‌های PDF و فایل‌های متن ساده) را که به صورت درون خطی (با کدگذاری پایه 64) یا از طریق URL ارائه می‌کنید، تجزیه و تحلیل کند. وقتی از Firebase AI Logic استفاده می‌کنید، می‌توانید این درخواست را مستقیماً از برنامه خود ارسال کنید.

با این قابلیت می توانید کارهایی مانند:

  • نمودارها، نمودارها و جداول داخل اسناد را تجزیه و تحلیل کنید
  • استخراج اطلاعات به فرمت های خروجی ساخت یافته
  • به سوالات مربوط به محتوای تصویری و متنی در اسناد پاسخ دهید
  • اسناد را خلاصه کنید
  • رونویسی محتوای سند (مثلاً به HTML)، حفظ طرح‌بندی و قالب‌بندی، برای استفاده در برنامه‌های پایین دستی (مانند خطوط لوله RAG)

پرش به نمونه کد پرش به کد برای پاسخ های جریانی


سایر راهنماها را برای گزینه های اضافی برای کار با اسناد (مانند PDF) ببینید
ایجاد خروجی ساختاریافته چت چند نوبتی

قبل از شروع

برای مشاهده محتوا و کد ارائه دهنده خاص در این صفحه، روی ارائه دهنده API Gemini خود کلیک کنید.

اگر قبلاً این کار را نکرده‌اید، راهنمای شروع را کامل کنید، که نحوه راه‌اندازی پروژه Firebase را توضیح می‌دهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Backend را برای ارائه‌دهنده API Gemini انتخابی خود مقداردهی کنید و یک نمونه GenerativeModel ایجاد کنید.

برای آزمایش و تکرار در درخواست‌های خود و حتی دریافت یک قطعه کد تولید شده، توصیه می‌کنیم از Google AI Studio استفاده کنید.

تولید متن از فایل‌های PDF (با پایه 64 کدگذاری شده)

قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید.
در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید .

می‌توانید از یک مدل Gemini بخواهید که متنی را با درخواست متن و فایل‌های PDF تولید کند—با ارائه mimeType هر فایل ورودی و خود فایل. الزامات و توصیه‌های مربوط به فایل‌های ورودی را بعداً در این صفحه پیدا کنید.

سویفت

برای تولید متن از ورودی چند وجهی متن و PDF، می‌توانید generateContent() فراخوانی کنید.


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")


// Provide the PDF as `Data` with the appropriate MIME type
let pdf = try InlineDataPart(data: Data(contentsOf: pdfURL), mimeType: "application/pdf")

// Provide a text prompt to include with the PDF file
let prompt = "Summarize the important results in this report."

// To generate text output, call `generateContent` with the PDF file and text prompt
let response = try await model.generateContent(pdf, prompt)

// Print the generated text, handling the case where it might be nil
print(response.text ?? "No text in response.")

Kotlin

برای تولید متن از ورودی چند وجهی متن و PDF، می‌توانید generateContent() فراخوانی کنید.

برای Kotlin، روش‌های موجود در این SDK توابع تعلیق هستند و باید از یک محدوده Coroutine فراخوانی شوند.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")


val contentResolver = applicationContext.contentResolver

// Provide the URI for the PDF file you want to send to the model
val inputStream = contentResolver.openInputStream(pdfUri)

if (inputStream != null) {  // Check if the PDF file loaded successfully
    inputStream.use { stream ->
        // Provide a prompt that includes the PDF file specified above and text
        val prompt = content {
            inlineData(
                bytes = stream.readBytes(),
                mimeType = "application/pdf" // Specify the appropriate PDF file MIME type
            )
            text("Summarize the important results in this report.")
        }

        // To generate text output, call `generateContent` with the prompt
        val response = generativeModel.generateContent(prompt)

        // Log the generated text, handling the case where it might be null
        Log.d(TAG, response.text ?: "")
    }
} else {
    Log.e(TAG, "Error getting input stream for file.")
    // Handle the error appropriately
}

Java

برای تولید متن از ورودی چند وجهی متن و PDF، می‌توانید generateContent() فراخوانی کنید.

برای جاوا، روش‌های موجود در این SDK یک ListenableFuture برمی‌گردانند.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


ContentResolver resolver = getApplicationContext().getContentResolver();

// Provide the URI for the PDF file you want to send to the model
try (InputStream stream = resolver.openInputStream(pdfUri)) {
    if (stream != null) {
        byte[] audioBytes = stream.readAllBytes();
        stream.close();

        // Provide a prompt that includes the PDF file specified above and text
        Content prompt = new Content.Builder()
              .addInlineData(audioBytes, "application/pdf")  // Specify the appropriate PDF file MIME type
              .addText("Summarize the important results in this report.")
              .build();

        // To generate text output, call `generateContent` with the prompt
        ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
        Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
            @Override
            public void onSuccess(GenerateContentResponse result) {
                String text = result.getText();
                Log.d(TAG, (text == null) ? "" : text);
            }
            @Override
            public void onFailure(Throwable t) {
                Log.e(TAG, "Failed to generate a response", t);
            }
        }, executor);
    } else {
        Log.e(TAG, "Error getting input stream for file.");
        // Handle the error appropriately
    }
} catch (IOException e) {
    Log.e(TAG, "Failed to read the pdf file", e);
} catch (URISyntaxException e) {
    Log.e(TAG, "Invalid pdf file", e);
}

Web

برای تولید متن از ورودی چند وجهی متن و PDF، می‌توانید generateContent() فراخوانی کنید.


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 a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });


// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(','));
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the PDF file
  const prompt = "Summarize the important results in this report.";

  // Prepare PDF file for input
  const fileInputEl = document.querySelector("input[type=file]");
  const pdfPart = await fileToGenerativePart(fileInputEl.files);

  // To generate text output, call `generateContent` with the text and PDF file
  const result = await model.generateContent([prompt, pdfPart]);

  // Log the generated text, handling the case where it might be undefined
  console.log(result.response.text() ?? "No text in response.");
}

run();

Dart

برای تولید متن از ورودی چند وجهی متن و PDF، می‌توانید generateContent() فراخوانی کنید.


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 a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


// Provide a text prompt to include with the PDF file
final prompt = TextPart("Summarize the important results in this report.");

// Prepare the PDF file for input
final doc = await File('document0.pdf').readAsBytes();

// Provide the PDF file as `Data` with the appropriate PDF file MIME type
final docPart = InlineDataPart('application/pdf', doc);

// To generate text output, call `generateContent` with the text and PDF file
final response = await model.generateContent([
  Content.multi([prompt,docPart])
]);

// Print the generated text
print(response.text);

وحدت

برای تولید متن از ورودی چند وجهی متن و PDF، می‌توانید GenerateContentAsync() را فراخوانی کنید.


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Provide a text prompt to include with the PDF file
var prompt = ModelContent.Text("Summarize the important results in this report.");

// Provide the PDF file as `data` with the appropriate PDF file MIME type
var doc = ModelContent.InlineData("application/pdf",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
        UnityEngine.Application.streamingAssetsPath, "document0.pdf")));

// To generate text output, call `GenerateContentAsync` with the text and PDF file
var response = await model.GenerateContentAsync(new [] { prompt, doc });

// Print the generated text
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

بیاموزید که چگونه یک مدل مناسب برای مورد استفاده و برنامه خود انتخاب کنید.

جریان پاسخ

قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید.
در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید .

می‌توانید با منتظر ماندن برای کل نتیجه تولید مدل، به تعاملات سریع‌تری برسید و در عوض از استریم برای مدیریت نتایج جزئی استفاده کنید. برای پخش جریانی پاسخ، generateContentStream را فراخوانی کنید.



الزامات و توصیه ها برای اسناد ورودی

توجه داشته باشید که فایلی که به عنوان داده های درون خطی ارائه می شود در حین انتقال روی base64 کدگذاری می شود که حجم درخواست را افزایش می دهد. اگر درخواست خیلی بزرگ باشد، خطای HTTP 413 دریافت می کنید.

برای کسب اطلاعات دقیق در مورد موارد زیر به "فایل های ورودی پشتیبانی شده و الزامات برای Vertex AI Gemini API " مراجعه کنید:

انواع MIME ویدیویی پشتیبانی شده

مدل‌های چندوجهی Gemini از انواع سند MIME زیر پشتیبانی می‌کنند:

نوع MIME سند فلش جمینی 2.0 Gemini 2.0 Flash-Lite
PDF - application/pdf
متن - text/plain

محدودیت در هر درخواست

PDFها به عنوان تصویر در نظر گرفته می شوند، بنابراین یک صفحه از یک PDF به عنوان یک تصویر در نظر گرفته می شود. تعداد صفحات مجاز در یک درخواست محدود به تعداد تصاویری است که مدل می تواند پشتیبانی کند:

  • Gemini 2.0 Flash و Gemini 2.0 Flash-Lite :
    • حداکثر تعداد فایل در هر درخواست: 3000
    • حداکثر صفحه در هر فایل: 1000
    • حداکثر حجم هر فایل: 50 مگابایت



چه کار دیگری می توانید انجام دهید؟

  • قبل از ارسال پیام های طولانی به مدل، نحوه شمارش نشانه ها را بیاموزید.
  • Cloud Storage for Firebase راه‌اندازی کنید تا بتوانید فایل‌های حجیم را در درخواست‌های چندوجهی خود بگنجانید و راه‌حل مدیریت‌شده‌تری برای ارائه فایل‌ها در درخواست‌ها داشته باشید. فایل‌ها می‌توانند شامل تصاویر، PDF، ویدیو و صدا باشند.
  • در مورد آماده شدن برای تولید فکر کنید (به چک لیست تولید مراجعه کنید)، از جمله:

قابلیت های دیگر را امتحان کنید

یاد بگیرید چگونه تولید محتوا را کنترل کنید

همچنین می‌توانید با فرمان‌ها و پیکربندی‌های مدل آزمایش کنید و حتی یک قطعه کد تولید شده را با استفاده از Google AI Studio دریافت کنید.

درباره مدل های پشتیبانی شده بیشتر بدانید

در مورد مدل های موجود برای موارد استفاده مختلف و سهمیه ها و قیمت آنها اطلاعات کسب کنید.


درباره تجربه خود با Firebase AI Logic بازخورد بدهید