Spaces:
Running
Running
File size: 2,559 Bytes
d8cb149 0e907e6 d8cb149 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
import os
# SCOPES for Google Docs API
SCOPES = ['https://www.googleapis.com/auth/documents']
# Authenticate and create Google Docs API service
def google_docs_auth():
creds = None
# Check if token.json exists (for existing OAuth tokens)
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If no valid credentials, go through the flow to get new ones
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)
creds = flow.run_console()
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
return build('docs', 'v1', credentials=creds)
# Functions to create a Google doc with formatted text
def create_google_doc(service, text):
# Request body for creating a new document
doc = {
'title': 'Updated Resume'
}
doc = service.documents().create(body=doc).execute()
# Document ID
doc_id = doc.get('documentId')
# Insert text into the document with:
# - Times New Roman
# - Font size of 10
requests = [
{
'insertText': {
'location': {
'index': 1,
},
'text': text
}
},
{
'updateTextStyle': {
'range': {
'startIndex': 1,
'endIndex': len(text) + 1
},
'textStyle': {
'fontSize': {
'magnitude': 10,
'unit': 'PT'
},
'weightedFontFamily': {
'fontFamily': 'Times New Roman'
}
},
'fields': 'fontSize,weightedFontFamily'
}
}
]
# Send the requests to the Google Docs API
service.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()
# Return the document URL
return f'https://docs.google.com/document/d/{doc_id}/edit' |