Embed PNG
import gslides
from gslides import Presentation, Table
import pandas as pd
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import os.path
import json
import matplotlib.pyplot as plt
import numpy as np
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import base64
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/presentations',
'https://www.googleapis.com/auth/drive.file']
def get_credentials():
creds = None
# The file token.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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.json', 'w') as token:
token.write(creds.to_json())
return creds
# Get credentials
credentials = get_credentials()
# Initialize gslides
gslides.initialize_credentials(credentials)
# Create a new presentation
presentation = Presentation.create(name='Test Presentation')
presentation_id = presentation.presentation_id
# Create a title slide
presentation.add_slide(
objects=[], # Empty objects list for title slide
layout=(1,1),
title="Test Presentation",
notes="Created using gslides"
)
# Create a slide with a table
table_data = pd.DataFrame({
'Metric': ['Metric A', 'Metric B'],
'Value': [0.85, 0.92],
'Status': ['Good', 'Excellent']
})
table = Table(data=table_data)
# Create a slide with the table
presentation.add_slide(
objects=[table],
layout=(1,1),
title="Sample Metrics",
notes="Example table showing metrics"
)
# Create a mock figure
plt.figure(figsize=(10, 6))
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, 'b-', linewidth=2)
plt.title('Sample Sine Wave', fontsize=14)
plt.xlabel('Time', fontsize=12)
plt.ylabel('Amplitude', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
# Save the figure with white background
plt.savefig('mock_figure.png', dpi=300, bbox_inches='tight', facecolor='white')
plt.close()
# Use Google Slides API directly to add the image
slides_service = build('slides', 'v1', credentials=credentials)
# Create a new slide with BLANK layout
requests = [
{
'createSlide': {
'slideLayoutReference': {
'predefinedLayout': 'BLANK'
}
}
}
]
# Execute the request
response = slides_service.presentations().batchUpdate(
presentationId=presentation_id,
body={'requests': requests}
).execute()
# Get the new slide ID
slide_id = response['replies'][0]['createSlide']['objectId']
# Upload the image to Drive and make it publicly accessible
drive_service = build('drive', 'v3', credentials=credentials)
file_metadata = {
'name': 'mock_figure.png',
'role': 'reader',
'type': 'anyone'
}
media = MediaFileUpload('mock_figure.png', mimetype='image/png')
file = drive_service.files().create(
body=file_metadata,
media_body=media,
fields='id, webContentLink'
).execute()
# Make the file publicly accessible
drive_service.permissions().create(
fileId=file.get('id'),
body={'type': 'anyone', 'role': 'reader'},
fields='id'
).execute()
# Get the direct download URL
file_id = file.get('id')
image_url = f'https://drive.google.com/uc?export=download&id={file_id}'
# Add title and image to the slide
requests = [
# Add title
{
'createShape': {
'objectId': 'TITLE_ID',
'shapeType': 'TEXT_BOX',
'elementProperties': {
'pageObjectId': slide_id,
'size': {
'width': {'magnitude': 6000000, 'unit': 'EMU'},
'height': {'magnitude': 800000, 'unit': 'EMU'}
},
'transform': {
'scaleX': 1,
'scaleY': 1,
'translateX': 1500000,
'translateY': 400000,
'unit': 'EMU'
}
}
}
},
# Add title text
{
'insertText': {
'objectId': 'TITLE_ID',
'text': 'Sample Figure: Sine Wave'
}
},
# Style the title
{
'updateTextStyle': {
'objectId': 'TITLE_ID',
'style': {
'fontSize': {'magnitude': 24, 'unit': 'PT'},
'bold': True
},
'textRange': {
'type': 'ALL'
},
'fields': 'fontSize,bold' # Specify which fields to update
}
},
# Add the image
{
'createImage': {
'url': image_url,
'elementProperties': {
'pageObjectId': slide_id,
'size': {
'width': {'magnitude': 6000000, 'unit': 'EMU'},
'height': {'magnitude': 4000000, 'unit': 'EMU'}
},
'transform': {
'scaleX': 1,
'scaleY': 1,
'translateX': 1500000,
'translateY': 1500000,
'unit': 'EMU'
}
}
}
}
]
# Execute the requests
slides_service.presentations().batchUpdate(
presentationId=presentation_id,
body={'requests': requests}
).execute()
print(f"Presentation created! ID: {presentation_id}")
# Clean up the temporary image file
if os.path.exists('mock_figure.png'):
os.remove('mock_figure.png')
Last updated