批量转换jpg到谷歌文档在超过6分钟?



我看过下面链接中的一篇文章:

批量转换jpg到Google Docs

批量转换jpg到Google Docs

在这篇文章中,他们发布了一个脚本,用于使用OCR将批处理照片转换为google doc。

这是一个伟大的回应。但是6分钟的限制呢?你能做点什么吗?或者至少以某种方式,在第二次执行时,它不会再次重复转换后的照片,而只是继续它离开的地方。

对不起,如果我懂编程就不会打扰你了。我搜索了很多,找到了一堆脚本,但无论我做什么,我都无法编辑它们,使其适合我想要的脚本。

谢谢

我相信你的目标如下。

  • 您想要使用Google Apps Script将JPEG文件转换为Google Document。
  • 在您的情况下,有很多JPEG文件。所以你想减少脚本的过程成本(在批量转换jpg到谷歌文档)转换。

问题和解决方法:

在这种情况下,我建议使用批处理请求来实现您的目标。您可以在这里看到批处理请求的样例脚本。但是,我认为批处理请求的请求体的创建有点复杂。所以,在这个答案中,我想建议使用谷歌应用程序脚本库(BatchRequest)来实现你的目标。当然,如果您不想使用这个库,您可以通过修改这里的示例脚本来创建脚本。

用法:

1。安装Google Apps Script库

你可以在https://github.com/tanaikech/BatchRequest#how-to-install上看到它。

2。示例脚本。

使用库的样例脚本如下所示。请将以下脚本复制粘贴到脚本编辑器中,并根据实际情况设置srcFolderIddstFolderId的变量。并且,请在高级Google服务中启用Drive API。请运行myFunction

function myFunction() {
const srcFolderId = "###";  // Please set the folder ID of the folder including JPEG files.
const dstFolderId = "###";  // Please set the folder ID of the destination folder.
// 1. Retrieve file list of JPEG files using files.list method in Drive API.
const headers = {authorization: `Bearer ${ScriptApp.getOAuthToken()}`};
const q = `'${srcFolderId}' in parents and mimeType='${MimeType.JPEG}' and trashed=false`;
const url = `https://www.googleapis.com/drive/v3/files?pageSize=1000&q=${q}&fields=${encodeURIComponent("nextPageToken,files(id)")}`;
let pageToken = "";
let files = [];
do {
const res = UrlFetchApp.fetch(url + "&pageToken=" + pageToken, {headers: headers, muteHttpExceptions: true});
if (res.getResponseCode() != 200) throw new Error(res.getContentText());
const obj = JSON.parse(res.getContentText());
files = files.concat(obj.files);
pageToken = obj.nextPageToken || "";
} while(pageToken);
// 2. Convert JPEG files to Google Document using files.copy method in Drive API. In this case, this is run with the batch process.
const requests = files.map(({id}) => ({
method: "POST",
endpoint: `https://www.googleapis.com/drive/v3/files/${id}/copy`,
requestBody: {parents: [dstFolderId], mimeType: MimeType.GOOGLE_DOCS},
}));
const res = BatchRequest.EDo({batchPath: "batch/drive/v3", requests: requests});
console.log(res);
}

注意:

  • 当使用批处理请求时,每个请求都与异步进程一起运行。所以我认为工艺成本会比https://stackoverflow.com/a/53698250低。但是,不幸的是,从你的问题中,我无法理解你想要转换的JPEG文件的数量和文件大小。所以我不确定上面的样例脚本是否可以直接解决你的问题。当出现错误时,请显示它。而且,如果有无法转换的文件,它们可能无法被Drive API转换。

引用:

  • 批量申请公文
  • 文件:<
  • 文件:副本/gh>
  • GAS库的BatchRequest
  • 相关问题。
    • 如何在Google Apps Script中使用UrlFetchApp进行驱动器API批处理请求
    • 使用驱动API/DriveApp从pdf转换到谷歌文档
    • Google Calendar API批量插入事件

是否有必要在谷歌应用程序脚本中这样做?如果没有,您可以使用google API来完成此操作。例如,您从Google developer创建一个身份验证令牌,然后使用您最喜欢的编程语言向Google端点发出请求-此方法没有超时(与Google app脚本不同)

编辑

根据您的要求。首先,转到这里,按照步骤1andstep2获取所需凭证的说明,以及安装python的Google客户端库(在我的情况下是python 3.8)

我已经将源代码分解为两个文件(因此复制下面代码的每个部分并将它们保存在他们尊敬的python文件-.py文件扩展名中)

credential.py(文件名)

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']
def cred():

creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
drive = build('drive', 'v2', credentials=creds)
return drive

image_to_doc.py(文件名)

"""
Convert image file to doc
"""
from apiclient import errors
from credentials import cred
def retrieve_all_files():
"""Retrieve a list of File resources. 
Returns:
List IDs of File resources.
"""
FOLDER_ID = YOUR_FOLDER_ID # Make sure only image files are on this Folder.
result_tmp = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = cred().children().list(folderId=FOLDER_ID, **param).execute()
result_tmp.extend(files['items'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError as error:
print(f'An error occurred: {error}')
break
result = [r['id'] for r in result_tmp]
return result
def convert(ids):
"""
If you have deleted files(less than 30 days, if you have the feature turned on) on the folder,
they will be included on the files to be converted. To get over this, delete the deleted file(s)
from the trash folder(delete forever)
"""
drive = cred()
try:
for id in ids:
copy_file = drive.files().copy(
fileId=id,
body=None, ocr=True).execute()
# print(copy_file['id'])
except errors.HttpError as error:
print(f'An error occurred: {error}')
def main():
files = retrieve_all_files()
convert(files)
if __name__ == "__main__":
main()

你可以用python image_to_doc.py

运行它它的作用是创建一个google doc副本(使用OCR)文件夹

中的每个图像

最新更新