تحليل المستندات (مثل ملفات PDF) باستخدام واجهة برمجة التطبيقات Gemini

يمكنك أن تطلب من نموذج Gemini تحليل ملفات المستندات (مثل ملفات PDF وملفات النصوص العادية) التي تقدّمها إما مضمّنة (بترميز base64) أو من خلال عنوان URL. عند استخدام Vertex AI in Firebase، يمكنك تقديم هذا الطلب مباشرةً من تطبيقك.

باستخدام هذه الميزة، يمكنك تنفيذ إجراءات، مثل:

  • تحليل المخططات البيانية والرسومات البيانية والجداول داخل المستندات
  • استخراج المعلومات إلى تنسيقات نتائج منظَّمة
  • الإجابة عن أسئلة حول المحتوى المرئي والنصوص في المستندات
  • تلخيص المستندات
  • تحويل محتوى المستند إلى نص (مثلاً إلى HTML) مع الحفاظ على التنسيقات و التنسيقات، وذلك لاستخدامها في التطبيقات النهائية (مثل قنوات RAG)

الانتقال إلى عيّنات الرموز البرمجية الانتقال إلى الرمز البرمجي للردود التي يتم بثّها


الاطّلاع على أدلة أخرى للحصول على خيارات إضافية للعمل مع المستندات (مثل ملفات PDF)
إنشاء إخراج منظَّم المحادثة المتعدّدة المقاطع

قبل البدء

إذا لم يسبق لك ذلك، أكمِل قراءة دليل البدء الذي يوضّح كيفية إعداد مشروعك على Firebase وربط تطبيقك بـ Firebase وإضافة حزمة تطوير البرامج (SDK) وبدء خدمة Vertex AI وإنشاء مثيل GenerativeModel.

لاختبار طلباتك وتكرارها وحتى الحصول على مقتطف رمز تم إنشاؤه، ننصحك باستخدام Vertex AI Studio.

إرسال ملفات PDF (المشفَّرة بترميز base64) واستلام النصوص

يُرجى التأكد من إكمال قسم قبل البدء في هذا الدليل قبل تجربة هذا العيّنة.

يمكنك أن تطلب من نموذج Gemini إنشاء نص من خلال تقديم نص وملفات PDF، مع توفير mimeType لكل ملف إدخال والملف نفسه. يمكنك الاطّلاع على المتطلبات والاقتراحات المتعلّقة بملفات الإدخال لاحقًا في هذه الصفحة.

Swift

يمكنك استدعاء generateContent() لإنشاء نص من إدخال متعدد الوسائط للنص وملفات PDF.

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

يمكنك طلب generateContent() لإنشاء نص من إدخال متعدد الوسائط للنص وملفات PDF.

بالنسبة إلى 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

يمكنك استدعاء generateContent() لإنشاء نص من إدخال متعدد الوسائط للنص وملفات PDF.

بالنسبة إلى Java، تعرض الطرق في حزمة 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

يمكنك طلب generateContent() لإنشاء نص من إدخال متعدد الوسائط للنص وملفات PDF.

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

يمكنك طلب generateContent() لإنشاء نص من إدخال متعدد الوسائط للنص وملفات PDF.

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 للمستند Gemini 2.0 Flash Gemini 2.0 Flash‑Lite
ملف PDF‏ - application/pdf
النص: text/plain

الحدود القصوى المسموح بها لكل طلب

يتم التعامل مع ملفات PDF كصور، لذا يتم التعامل مع صفحة واحدة من ملف PDF كأحد الصور. يقتصر عدد الصفحات المسموح به في طلب البحث على عدد الصور التي يمكن للنموذج التعامل معها:

  • Gemini 2.0 Flash وGemini 2.0 Flash‑Lite:
    • الحد الأقصى لعدد الملفات في كل طلب: 3,000
    • الحد الأقصى لعدد الصفحات في كل ملف: 1,000
    • الحد الأقصى لحجم كل ملف: 50 ميغابايت



ما هي الإجراءات الأخرى التي يمكنك اتّخاذها؟

  • تعرَّف على كيفية احتساب الرموز المميّزة قبل إرسال طلبات طويلة إلى النموذج.
  • إعداد Cloud Storage for Firebase لكي تتمكّن من تضمين ملفات كبيرة في طلباتك المتعدّدة الوسائط والحصول على حلّ أكثر تنظيمًا لتقديم الملفات في طلباتك يمكن أن تتضمّن الملفات صورًا وملفات PDF وفيديوهات وملفات صوتية.
  • ابدأ التفكير في الاستعداد للنشر، بما في ذلك إعداد Firebase App Check لحماية Gemini API من إساءة استخدامها من قِبل عملاء غير مصرَّح لهم. يُرجى أيضًا مراجعة قائمة التحقّق من الإنتاج.

تجربة إمكانات أخرى

التعرّف على كيفية التحكّم في إنشاء المحتوى

يمكنك أيضًا تجربة الطلبات وإعدادات النماذج باستخدام Vertex AI Studio.

مزيد من المعلومات عن الطُرز المتوافقة

اطّلِع على مزيد من المعلومات عن النماذج المتاحة لحالات الاستخدام المختلفة واطلاعك على الحصص و الأسعار.


تقديم ملاحظات حول تجربتك مع Vertex AI in Firebase