Sanket Tarodekar
Sanket Tarodekar

Reputation: 302

OCR images from google drive using Google App Script

I have implemented following script to do OCR on single and multiple images using image URL.

function doOCRALL() {
  var selected = SpreadsheetApp.getActiveSheet().getActiveRange().getValues().length;
  for (var i = 0; i < selected; i++) {
    var activeCol = SpreadsheetApp.getActiveSheet().getActiveCell().getColumn();
    var activeRow = SpreadsheetApp.getActiveSheet().getActiveCell().getRow();
    var valueURL = SpreadsheetApp.getActiveSheet().getRange(activeRow + i, activeCol).getValue();

    var image = UrlFetchApp.fetch(valueURL).getBlob();

    var file = {
      title: 'OCR File',
      mimeType: 'image/png'
    };

    // OCR is supported for PDF and image formats
    file = Drive.Files.insert(file, image, {ocr: true});
    var doc = DocumentApp.openByUrl(file.embedLink);
    var body = doc.getBody().getText();
    //Get link Doc that Generated
    SpreadsheetApp.getActiveSheet().getRange(activeRow + i, activeCol + 2).setValue(file.embedLink);
    //Get Content of Doc that Generated
    SpreadsheetApp.getActiveSheet().getRange(activeRow + i, activeCol + 1).setValue(body);

  }
}


function doOCR() {
  //
  var activeCol = SpreadsheetApp.getActiveSheet().getActiveCell().getColumn();
  var activeRow = SpreadsheetApp.getActiveSheet().getActiveCell().getRow();

  var valueURL = SpreadsheetApp.getActiveSheet().getRange(activeRow, activeCol).getValue();

  var image = UrlFetchApp.fetch(valueURL).getBlob();

  var file = {
    title: 'OCR File',
    mimeType: 'image/png'
  };

  // OCR is supported for PDF and image formats
  file = Drive.Files.insert(file, image, {ocr: true});
  var doc = DocumentApp.openByUrl(file.embedLink);
  var body = doc.getBody().getText();


  // Print the Google Document URL in the console
  Logger.log("body: %s", body);
  Logger.log("File URL: %s", file.embedLink);
  //Get link Doc that Generated
  SpreadsheetApp.getActiveSheet().getRange(activeRow, activeCol + 2).setValue(file.embedLink);
  //Get Content of Doc that Generated
  SpreadsheetApp.getActiveSheet().getRange(activeRow, activeCol + 1).setValue(body);
}



function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('OCR Tools')
      .addItem('Extract Cell', 'doOCR')
      .addItem('Extract All Cell', 'doOCRALL')
      .addSeparator()
      .addSubMenu(ui.createMenu('About US')
          .addItem('Infomation', 'menuItem2'))
      .addToUi();
}

function menuItem2() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .alert('AIO Team');
}

When I provide an image URL for any image, it works. But if I upload the same image on my drive and then provide the image URL from drive, it only gives me "Sign in Main menu". For other drive images it gives the same text. Thanks in advance.

Upvotes: 3

Views: 4865

Answers (1)

tehhowch
tehhowch

Reputation: 9872

If content is already in Drive, you do not need to get a link to it - just supply the file id (which you can get from a link to it).

Once you have the file ID, you can simply copy it, and use the optimal arguments to activate OCR. The full options list is, of course, available on the Drive REST API page: https://developers.google.com/drive/api/v2/reference/files/copy#parameters I encourage you to also read about best practices such as fields specification (which is a requirement of the more recent drive API version).

This function takes an input Drive file ID that you got from somewhere, and a truth-y value to set the "use OCR" option. Obvious assumptions are that you have permission, the id is valid, you have enabled the advanced service and the Drive API in cloud console, etc.

function getIdOfCopyOfDriveFile(fileId, useOcr) {
  const options = {
    fields: "choose the metadata fields to return in the response e.g. 'id,title,parents'"
  };
  const existingMetaData = Drive.Files.get(fileId, options);

  options.ocr = !!useOcr;
  existingMetaData.title += " (copied with" + (options.ocr ? " " : "out ") + "ocr)";
  // We could do other modifications of fields we requested before
  // copying, like changing the parents array to move the new file.
  const newFileMetaData = Drive.Files.copy(existingMetaData, fileId, options);
  return newFileMetaData.id;
}

Upvotes: 3

Related Questions