API di correzione bozza di IA generativa

Con l'API GenAI Proofreading di ML Kit, puoi aiutare gli utenti a controllare la grammatica e l'ortografia di brevi testi.

Funzionalità chiave

  • Rileggere il testo inserito tramite tastiera o voce
  • Le richieste restituiranno almeno un suggerimento. Se vengono restituiti più suggerimenti, i risultati verranno ordinati in base alla confidenza decrescente.

Risultati di esempio

Ingresso

Tipo di input

Output

questo è un breve messaggio

Tastiera

Questo è un messaggio breve

Il progetto è quasi completato, ma deve essere rivisto

Tastiera

Il progetto è quasi completato, ma deve essere rivisto

Incontratemi all'orso,

Voce

Ci vediamo al bar.

Per iniziare

Per iniziare a utilizzare l'API GenAI Proofreading, aggiungi questa dipendenza al file di build del progetto.

implementation("com.google.mlkit:genai-proofreading:1.0.0-beta1")

Quindi, configura e ottieni un client Proofreader con impostazioni specifiche per la lingua e il tipo di input. Controlla e assicurati che le funzionalità del modello sul dispositivo necessarie siano disponibili (attivando un download, se necessario). Invia il testo che vuoi analizzare in un ProofreadingRequest, esegui l'inferenza di correzione bozze e infine elabora i suggerimenti restituiti per correggere il testo.

Kotlin

val textToProofread = "The praject is compleet but needs too be reviewd"

// Define task with required input and output format
val options = ProofreaderOptions.builder(context)
    // InputType can be KEYBOARD or VOICE. VOICE indicates that
    // the user generated text based on audio input.
    .setInputType(ProofreaderOptions.InputType.KEYBOARD)
    // Refer to ProofreaderOptions.Language for available
    // languages
    .setLanguage(ProofreaderOptions.Language.ENGLISH)
    .build()
val proofreader = Proofreading.getClient(options)

suspend fun prepareAndStartProofread() {
    // Check feature availability, status will be one of the
    // following: UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
    val featureStatus = proofreader.checkFeatureStatus().await()

    if (featureStatus == FeatureStatus.DOWNLOADABLE) {
        // Download feature if necessary.
        // If downloadFeature is not called, the first inference
        // request will also trigger the feature to be downloaded
        // if it's not already downloaded.
        proofreader.downloadFeature(object : DownloadCallback {
            override fun onDownloadStarted(bytesToDownload: Long) { }

            override fun onDownloadFailed(e: GenAiException) { }

            override fun onDownloadProgress(
                totalBytesDownloaded: Long
            ) {}

            override fun onDownloadCompleted() {
                startProofreadingRequest(textToProofread, proofreader)
            }
        })
    } else if (featureStatus == FeatureStatus.DOWNLOADING) {
        // Inference request will automatically run once feature is
        // downloaded.
        // If Gemini Nano is already downloaded on the device, the
        // feature-specific LoRA adapter model will be downloaded
        // very quickly. However, if Gemini Nano is not already
        // downloaded, the download process may take longer.
        startProofreadingRequest(textToProofread, proofreader)
    } else if (featureStatus == FeatureStatus.AVAILABLE) {
        startProofreadingRequest(textToProofread, proofreader)
    }
}

suspend fun startProofreadingRequest(
    text: String, proofreader: Proofreader
) {
    // Create task request
    val proofreadingRequest =
        ProofreadingRequest.builder(text).build()

    // Start proofreading request with non-streaming response
    // More than 1 result may be returned. If multiple suggestions
    // are returned, results will be sorted by descending confidence.
    val proofreadingResults =
        proofreader.runInference(proofreadingRequest).await().results

    // You can also start a streaming request
    // proofreader.runInference(proofreadingRequest) { newText ->
    //     // show new text in UI
    // }
}

// Be sure to release the resource when no longer needed
// For example, on viewModel.onCleared() or activity.onDestroy()
proofreader.close()

Java

String textToProofread = "The praject is compleet but needs too be reviewd";

// Define task with required input and output format
ProofreaderOptions proofreaderOptions = 
    ProofreaderOptions
        .builder(context)
        // InputType can be KEYBOARD or VOICE. VOICE indicates that the
        // user generated text based on audio input.
        .setInputType(ProofreaderOptions.InputType.KEYBOARD)
        // Refer to ProofreaderOptions.Language for available languages
        .setLanguage(ProofreaderOptions.Language.ENGLISH)
        .build();
Proofreader proofreader = Proofreading.getClient(proofreaderOptions);

void prepareAndStartProofread(Context context) throws ExecutionException,
        InterruptedException {
    // Check feature availability, status will be one of the following:
    // UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
    try {
        int featureStatus = proofreader.checkFeatureStatus().get();
        if (featureStatus == FeatureStatus.DOWNLOADABLE) {
            // Download feature if necessary.
            // If downloadFeature is not called, the first inference request
            // will also trigger the feature to be downloaded if it's not
            // already downloaded.
            proofreader.downloadFeature(new DownloadCallback() {
                @Override
                public void onDownloadCompleted() {
                    startProofreadingRequest(textToProofread, proofreader);
                }

                @Override
                public void onDownloadFailed(GenAiException e) {
                }

                @Override
                public void onDownloadProgress(long totalBytesDownloaded) {
                }

                @Override
                public void onDownloadStarted(long bytesDownloaded) {
                }
            });
        } else if (featureStatus == FeatureStatus.DOWNLOADING) {
            // Inference request will automatically run once feature is
            // downloaded.
            // If Gemini Nano is already downloaded on the device, the
            // feature-specific LoRA adapter model will be downloaded
            // very quickly. However, if Gemini Nano is not already
            // downloaded, the download process may take longer.
            startProofreadingRequest(textToProofread, proofreader);
        } else if (featureStatus == FeatureStatus.AVAILABLE) {
            startProofreadingRequest(textToProofread, proofreader);
        }
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    }
}

void startProofreadingRequest(String text, Proofreader proofreader) {
    // Create task request
    ProofreadingRequest proofreadingRequest = ProofreadingRequest
            .builder(text).build();

    try {
        // Start proofreading request with non-streaming response
        // More than 1 result may be returned. If multiple suggestions are
        // returned, results will be sorted by descending confidence.
        proofreader.runInference(proofreadingRequest).get().getResults();

        // You can also start a streaming request
        // proofreader.runInference(proofreadingRequest, newText -> {
        //     // Show new text in UI
        // });
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    }
}

// Be sure to release the resource when no longer needed
// For example, on viewModel.onCleared() or activity.onDestroy()
proofreader.close();

Come il modello gestisce diversi tipi di input

Quando il modello dispone di maggiori informazioni su come l'utente ha inserito il testo (tastiera o voce), può prevedere meglio il tipo di errori che potrebbero essere presenti. Il testo inserito con la tastiera è più soggetto a errori ortografici con i tasti vicini, mentre il testo inserito con la voce è più soggetto a errori ortografici di parole con la stessa pronuncia.

Funzionalità supportate e limitazioni

La correzione bozze è supportata per le seguenti lingue: inglese, giapponese, francese, tedesco, italiano, spagnolo e coreano, definite in ProofreaderOptions.Language. L'input deve contenere meno di 256 token.

La disponibilità della configurazione di funzionalità specifica (specificata da ProofreaderOptions) può variare in base alla configurazione del dispositivo specifico e ai modelli scaricati sul dispositivo.

Il modo più affidabile per gli sviluppatori per assicurarsi che la funzionalità API prevista sia supportata su un dispositivo con ProofreaderOptions richiesto è chiamare il metodo checkFeatureStatus(). Questo metodo fornisce lo stato definitivo della disponibilità delle funzionalità sul dispositivo in fase di runtime.

Problemi di configurazione comuni

Le API ML Kit GenAI si basano sull'app Android AI Core per accedere a Gemini Nano. Quando un dispositivo viene appena configurato (incluso il ripristino) o l'app AICore viene appena ripristinata (ad es. cancellazione dei dati, disinstallazione e reinstallazione), l'app AICore potrebbe non avere tempo sufficiente per completare l'inizializzazione (incluso il download delle configurazioni più recenti dal server). Di conseguenza, le API ML Kit GenAI potrebbero non funzionare come previsto. Di seguito sono riportati i messaggi di errore di configurazione comuni che potresti visualizzare e come gestirli:

Esempio di messaggio di errore Come gestirla
AICore non è riuscito a eseguire l'operazione con il tipo di errore 4-CONNECTION_ERROR e il codice di errore 601-BINDING_FAILURE: il servizio AICore non è riuscito a eseguire il binding. Ciò può accadere quando installi l'app utilizzando le API ML Kit GenAI immediatamente dopo la configurazione del dispositivo o quando AICore viene disinstallato dopo l'installazione dell'app. L'aggiornamento dell'app AICore e la reinstallazione dell'app dovrebbero risolvere il problema.
AICore non è riuscito a completare l'operazione con il tipo di errore 3 - PREPARATION_ERROR e il codice di errore 606 - FEATURE_NOT_FOUND: la funzionalità ... non è disponibile. Ciò può accadere quando AICore non ha completato il download delle configurazioni più recenti. Quando il dispositivo è connesso a internet, l'aggiornamento richiede in genere da pochi minuti a qualche ora. Il riavvio del dispositivo può velocizzare l'aggiornamento.

Tieni presente che se il bootloader del dispositivo è sbloccato, visualizzerai anche questo errore. Questa API non supporta i dispositivi con bootloader sbloccati.
AICore non è riuscito a completare l'operazione con il tipo di errore 1-DOWNLOAD_ERROR e il codice di errore 0-UNKNOWN: Feature ... failed with failure status 0 and error esz: UNAVAILABLE: Unable to resolve host ... Mantieni la connessione di rete, attendi qualche minuto e riprova.