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

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

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

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

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


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

قبل از شروع

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

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

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

قبل از امتحان کردن این نمونه، مطمئن شوید که بخش قبل از شروع این راهنما را تکمیل کرده اید.

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

سویفت

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

import FirebaseVertexAI

// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()

// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.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 Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.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 Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
        .generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

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 { getVertexAI, getGenerativeModel } from "firebase/vertexai";

// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
      FirebaseVertexAI.instance.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);

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

جریان پاسخ

قبل از امتحان کردن این نمونه، مطمئن شوید که بخش قبل از شروع این راهنما را تکمیل کرده اید.

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



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

برای کسب اطلاعات دقیق در مورد موارد زیر به "فایل های ورودی پشتیبانی شده و الزامات برای 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، ویدیو و صدا باشند.
  • به فکر آماده شدن برای تولید، از جمله راه‌اندازی Firebase App Check برای محافظت از Gemini API در برابر سوء استفاده توسط مشتریان غیرمجاز باشید. همچنین، حتماً چک لیست تولید را مرور کنید.

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

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

همچنین می‌توانید با استفاده از Vertex AI Studio ، دستورات و پیکربندی‌های مدل را آزمایش کنید.

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

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


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