Обнаружение текста документа PDF / TIFF gcsDestinationBucketName - PullRequest
0 голосов
/ 22 мая 2019

Я работаю над преобразованием PDF в текстовые файлы с помощью API облачного видения Google.

Я получил начальную справку по коду с этой стороны, преобразование изображения в текст прекрасно работает с ключом json, который я получил при регистрации иактивация,

вот код, который я получил для преобразования pdf в текст

private static object DetectDocument(string gcsSourceUri,
string gcsDestinationBucketName, string gcsDestinationPrefixName)
{
var client = ImageAnnotatorClient.Create();

var asyncRequest = new AsyncAnnotateFileRequest
{
    InputConfig = new InputConfig
    {
        GcsSource = new GcsSource
        {
            Uri = gcsSourceUri
        },
        // Supported mime_types are: 'application/pdf' and 'image/tiff'
        MimeType = "application/pdf"
    },
    OutputConfig = new OutputConfig
    {
        // How many pages should be grouped into each json output file.
        BatchSize = 2,
        GcsDestination = new GcsDestination
        {
            Uri = $"gs://{gcsDestinationBucketName}/{gcsDestinationPrefixName}"
        }
    }
};

asyncRequest.Features.Add(new Feature
{
    Type = Feature.Types.Type.DocumentTextDetection
});

List<AsyncAnnotateFileRequest> requests =
    new List<AsyncAnnotateFileRequest>();
requests.Add(asyncRequest);

var operation = client.AsyncBatchAnnotateFiles(requests);

Console.WriteLine("Waiting for the operation to finish");

operation.PollUntilCompleted();

// Once the rquest has completed and the output has been
// written to GCS, we can list all the output files.
var storageClient = StorageClient.Create();

// List objects with the given prefix.
var blobList = storageClient.ListObjects(gcsDestinationBucketName,
    gcsDestinationPrefixName);
Console.WriteLine("Output files:");
foreach (var blob in blobList)
{
    Console.WriteLine(blob.Name);
}

// Process the first output file from GCS.
// Select the first JSON file from the objects in the list.
var output = blobList.Where(x => x.Name.Contains(".json")).First();

var jsonString = "";
using (var stream = new MemoryStream())
{
    storageClient.DownloadObject(output, stream);
    jsonString = System.Text.Encoding.UTF8.GetString(stream.ToArray());
}

var response = JsonParser.Default
            .Parse<AnnotateFileResponse>(jsonString);

// The actual response for the first page of the input file.
var firstPageResponses = response.Responses[0];
var annotation = firstPageResponses.FullTextAnnotation;

// Here we print the full text from the first page.
// The response contains more information:
// annotation/pages/blocks/paragraphs/words/symbols
// including confidence scores and bounding boxes
Console.WriteLine($"Full text: \n {annotation.Text}");

return 0;
}

эта функция требует 3 параметра: строка gcsSourceUri, строка gcsDestinationBucketName, строка gcsDestinationPrefixName

я не знаюпонять, какое значение я должен установить для этих 3-х параметров.Я никогда не работал над сторонним API, так что это немного сбивает меня с толку

1 Ответ

1 голос
/ 06 июня 2019

Предположим, у вас есть ведро GCS с именем 'giri_bucket' и вы положили pdf в корень хранилища 'test.pdf'.Если вы хотите записать результаты операции в одно и то же ведро, вы можете установить следующие аргументы:

  • gcsSourceUri: 'gs: //giri_bucket/test.pdf'
  • gcsDestinationBucketName: 'giri_bucket'
  • gcsDestinationPrefixName: 'async_test'

Когда операция завершится, в вашем GCS-хранилище будет 1 или более выходных файлов по адресу giri_bucket / async_test.

Если хотите, вы можете даже записать свой вывод в другое ведро.Вам просто нужно убедиться, что ваше gcsDestinationBucketName + gcsDestinationPrefixName уникально.

Подробнее о формате запроса вы можете прочитать в документации: AsyncAnnotateFileRequest

...