gphotospy package¶
Submodules¶
gphotospy.album module¶
-
class
gphotospy.album.
Album
(service)¶ Bases:
object
Album manager
Examples
Example init of the album manager:
Imports
>>> from gphotospy import authorize >>> from gphotospy.album import Album
Select Secrets file
>>> CLIENT_SECRET_FILE = "gphoto_oauth.json"
Get authorization and return a service object
>>> service = authorize.init(CLIENT_SECRET_FILE)
Init the album manager
>>> album_manager = Album(service)
-
add_enrichment
(album_id: str, enrichement_type, position)¶ Generic. Use the specified versions
-
add_location
(album_id: str, location, position=None)¶ Add a location enrichment to the album, at the given position
Parameters: - album_id (str) – Id of the album to add text to
- location (Location object) – Location object, as returned from geolocate() function
- position (Position object) – Position object where to add the location. Contruct it with the set_position() function
Examples
Imports:
>>> from gphotospy.album import set_position, geolocate, POSITION
Location and position inside the album
>>> Rome = geolocate("Rome", 41.9028, 12.4964) >>> last_pos = set_position(POSITION.LAST)
Create enrichemnt
>>> album_manager.add_location(id_album, Rome, last_pos) {'id': '...'}
-
add_map
(album_id: str, origin_loc, destination_loc, position=None)¶ Add a map enrichment to the album, at the given position
Parameters: - album_id (str) – Id of the album to add text to
- origin_loc (Location object) – Location of MAP origin, as returned from geolocate() function
- destination_loc (Location object) – Location of MAP origin, as returned from geolocate() function
- position (Position object) – Position object where to add the location. Contruct it with the set_position() function
Examples
Imports:
>>> from gphotospy.album import set_position, geolocate, POSITION
Add two locations and a position inside the album
>>> Rome = geolocate("Rome", 41.9028, 12.4964) >>> Pescara = geolocate("Nice city", 42.5102, 14.1437) >>> first_pos = set_position(POSITION.FIRST)
Create enrichemnt
>>> album_manager.add_map(id_album, Pescara, Rome, first_pos) {'id': '...'}
-
add_text
(album_id: str, text: str, position=None)¶ Add a text enrichment to the album, at the given position
Parameters: - album_id (str) – Id of the album to add text to
- text (str) – Text to be added as enrichment
- position (Position object) – Position object where to add the text. Contruct it with the set_position() function
Examples
Add text enrichment
>>> album_manager.add_text(id_album, 'Test Text Enrichment') {'id': '...'}
-
batchAddMediaItems
(album_id: str, items)¶ Add a list of media items to the given album
The media items and the album must have been created by the developer via the API.
Parameters: - album_id (str) – Id of the album to add the items to
- items ([str]) – list of Ids of items to add to the album
Returns: Return type: Empty object if successfull
-
batchRemoveMediaItems
(album_id: str, items)¶ Removes a list of media items to the given album
The media items and the album must have been created by the developer via the API.
Parameters: - album_id (str) – Id of the album to add the items to
- items ([str]) – list of Ids of items to add to the album
Returns: Return type: Empty object if successfull
-
create
(title: str)¶ Creates an empty album with the given title
Parameters: title (str) – Title of the album to create Returns: Album information Return type: json object Examples
Create new album
>>> album_manager.create('test album') {'id': '...', 'title': 'test album', 'productUrl': 'https://photos.google.com/lr/album/...', 'isWriteable': True}
-
get
(id: str)¶ Returns the album info corresponding to the specified id
Parameters: id (str) – Id of the album to get Returns: Album information Return type: json object Examples
Get an iterator:
>>> album_iterator = album_manager.list()
Get next album’s id
>>> album_id = next(album_iterator).get("id")
Get album’s info based on id
>>> album_manager.get(album_id)
-
list
(show_only_created=False)¶ Iterator over the albums present in the Google Photos account
Parameters: show_only_created (bool, optional) – Set if it has to list only albums created via the API (default is set by show_only_created(), whose default is FALSE) Yields: An iterator over the list of albums Notes
Google Photo API list request returns in reality an object containing a paginated list of albums.
This function transforms the list in an iterator and takes care of pagination behind the scenes.
Since there is a maximum limit on API requests per day per project it does not seem well to ask for less than the maximum pagination possible.
However, if there are concerns of bandwith or speed, the pagination can be set by album.set_pagination(n) with 1 < n < 50, since at least 1 album must be sought and 50 is the API maximum. 20 is API default.
Examples
Get an iterator:
>>> album_iterator = album_manager.list()
Print first item:
>>> print(next(album_iterator))
Sets the share method to allow collaborative by default or not
Parameters: val (bool) – value to be set (default is False) Examples
>>> album_manager.set_collaborative_share(False)
Sets the share method to allow commentable by default or not
Parameters: val (bool) – value to be set (default is True) Examples
>>> album_manager.set_commentable_share(True)
-
set_pagination
(n: int)¶ Undocumented: see list() for more info
Shares the album with the given id and options
Parameters: - id (str) – Id of the album to be shared
- collaborative (bool, optional) – Set if the album is collabotative (default is set by set_collaborative_share(), whose default is False)
- commentable (bool, optional) – Set if the album is commentable (default is set by set_commentable_share(), whose default is True)
Returns: ShareInfo object if all went well
Return type: json object
Notes
This action is allowed only on albums which were created via the API.
Examples
Create new album and get its id:
>>> new_album = album_manager.create('test album') >>> id_album = new_album.get("id")
Share the newly created album
>>> album_manager.share(id_album) {'sharedAlbumOptions': {'isCommentable': True}, 'shareableUrl': 'https://photos.app.goo.gl/...', 'shareToken': '...', 'isJoined': True, 'isOwned': True}
Unshare the album
>>> album_manager.unshare(id_album) {}
-
show_only_created
(val: bool)¶ Sets the list method to show only albums created by the API or not
Parameters: val (bool) – value to be set (default is False) Examples
>>> album_manager.show_only_created(False)
Unshares the album with the given id
Parameters: id (str) – Id of the shared album to be unshared Returns: Empty if all went well Return type: json object Notes
This action is allowed only on albums which were created via the API.
Examples
Create new album and get its id:
>>> new_album = album_manager.create('test album') >>> id_album = new_album.get("id")
Share the newly created album
>>> album_manager.share(id_album) {'sharedAlbumOptions': {'isCommentable': True}, 'shareableUrl': 'https://photos.app.goo.gl/...', 'shareToken': '...', 'isJoined': True, 'isOwned': True}
Unshare the album
>>> album_manager.unshare(id_album) {}
-
-
class
gphotospy.album.
POSITION
¶ Bases:
object
Defines positions for enrichments inside an album.
Used in the function set_position()
-
UNSPECIFIED
¶ Position is unspecified. Default in API if not specified.
-
FIRST
¶ First position in the album
-
LAST
¶ Last position in the album
-
AFTER_MEDIA
¶ After the specified media (specify media id)
-
AFTER_ENRICHMENT
¶ After the specified enrichment (specify enrichment id)
-
AFTER_ENRICHMENT
= 'AFTER_ENRICHMENT_ITEM'
-
AFTER_MEDIA
= 'AFTER_MEDIA_ITEM'
-
FIRST
= 'FIRST_IN_ALBUM'
-
LAST
= 'LAST_IN_ALBUM'
-
UNSPECIFIED
= 'POSITION_TYPE_UNSPECIFIED'
-
-
gphotospy.album.
geolocate
(name: str, lat: float, lon: float)¶ Returns a quasi-codified geopositioned element.
Latitude and Longitude have to follow the WGS84 standard. The name of the position is not codified, so it is allowed to nikckname positions, such as “uncle Tobi’s house”, while keeping the geographic cordinates standard
Parameters: - name (str) – Any meaningful name to give to the position
- lat (float) – Latitude as following the WGS84 standard [range: -90.0, +90.0]
- lon (float) – Longitude as following the WGS84 standard [range: -90.0, +90.0]
Returns: Return type: A geographic point to use in Location or Map enrichments
Examples
>>> rome = geolocate("Rome", 41.9028, 12.4964)
-
gphotospy.album.
set_position
(position='FIRST_IN_ALBUM', id_item=None)¶ Contructs the position of Enrichment item inside the album
Parameters: position (POSITION) – - position in the album. Possible values are:
- POSITION.UNSPECIFIED Left unspecified
- POSITION.FIRST First inside the album
- POSITION.LAST Last inside the album
- POSITION.AFTER_MEDIA After the media
- specified by id_item
- POSITION.AFTER_ENRICHMENT After another enrichment,
- specified by id_item
Returns: Return type: Item position Examples
Set absolute position:
>>> pos1 = set_position(POSITION.LAST)
Set relative position; enrichment_id contains the id of the enrichment after which to position the element:
>>> pos2 = set_position(POSITION.AFTER_ENRICHMENT, enrichment_id)
gphotospy.authorize module¶
Initializes the service, requesting the authorization from the browser.
Parameters: secrets (str) – JSON file containing the secrets for OAuth, as created in the Google Cloud Console Returns: Return type: A service object to pass to the Media, Album, or SharedAlbum contructors
gphotospy.media module¶
-
class
gphotospy.media.
CONTENTFILTER
¶ Bases:
object
Filters to search media by categories
-
NONE
¶ Default content category.
-
LANDSCAPES
¶ Media contains landscape
-
RECEIPTS
¶ Media contains receipts
-
CITYSCAPES
¶ Media contains cityscapes
-
LANDMARKS
¶ Media contains landmarks
-
SELFIES
¶ Media contains selfies
-
PEOPLE
¶ Media contains people
-
PETS
¶ Media contains pets
-
WEDDINGS
¶ Media contains wedding scenes
-
BIRTHDAYS
¶ Media contains birthday scenes
-
DOCUMENTS
¶ Media contains documents
-
TRAVEL
¶ Media contains media taken during
-
ANIMALS
¶ Media contains animals
-
FOOD
¶ Media contains food
-
SPORT
¶ Media contains sporting events
-
NIGHT
¶ Media taken at night
-
PERFORMANCES
¶ Media from performances
-
WHITEBOARDS
¶ Media contains whiteboards
-
SCREENSHOTS
¶ Media item is a screenshot
-
UTILITY
¶ Media that are considered utilities, such as documents, whiteboards, receipts, …
-
ARTS
¶ Media contains art
-
CRAFTS
¶ Media contains crafts
-
FASHION
¶ Media is fashion related
-
HOUSES
¶ Media contains houses
-
GARDENS
¶ Media contains gardens
-
FLOWERS
¶ Media contains flowers
-
HOLIDAYS
¶ Media taken on holidays
Examples
Import
>>> from gphotospy.media import CONTENTFILTER
Search media by setting content
>>> search_iterator = media_manager.search(filter=[CONTENTFILTER.TRAVEL]) >>> next(search_iterator) {'id': '...', 'productUrl': 'https://photos.google.com/lr/photo/...', 'baseUrl': 'https://lh3.googleusercontent.com/lr/...', 'mimeType': 'image/jpeg', 'mediaMetadata': {'creationTime': '...', 'width': '899', 'height': '1599', 'photo': {}}, 'filename': '...jpg'}
-
ANIMALS
= <gphotospy.media.Val object>
-
ARTS
= <gphotospy.media.Val object>
-
BIRTHDAYS
= <gphotospy.media.Val object>
-
CITYSCAPES
= <gphotospy.media.Val object>
-
CRAFTS
= <gphotospy.media.Val object>
-
DOCUMENTS
= <gphotospy.media.Val object>
-
FASHION
= <gphotospy.media.Val object>
-
FLOWERS
= <gphotospy.media.Val object>
-
FOOD
= <gphotospy.media.Val object>
-
GARDENS
= <gphotospy.media.Val object>
-
HOLIDAYS
= <gphotospy.media.Val object>
-
HOUSES
= <gphotospy.media.Val object>
-
LANDMARKS
= <gphotospy.media.Val object>
-
NIGHT
= <gphotospy.media.Val object>
-
NONE
= <gphotospy.media.Val object>
-
PEOPLE
= <gphotospy.media.Val object>
-
PERFORMANCES
= <gphotospy.media.Val object>
-
PETS
= <gphotospy.media.Val object>
-
RECEIPTS
= <gphotospy.media.Val object>
-
SCREENSHOTS
= <gphotospy.media.Val object>
-
SELFIES
= <gphotospy.media.Val object>
-
SPORT
= <gphotospy.media.Val object>
-
TRAVEL
= <gphotospy.media.Val object>
-
UTILITY
= <gphotospy.media.Val object>
-
WEDDINGS
= <gphotospy.media.Val object>
-
WHITEBOARDS
= <gphotospy.media.Val object>
-
-
class
gphotospy.media.
FEATUREFILTER
¶ Bases:
object
Filters to search media by feature
-
NONE
¶ No filter applied
-
FAVORITES
¶ Media marked as favorites
Examples
Import
>>> from gphotospy.media import FEATUREFILTER
Search media by setting content
>>> search_iterator = media_manager.search(filter=[FEATUREFILTER.FAVORITES]) >>> next(search_iterator)
-
FAVORITES
= <gphotospy.media.Val object>
-
NONE
= <gphotospy.media.Val object>
-
-
class
gphotospy.media.
MEDIAFILTER
¶ Bases:
object
Filters to search media by type
-
ALL_MEDIA
¶ All media types included
-
VIDEO
¶ Media is a video
-
PHOTO
¶ Media is a photo
Examples
Import
>>> from gphotospy.media import MEDIAFILTER
Search media by setting content
>>> search_iterator = media_manager.search(filter=[MEDIAFILTER.VIDEO]) >>> next(search_iterator) {'id': '...', 'productUrl': 'https://photos.google.com/lr/photo/...', 'baseUrl': 'https://lh3.googleusercontent.com/lr/...', 'mimeType': 'video/mp4', 'mediaMetadata': {'creationTime': '2020-05-07T15:05:13Z', 'width': '480', 'height': '848', 'video': {'fps': 30.000768068818967, 'status': 'READY'}}, 'filename': '...mp4'}
-
ALL_MEDIA
= <gphotospy.media.Val object>
-
PHOTO
= <gphotospy.media.Val object>
-
VIDEO
= <gphotospy.media.Val object>
-
-
class
gphotospy.media.
Media
(service)¶ Bases:
object
Media manager
Examples
Example init of the media manager:
Imports
>>> from gphotospy import authorize >>> from gphotospy.media import Media
Select Secrets file
>>> CLIENT_SECRET_FILE = "gphoto_oauth.json"
Get authorization and return a service object
>>> service = authorize.init(CLIENT_SECRET_FILE)
Init the media manager
>>> media_manager = Media(service)
-
batchCreate
(album_id=None, album_position=None, media_items=None)¶ Create medias in the Photos account
The media must be previously uploaded. It is recommended to stage them using the stage_media() method, and once a batch has been uploaded use this method to complete the transition.
Parameters: - media_items (list, optional) – List of upload objects, uploaded to the server. If you are using stage_media() ignore this parameter. if not staging, use upload.upload() to upload the file and get the token, and media.get_upload_object() to get the upload object, and create a list with these object to pass to this parameter.
- album_id (str) – Id of the album to attach the media to. It is optional, if not specified, it will create an album with the current date, and add all media to that album
- album_position (POSITION, optional) – Position in the album where to put the media. See the relative class in album.POSITION
Returns: - Media item result (some media creation may fail, the list has
- the results for each attempted item creation)
Examples
Stage media (raw upload)
>>> media_manager.stage_media(os.path.join(os.getcwd(), 'picture.jpg'))
Finalize all staged media
>>> res = media_manager.batchCreate()
Advanced creation without stage_media:
>>> from gphotospy.upload import upload >>> img_file = os.path.join(os.getcwd(), 'picture.jpg')
Uploading file
>>> upload_token = upload(service.get("secrets"), img_file)
Constructing the upload file list
>>> upload_items = [] >>> upload_items.append(media_manager.get_upload_object(upload_token, description="a new picture"))
Batch Create (we need an album’s id)
>>> media_manager.batchCreate(album_id, media_items=upload_items)
-
get
(id: str)¶ Returns the media info corresponding to the specified id
Parameters: id (str) – Id of the media to get Returns: Media inforamtion Return type: json object Examples
Get an iterator:
>>> media_iterator = media_manager.list()
Get next media’s id
>>> media_id = next(media_iterator).get("id")
Get media’s info based on id
>>> media_manager.get(media_id) {'id': '...', 'productUrl': 'https://photos.google.com/lr/photo/...', 'baseUrl': 'https://lh3.googleusercontent.com/lr/...', 'mimeType': 'image/jpeg', 'mediaMetadata': {'creationTime': '...', 'width': '899', 'height': '1599', 'photo': {}}, 'filename': '...jpg'}
-
get_upload_object
(upload_token, file_name='', description='')¶ Manually constructs an upload object.
It is recommended to follow the stage procedure instead of the raw uploading method.
Parameters: - upload_token (upload token) – Upload token as returned from the upload.upload() function
- file_name (str, optional) – File name to register in the server, in the form of name.extension
- description (str, optional) – Description to display in the media info panel
Returns: Return type: Upload object
-
list
()¶ Iterator over the meda present in the Google Photos account
Yields: Iterator over the list of media Notes
Google Photo API list request returns in reality an object containing a paginated list of media.
This function transforms the list in an iterator and takes care of pagination behind the scenes.
Since there is a maximum limit on API requests per day per project it does not seem well to ask for less than the maximum pagination possible.
However, if there are concerns of bandwith or speed, the pagination can be set by album.set_list_pagination(n) with 1 < n < 100, since at least 1 album must be sought and 100 is the API maximum. 25 is API default.
Examples
Get iterator
>>> media_iterator = media_manager.list()
Print first item
>>> print(next(media_iterator))
-
search
(filter, exclude=None)¶ Iterator over a filtered search of all the media present in the Google Photos account.
Parameters: - fileter (array) – filters to be included
- exclude (array) – filters to be excluded
Yields: Iterator over the list of media
Notes
There are 4 categories of filters, each with its own class. More info on the relative class. - Date Filter: - Content Filter: class CONTENTFILTER - Media Type Filter: class MEDIAFILTER - Feature Fileter: class FEATUREFILTER
Google Photo API search request returns in reality an object containing a paginated list of media.
This function transforms the list in an iterator and takes care of pagination behind the scenes.
Since there is a maximum limit on API requests per day per project it does not seem well to ask for less than the maximum pagination possible.
However, if there are concerns of bandwith or speed, the pagination can be set by album.set_search_pagination(n) with 1 < n < 100, since at least 1 album must be sought and 100 is the API maximum. 25 is API default.
-
search_album
(album_id: str)¶ Specialized search in album, no other filter can apply.
Parameters: album_id (str) – Id of the album containing the media sought Yields: Iterator over the list of media present in the album Examples
Get an album id
>>> from gphotospy.album import Album >>> album_manager = Album(service) >>> album_iterator = album_manager.list() >>> album_id = next(album_iterator).get("id")
Search in album
>>> search_iterator = media_manager.search_album(album_id) >>> next(search_iterator)
-
set_list_pagination
(n: int)¶ Undocumented: see list()
-
set_search_pagination
(n: int)¶ Undocumented: see search()
-
show_archived
(val: bool)¶ Sets the search method to show archived media or not
Parameters: val (bool) – value to be set (default is False) Examples
>>> media_manager.show_archived(False)
-
show_only_created
(val: bool)¶ Sets the search method to show only media created by the API or not
Parameters: val (bool) – value to be set (default is False) Examples
>>> media_manager.show_only_created(False)
-
stage_media
(media_file, description='')¶ Stage media to be added to the photo account, by uploading to Google server.
To complete the operation all the staged media should be uploaded through the batchCreate() method (see).
Parameters: - media_file (Path) – Path of the media file to be uploaded
- description (str, optional) – Description to display in the media info panel
Returns: Return type: New media object if successfull, None if unsuccessfull.
Examples
Stage media (raw upload)
>>> media_manager.stage_media(os.path.join(os.getcwd(), 'picture.jpg'))
Finalize all staged media
>>> media_manager.batchCreate()
-
-
exception
gphotospy.media.
MediaError
(msg='')¶ Bases:
Exception
Base class for exceptions in this module.
-
class
gphotospy.media.
MediaItem
(media_object)¶ Bases:
gphotospy.media.Val
Maps a MediaItem
-
dimensions
(max_width=0, max_height=0)¶ Gets media dimensions
Parameters: - max_width (int) – If specified sets a maximum allowed width
- max_height (int) – If specified sets a maximum allowed height
Returns: (Width, Height) tuple
Return type: (int, int)
Examples
>>> media.get_media_dimesions(media_id) (720, 200)
-
filename
()¶ Gets media filename
-
get_url
(for_download=True, max_width=0, max_height=0, crop=False)¶ Gets the media’s URL.
This method tries to recognize if the media is a video or a photo, and gets the URL accordingly.
Parameters: - for_download (bool) – Specify if the url is for download purposes. If False and the media is a video, it retrieves the thumbnail (default True)
- max_width (int) – If specified, sets the picture’s or video thumbnail’s maximum width
- max_height (int) – If specified, sets the picture’s or video thumbnail’s maximum height
- crop (bool) – If True, crops the image at the exact dimensions set by (default False)
Returns: - Url (str)
- Raise
- —–
- UnknownMediaType – If it cannot guess which type is the media
Examples
>>> media.get_url()
-
is_photo
()¶ Returns True if the media item is a photo
-
is_video
()¶ Returns True if the media item is a video
-
metadata
()¶ Gets the MediaItem’s metadata (JSON object mapped to a dict)
-
raw_download
()¶ Downloads the raw media.
This method tries to recognize if the media is a video or a photo, and downloads it accordingly.
Returns: - File object data. – Internally it applies a read() to the rullib.urlopen on the media address
- Raise
- —–
- UnknownMediaType – If it cannot guess which type is the media
Examples
>>> media_iterator = media_manager.list() >>> media = MediaItem(next(media_iterator))
Once we have the media item we can download the media as a file
>>> with open(media.filename(), 'wb') as output: >>> ... output.write(media.raw_download())
-
-
exception
gphotospy.media.
UnknownMediaType
(msg='')¶ Bases:
gphotospy.media.MediaError
Exception raised when donloading media has an unknown type
-
gphotospy.media.
date
(year=0, month=0, day=0)¶ Return a Date object.
Parameters: - year (int) – Year component of the date. Set to 0 if searching for recurrences, when day and month is fixed, such as birthdays, … Must be from 1 to 9999, or 0 if specifying a date without a year.
- month (int) – Month component of the date. Set to 0 month and day if only the year is significant. Must be from 1 to 12, or 0 if specifying a date without a month.
- day (int) – Day component of the date. Set to 0 if only month and year are to be sought, or set to 0 day and month if searching only for years. Must be from 1 to 31, and valid for the month, or 0 if specifying a date without a day.
Returns: Return type: Date object
Examples
Import
>>> from gphotospy.media import date
Set Christmas and search for Christmas media
>>> Xmas = date(0, 12, 25) >>> search_iterator = media_manager.search(filter=[Xmas]) >>> next(search_iterator) {'id': '...', 'productUrl': 'https://photos.google.com/lr/photo/...', 'baseUrl': 'https://lh3.googleusercontent.com/lr/...', 'mimeType': 'image/jpeg', 'mediaMetadata': {'creationTime': '...', 'width': '899', 'height': '1599', 'photo': {}}, 'filename': '...jpg'}
-
gphotospy.media.
date_range
(start_date, end_date)¶ Return a dateRange object.
Parameters: - start_date (Date object) – Starting date of the range. Use date() function to set it
- end_date (Date object) – Ending date of the range. Use date() function to set it
Returns: Return type: dateRange object
Examples
Import
>>> from gphotospy.media import date, date_range
Set Christmas and search for Christmas media
>>> Xmas = date(0, 12, 25) >>> new_year_eve = date(0, 12, 31) >>> my_range = date_range(Xmas, new_year_eve) >>> search_iterator = media_manager.search(filter=[my_range]) >>> next(search_iterator) {'id': '...', 'productUrl': 'https://photos.google.com/lr/photo/...', 'baseUrl': 'https://lh3.googleusercontent.com/lr/...', 'mimeType': 'image/jpeg', 'mediaMetadata': {'creationTime': '...', 'width': '899', 'height': '1599', 'photo': {}}, 'filename': '...jpg'}
gphotospy.upload module¶
-
gphotospy.upload.
upload
(secrets, media_file)¶ Uploads files of media to Google Server, to put in Photos
Parameters: - secrets (str) – JSON file containing the secrets for OAuth, as created in the Google Cloud Consolle
- media_file (Path) – Path to the file to upload
Returns: Return type: Upload Token if successfull, otherwise None