Python Tutorial: Real World Example - Using Patreon API and Pillow to Automate Image Creation
52:33

Python Tutorial: Real World Example - Using Patreon API and Pillow to Automate Image Creation

Corey Schafer 11.05.2020 43 482 просмотров 980 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Programming Tutorial, we'll be learning how to use the Patreon API and the Pillow library to automate the creation of images. I'm specifically using this to add credits to the end of my videos to thank my supporters. This video will focus on Patreon supporters specifically, but in the next video, we will see how to use the YouTube API to do the same thing with YouTube Members. Let's get started... Patreon API Documentation - https://docs.patreon.com/ Virtual Environment Tutorial - https://youtu.be/Kg1Yvry_Ydk Environment Variable Tutorial - https://youtu.be/5iWhQWVXosU List Comprehensions Tutorial - https://youtu.be/3dt4OGnU5sM Pillow Tutorial - https://youtu.be/6Qs3wObeWwc ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python

Оглавление (15 сегментов)

Introduction

hey there how's it going everybody in this video I'm going to be showing a real-world example of writing a Python script that automates some tasks so specifically I'm going to be showing how I can write a script to grab a list of my patreon supporters using the patreon API and then using the pillow library to create an image with those names so that I can add support or credits to the end of my videos now this is going to focus specifically on the patreon API but I'm also going to do this for YouTube members as well in a future video so if you're a YouTube member then don't worry I won't forget about you now this is a perk that I added for YouTube members and patreon supporters just this week and as I was writing the code to do this I thought that would make for a useful video I added a couple of other perks as well so if you're interested then be sure to check out my latest post over on the community tab on YouTube that explains what some of those are now just in case you're not entirely clear what my goal here is let me show you what the finished version of what we'll be building in this video looks like and after we look at this then I'll show you how to write this code from scratch so this is the finished version of the code that we're going to be writing in this video and you can see that I'm using the patreon API here I have an access token don't worry I'm gonna get rid of these access tokens before I publish this video and then we're just doing a bunch of different things here to go out and grab a list of patreon supporters and then I also have this image module over here and what this does is it takes those lists of patreon names and it creates an image using those names and I know that this looks like a lot but we're gonna write all of this from scratch in this video so hopefully by the end it'll all make sense but if I go ahead and run what I have now then let me show you what this is supposed to do so it's going out to the API here and getting patreon info it has to reverse a couple of pages and then once it's done it will create a credits dot PNG here so hold on this isn't done yet let me go ahead and open my Finder window here okay so that just finished up and now if I open up my Finder window here and look at the image is the image that I wanted to create so it went out to the patreon API got a list of supporters and made a credits image here that I can use in my videos now so with that said let's go ahead and see how I can write this from scratch okay so I'm just going to go ahead and close down this project that I have now and I have an empty project pulled up here with no code written yet now I know

Why use an API

that there probably aren't a lot of people watching this that will be using the patreon API for anything but I still think that this is a good video to learn some neat Python tricks and see how we can automate some of these tests to make our lives a little bit easier and I'll be covering more api's in the near future as well so this will be a good introduction into how this usually works so with that said let's go ahead and get started so first of all some of you might be wondering why I'm using an API instead of using web scraping or something like that well the reason for that is because I have two-factor authentication set up on my patreon account that texts me a login code to my phone so using web scraping would get a little complicated in that case and that goes for a lot of these services and anytime you want to create an app that grabs information from you know sites like patreon or Twitter or YouTube or something like that then it's almost always a good idea to use their API because it gives you an easier and more effective way to access their data so most of the time when you use an API you'll need to login to whatever service you are using and create a secret API key and that's what you'll use in your application so that they know who you are and can authenticate you so that's the first

Creating an API key

thing I'm going to do with this project as well so let me go over to my patreon account and create a new API key so that I can be authenticated and get the information that I'm looking for okay so we can see that I already have a one API key here but I'm just going to delete this because this is the one that I just used in that sample project so now it's asking you to put in the secret key in order to delete this here so let me delete this and now that API key will be useless so it's okay that I showed that key at the beginning of the video because it's no longer going to be able to be used okay so now I'm going to need to create a new API key so this is most likely going to be the first step anytime you're using an API like Twitter or YouTube or anything like that so to do this on patreon they just have a create client here and then we have to fill in some details and this is pretty common as well so I have to give this an app name so I'm going to just fill in YouTube credits for the app name it needs a description I'll just say Python script to fetch current patrons for the app category here I will select let's see patron recognition and now it doesn't look like any of these other ones are required except for this redirect URIs now if I was doing an oath o auth type of application then I would need to put in a URL here I still but I'm not gonna be using OAuth in this video whoops and it says that I need HTTPS here so let me add that in as well and I think that if you don't have a personal website I think patreon actually has a website that you can use here in place and also for the client API version I'm gonna select just the latest version and check version 2 there now I can create that client and now whenever I open up this new client that I just created we can see that now we have a bunch of different IDs and secret tokens here so all I'm gonna need for the app that I'm writing in this video is going to be this creators access token right here and I'll be deleting these credentials after this video so don't worry about people seeing this video and trying to access my patreon data because you know by the time I release the video I'll have created a different app with different credentials now as far as these other keys here now if I were building an OAuth application then I would need some of these others as well if you don't know what oh aw this' then don't worry about that too much like I said we won't be covering that here this is just going to be a simple script that just requires this creators access token now if you're wondering how I know that I only need the Creator access token it's because I read through their API documentation anytime you're working with an API the documentation is going to be absolutely essential I have this open here in the browser if we want to see what this looks like and trust me sometimes it's frustrating when the documentation isn't as good as you'd hoped but if you take the time to read through then usually it's a big help I really do wish that they'd add some more Python examples to this patreon API documentation because it did take me a good bit of time playing around to find out how to do exactly what I wanted to do in this video and I'll leave a link to the patreon API documentation and the description section below just in case anybody's interested ok so let me copy this creator access token here and then I can use this in my Python script so now that we have that

Installing the Patreon package

copied we can begin writing our script that will effect a from patreon and I already have a folder created on my desktop with some empty scripts and I also have a virtual environment activated as well but you don't have to use a virtual environment I just like to use a new environment for every video and if you'd like to learn more about virtual environments then I'll be sure to leave a link to my video on that topic in the description section below as well now before I start writing some code here I do want to install something now sometimes these companies will also make libraries that make it easier to work with their API and patreon has one of these so to use their library we can simply install the official patreon package using pip so I have my terminal open here with my environment activated and this is just pip install and this is patreon so I'm going to install this and what's that is installed then I will minimize this and now open up our project so like I said I have a directory on my desktop here called patreon with two files in here and right now both of these files are empty but this could be located anywhere okay so the first thing I'm going to do here is import the patreon package that we just installed so that is import patreon and now I'm gonna paste in that

Adding the Patreon access token

access token that we got from the patreon site and this is a pretty common workflow so far when working with api's so I'm just going to call this access underscore token and set that equal to that access token that we got from patreon now for the purpose of making things easy for this video I'm just going to have this access token directly in my script but when you work with api's you definitely want to keep these access tokens secret if someone gets ahold of your access code then they'll be able to access the API services on your behalf so if you ever think an API key is lost or stolen then you'll need to delete that key and create a new one now one way to keep these tokens and passwords safe is to put them in an environment variable or a configuration file that isn't committed to any repositories and I have a video on using environment variables for these kinds of secret keys as well so if you'd like to see what that looks like then I will leave a link to that video in the description section below okay so now that we have that access token there are several ways that we could talk to the API so we could make web requests using something like the web request library or the request library and those web requests would return JSON data now this wouldn't be the same as scraping a page because there wouldn't be any HTML that we need to parse api's return data and an easy to digest format which is usually JSON but the reason that we installed this patreon package is because it makes this a bit easier by giving us access to their own custom classes and methods that will make these web requests in the background for us so for example to get authenticated with the API I can simply say something like API underscore client is equal to patreon dot I and then pass in my access token so you can see that the package that we installed had this API class and we instantiate that with our access token and that'll make all the authentic and web requests for us in the background now again I'm not going to go into a lot of the details here on using the API and what's in the documentation but that documentation is what I had to read through in order to know exactly what methods to use and how to pass in this kind of information when you're working with api's the documentation will definitely be your best friend ok so now we should be authenticated through the API and before I fetch my patrons I need to grab my campaign ID which is basically just a reference to my patreon account so to do this I'm just gonna leave a comment here as well and I'll just say you know get the campaign ID and to get this I'm gonna say campaign underscore response is equal to and then I'm going to take this API client here and this is API client dot fetch underscore campaign and now in order to actually get the campaign ID I need to say campaign underscore ID is equal to and this campaign response here has a method called data and within that response I'm gonna grab the first item of that response and then grab the ID of that item now again I know that this looks a little confusing for now but this was just template code that I found in the documentation I haven't really done anything unique with this API yet that wasn't in their documentation but now that I have my campaign ID this is when I'll start customizing this code to kind of fit my own needs so to grab my patrons they have a method that grabs one page of pledges at a time so now let me go ahead and grab a page of pledges so that we can see what this looks like and then we'll see how to loop over and grab all of the results and don't worry I'm not gonna expose any information here from any of my supporters just except for their names and these supporters are actually ones who selected the option on patreon that they are okay with you know me giving them a shout-out so to get a page of pledges I can simply say pledges underscore response is equal to and now I'm gonna use this API client again and this method is called fetch underscore whoops let me spell this correctly fetch underscore page underscore of underscore pledges and now we need to pass in a couple of arguments so first it's going to need our campaign ID so that it knows you know what patreon account to get pledges for and also the number of patrons per page I'll just say 25 so to make sure that we actually got a response of 25 people we can print that response out by accessing the data method of this response so I'll just print this out and say that I want to print pledges response dot data so if I haven't made any mistakes so far in the video then this should work so let's see what we get here okay so we can see that we get a list I'm not going to count these up but I'm just going to assume that we have 25 of these patreon JSON API resource objects and these are actually the patrons even if it's not completely obvious at the moment it actually took me a bit of good bit of time figuring out how to get specific information from these objects you know like I said earlier I think that they're Python documentation could use a little bit of work because it wasn't really easy for me to figure this out but after some playing around I found out that I can get information by accessing specific attributes and relationships on this object so for example if I wanted to grab a patrons name then I could simply say let me remove this print object there I'll say for pledge in this pledge response dot data so we're looping over each of these JSON API resources here and now to print out their first name I will say pledge dot relationship and then I will pass in patron and basically this will allow me to access certain attributes of a specific patron so now to access an attribute I can say dot attribute whoops let me spell that correctly dot attribute and I'm just going to grab the first name now I'm only going to access the first name right and how because not all of these supporters selected the option that they were okay with you know getting shoutouts publicly so I'm gonna respect their privacy here and just print out first names for now and in a bit I'll show how we can narrow it down to the people who are in you know that shout out we're rewarded here so if I run this we should get some first names here okay so this looks good it looks like it is working so far so that's good but right now we're only getting 25 people since we only grabbed one page so how can we get all of the pages so that I can grab everybody well the patreon package helps us out a lot here because each page is returned gives us a reference to the next page and we can keep track of this of which page we're using or which page were on using a cursor so I'm going to write an infinite loop that keeps grabbing pages until there are no more left or until the cursor is equal to none and also create an empty list of our patrons that I'll keep appending to so that we can have all of the results from all the pages just in one list so I'll keep what we have here for now but above this code this is where I will write this infinite loop so first of all I'm going to create a list here of an empty list called all pledges and this will be what I append to with all of the responses from all of the pages and also I'm going to create a cursor and set this equal to none the cursor is what tells us or was what tells us how to get to the next page so now I'm going to create an infinite loop here and now I'm going to copy this line here and move it up into my while loop but now I'm gonna add in one more argument here so right now we are passing in the campaign ID and that we want 25 people per page but I'm also going to pass in an argument of cursor is equal to cursor now when it is none it means that we're going to start on the first page and the way that we're going to update this is every time I go through here I'm going to set this equal to the API client dot extract underscore cursor and we need to pass in this pledges response variable right here so each time through this loop this cursor will get updated and it will go to the next page and then I'll show how we break out of this loop but first I want to append the results per page to our all pledges list here so I will just use a plus equals to increment this and I will just say pledges response dot data so that will just keep appending to this all pledges list here with the data per page so now we're in an infinite loop here so now we have to have a way to break out of this loop so if this cursor is still equal to none after it tries to extract the cursor then it just means that there were no more pages so I can just say if not cursor then we can just break out of that loop and now when I actually run this code it's going to take a little bit longer since it's now fetching multiple pages so I'm actually going to add in a print statement above this loop here just so we can see that our program is actually doing something just in case it gets stuck so I'll say print and we'll just say fetching oops let me spell this correctly fetching patron info ok and now let's loop over and look at the first name of all of these responses so instead of using this pledges dot response data remember this was just a single page here now we can loop over this all pledges list here and this should be the data from all of those pages so if I save this and run it then ok it says that it is fetching patron info it might take a second ok and that finished and now we should be getting the first names of everyone from my patreon and we didn't get any errors or warnings so it looks like that is working well ok so now that I have all of my patrons now I'm going to filter down to the ones who are included in the reward tier for being in the credits at the end of videos now this is my first time putting credits in my videos so if you are a patron and think that you should be including here but you know don't see your name by the end of this video then definitely make sure that you have your rewards turned on for this reward tier you know some of my when I was doing this video I saw that some of the biggest supporters over there don't have their rewards turned on so I definitely want to show my thanks but you know I also definitely understand that some people want to remain anonymous and that's fine also but for now that we have all of

filtering patron info

these patrons now I'm going to filter out our results here for this specific reward tier and then we'll also sort the results as well so in order to filter these out and also to sort these I'm actually going to grab a couple of extra fields here from our API request so to do this I'm gonna go back up to where we were fetching our page of pledges and I'm going to go ahead and add in a couple of more fields here and these this will help me with filtering and with sorting so the fields that I want to add here I'm just gonna say fields are equal to and this is going to be a dictionary and the dictionary I'm going to say that the information I want is going to be for pledges and now I'm gonna pass in a list here and the list of additional you know parameters or fields that I want the total underscore historical amount of sense that is just the total support that someone has given me over the lifetime of their patreon support and I'll just use that for sorting sense you know I'd like to have those people up towards the top now also I'm gonna get the this field here called declined since this just means that somebody maybe tried to become a patron but their credit card declined or something like that okay so we'll see exactly why I needed those extra fields in just a second but right now let's go ahead and filter out this data so now that we have our pledges in one list now I'm going to create a new list for our filtered data so this new list I'm going to have some information here on the pledges I don't want to call that people I'll call this pledges underscore info I'll set this equal to an empty list and now I can go ahead and use our existing loop here to filter this data down so let me go ahead and get rid of this here I'm gonna use this again in a second but I'm just gonna cut it out for now okay so there are a few things that I want to check here while we're filtering this first I'm gonna create a variable called declined and check if you know they have declined payment or something like that which means that they're technically no longer a patron to do this it is under the pledge dot attribute and it is this declined a since actually just let me what I copied there earlier so I can copy this and paste this in here so this here if the pledge doesn't have anything for decline to sense then it actually means that they are fine but if it has a date there then it means that currently you know their payments are declined so now I also want to check the reward tier for each of these pledges right now I'm just going to set this equal to zero and

getting patron reward tier

the reason for that is that I want to be able to grab their reward tier but I need to set up a conditional first so this is actually one spot where I got a little bit hung up whenever I was trying to write the script myself so let me show you how I can grab the current patrons reward tier here so in order to grab their current reward tier you can access the relationship of reward and then look at the attribute for a mount underscore since and that will tell you their current reward tier on patreon now the problem that I ran into here is that it's possible for pledges to not accept rewards so if I you know if I put up a reward tier that says hey if you know support me at five dollars a month or something like that then I'll credit you at the end of the video they can you know still give five dollars a month but say you know that's okay I don't want my name in the credits just you know I want to support but I don't want the name in the credits so if they turn down the reward then this will actually throw an error here because it won't have a relationship of reward this will be a none return here and then when I try to access attribute here I get the error of you know none type has no attribute method so in order to check if that is none what we need to do is we need to check this pledge dot relation chips and then this actually returns a dictionary this relationships here I want to access the rewards key of these relationships and then I want to see if that rewards key has a data key and if it does then I want to grab this relationship reward here now I'm not actually setting this to anything right now but this rewards here equal to zero here now I'm going to set that equal to their rewards here okay so now let's go ahead and actually filter these out so now for each patron I'm gonna say if that patron is not declined and if their reward tier is greater than 500 now this is cents here so this is not $500 you don't have to give $500 to be in the credits here this is a $5 per month support oh and actually almost messed up here I actually want this to be greater than or equal to because the people who are in this reward tier it will actually equal 500 so if they are greater than or equal to that reward tier then I want to capture their information so I'm going to take this pledges info list which is currently empty and I'm going to append to this list grab some information about them here now I'm also going to make this pledges info I'm gonna make this a list of dictionaries so let me clean this up a bit so this will be a list of dictionaries here and those dictionaries will just contain two bits of information first I want to grab their full name for the credits so that full name key will be equal to the value of let me go up here and grab one of these actually let me grab this real quick and paste it in here so this will be equal to pledge diet relationship dot patron and now we can access the attributes of this patron and I want to grab their full underscore name and now the second bit of information that I'm going to use in order to sort these pledges is going to be their total historical amount of sense so I'll paste that in as the key and now and in order to grab that information here I don't actually have to use this relationship I can just say pledge dot attribute like I did up here so I'll say pledge dot attribute total historical amount of since okay so now that we are looping through all the pledges here and then running this filter here now we should have a our list of patrons who are specifically in this rewards here for being featured in the credits so let me print out these names and make sure that we're getting some results and that I didn't make any mistakes while typing this out here so let me just print out actually I'll just go ahead and loop over this pledge info here so I'll say for pledge in this pledge info list and I will print out their full name now remember this is a list of dictionaries so each of these pledges here is going to be a dictionary and I can just access that full name key so if I run this then it's going to go out and fetch that patron information and then filter those out and then print them down here okay so it looks like I'm getting an error here let me check so this is a key error of rewards let me look at my notes here oh okay this is actually this key here is not rewards it is reward for this key and like I said you just have to read through the documentation to know I know that this doesn't make any sense by not looking at the documentation but I just wanted to show you my process here of writing this script so now if I did everything correctly now this should

sorting pledges

work okay so we got some names printed out here so this looks good it does look like a shorter list of names here so we can see that we're getting some filtered results so right now these results are just in the same order as I fetch them from patreon but I'd like to sort these and order of the biggest supporters first so to do this I'm just going to create a new sorted list so right here let's see I will remove this list where I'm putting out these full names and now let's create a new list of sorted pledges and I will set this equal to now if you've never sorted a list before you can use this sorted function here and within this function we want to pass in the list that we want to sort so that is this pledges info list now right now this is a list of dictionaries so it's not going to sort it the way that we want to sort it by this total historical amount of since here so we're gonna have to pass in our own custom key and we'll say that the key is equal to and I'm just going to use a lambda function here I could come up here and write my own function but at lambda is basically just an anonymous inline function so I will say that for every pledge that we see we want to sort on the pledges total historical amount of cents key okay and now that's going to sort by default from smallest to largest but I want from largest to smallest so I'm also going to pass in reverse is equal to true so if I save this then I should have a list here of sorted pledges and now I'm just going to write a quick list comprehension just to grab the full names from that sorted list you can use a regular for loop here if you're not familiar with list comprehensions but to do this with a comprehension it's as easy as just saying Pledge names is equal to and a list comprehension just looks like this we can say that I want a to grab the Pledge full name key for all of the pledges in this sorted pledges list okay so now let me print this list just to make sure I don't have any errors so I will print out the list of these pledge names here okay and here we have our list of names so this seems to be working well so now I have a list of names of the supporters that I'll be adding to the credits of videos but I also want to automate the creation of the image that I'll be using for these credits so the editor that the video editor that I use allows me to animate and scroll through an image so all I need is a static PNG image of all these names so to create this image I'm going to use the pillow library in Python which is a library that allows us to work with images and I actually have a video on pillow as well but I didn't cover how to write text to an image so this will be a bit different than what I did in that video but I'll still leave a link to that video in the description section below just in case anyone wants to see some other cool things that we can do with images and I'll actually

installing Pillow

write the code that creates this image in a separate file and once we're finished we'll import that it within this module here to create the image but first before we do that we need to install the pillow library with pip so let me open my terminal back up here and clear the screen and now I'm going to install pillow by saying pip install pillow and I look and that worked okay so now I can minimize this actually that was pretty quick let me make sure that actually worked okay it says already satisfied that's good okay so now let me open up a new Python script here and write a function to write these names to an image now I already have a file here called image dot pi and this is completely blank at the moment now I would like to point out that this file image dot pi is in the same directory as the script that we just got done writing and that will just make importing this function that I write easier okay so how can we write this text to an image so first of all I'm going to need to import

creating the image

a couple of things from pillow in order to create this image so I'm going to say from PIL I want to import this image class also this image draw class and image font class and now I'm going to create a new function that will create our image and it will take in a list of names as an argument so I'll call this function create underscore credits and this will take in a list of patron names okay and now the first thing that I'm going to add here are going to be some image properties you know such as the image width and height along with our starting Y position for the text and the padding between the lines now I had to play around with these numbers to figure out exactly what I wanted and you're seeing the final product here but I definitely you know just had to guess these numbers to start off with and then I you know it just took some trial and error and playing around with it before I got the image to look right but let me go ahead and type these in and I'll try to explain as I go so first I'm gonna have the text Y position here and I'm gonna set this equal to 800 so this is a starting position of 800 units I'm not sure actually what pillo uses I'm not sure if this is pixels or something else but this is going to start 800 units whatever units those are down on the image the reason it's so far down is because since I want this to be credits a lot of blank space at the top before the first name and now I'm going to also use some text padding here and this will be the padding between each line of text and again this is going to be 120 maybe pixels so 120 units of whatever those are and now I want an image width and this is pixels I know this because I want 1920 since that is the resolution that I upload videos to and now I want the image height now the image height is actually going to be variable because if you think about it you know one day I might have 15 patrons and then the next day I might have 20 so I can't just have a standard height it needs to actually grow with the number of patrons so what I'm gonna do here is I'm gonna say that I want the height to be the length of this patrons names list and then I'm going to multiply that by the text padding between each of these line numbers and now I also want to leave room for the top and the bottom because if I just did it this way then it would just barely fit in those names but I also want to have padding for the top and bottom so I want to also add the pixels that will be the text Y position times 2 because I want a text Y position padding at the top and at the bottom and if that doesn't entirely make sense don't worry too much about it right now I'll kind of show you what this did once we actually see the final result and also this is just such a you know unique situation for me so I doubt that you'll be doing you know anything exactly like this but I guess it is good to know you know kind of a little bit about the math behind this just in case you are doing something similar ok and now that we

drawing the image

have those image properties now I'm going to create a new blank image so to do this I'm just gonna say image is equal to image dot new and remember this image here is this pillo image class that we imported so I'm going to say image new and we want this to be an RGB image and then I'm going to pass in a tuple of the image width and the image height we already have the image width up here which is static and then the image height we have that calculated here as well and now I need to pass in a background color for this image so I just did some playing around and I found a color that I liked this is just an RGB value it's 58 6368 and you can play around with that that's just kind of like a dark blue background and now I'm going to draw this image so I'll say draw is equal to image draw which is this class here that we imported image draw dot draw image okay and lastly I want this to look nice so I'm going to use a custom font now I know exactly where this font is located on my machine so I'm going to put the exact path to this font but the location for fonts is going to be different on your machine so if you're on Windows or Linux then you'll need to look up where her fonts are located if you're doing something like this and if you're on a Mac then your fonts are likely going to be in a similar location as mine but probably in your user folder instead of mine obviously but to specify a font I can simply say FN T is equal to image font dot true type and that is all lowercase and now let me see the location on my machine let me go back to my terminal here I think this is in sa users my user name library fonts and then this is I'm gonna use this railway regular font yes so this is the location here so I'm just gonna copy that full path and paste this in as the font that I want to use and now I'm also going to pass in a font size now I want this text to be very large so I'm just going to use 100 font size here and now that we

writing patrons names

have all this set up now I can loop over the names that will be passed into this function and write those names to our image so to do this let's see what do we call this patrons names so I can say for name in patrons names and now within this loop I want this text to be centered on my image so I'm going to need to know the width of this text in order to Center this to the image so to grab the text width I can use this draw dot text size method here and now I want the text size of the font with that name passed in because you know all of these names are going to be different widths and then I also have to tell it to use the font that we specified so I can get the exact width now this here returns a tuple of the text width and the text height we're only going to be using the text width but we're you're also need to have a placeholder here an underscore is just a throwaway placeholder for a variable that you're not using so I could put text height here as well to capture that but I'm not going to be using it so I'm just using an underscore

drawing text

okay and now all we have to do is draw on our text to this image so I'm going to say draw dot text and now I'm going to pass in a few different parameters here okay so the first parameter is actually going to be the x value of the text now the x value remember we want this to be centered and we know the text width image width so all I have to do to Center this is I can just say image width minus the text width and then I want to divide that by two okay and that will Center that text on our image now for the Y position of the text we want to use this text Y position here and we're starting at 800 so I will pass that in as well whoops and it looks like I accidentally left out some parentheses here so for

drawing text code

this draw dot text our first value is going to be a tuple of the X& Y positions so within this text method here this is our first value to this text method an X& Y tuple this is our X this is our Y and now we also want to add in the actual text that we want to write which is going to be this name from the names list and then the font that we want to use is going to be equal to F and T is what we set up for font and also a fill color for this text so white is 255 255 I just want this to be a little off-white so I'll say 250 250 okay and finally within this loop we also need to increment the Y position of our text by the amount of our padding so that we're not just writing text over itself every time through the loop so what did I call this here text Y position so we need to say text Y position plus equals the text padding and yes I called that text underscore padding so now when we're looping through this every time it's going to you know calculate the text size for that name and then draw that name onto our image at this Y position and then it's going to increment that Y position for the next name so it should just keep going down the image filling in these names so now that should loop over all of our names and write them to an image all we need to do now is save that image to our machine and I'm just going to save this image to the current directory and I'll call this you know credits dot PNG or something like that now be sure that you're outside of your for loop here because you don't want to save the image every time through the loop you only want to save this image once that loop is complete and all these names have been written to our image so now I can just say IMG I believe is what we called our image up here yep IMG dot save and then the name of the image so I'll just call this credits dot PNG okay and now we could be done with this function I'm actually going to return this image as well I don't think I'm gonna actually use this return value but if we don't capture it then that's fine okay so finally we should just about be

import function

done with all of our coding the only thing left to do now is to import this function that we just created into our other script and pass in our list of names to this function and at that point it should create this image so let me switch back to my other script here and first I need to import that function that we just created now again this image dot PI module that we just wrote that is in the same directory as this script here so I can just import this directly so I can say from image import and let me make sure I got the name of this function crack so it's create credits so we'll import that create credits function and now let's call this function at the bottom of our script so I'll just go ahead and keep that print statement there it's not gonna hurt anything so I'll say create credits and pass in our pledge names to that function okay so now if everything went according to plan and I didn't make any mistakes I should be able to run this and get the image after that's run so let me try this out so it's going out and fetching the patron info and then once it gets that it should create an image with those names okay so that script completed and we can see that we have a credit stop P& G here let me open this here in finder and open up this image so if I open this we can see that we successfully created that image it has that nicer font and everything I think the colors look good and you can see that we have a lot of padding here at the top and bottom that's just so I can scroll the credits and it looks a little more natural whenever it's actually in a video so that looks good let's go ahead and close this down okay so it looks like this script is working nicely and is doing what I was hoping it would do now I know that this project is very specific to my own needs here but I wanted to show you all this quick little project just to show you how you can use Python to automate just about anything and without writing a script for this you know this is probably something I wouldn't be able to do you know it would be a lot of work manually creating the script or creating these images for each video especially when there are people coming and going from patreon all the time so this script is going to make it a lot easier for me to you know just automate that process of going out and getting those names you know so I can thank some people at the end of my videos so like I said this is a new perk that I added for my patreon and YouTube members I really appreciate all of you guys who support financially because that's really what allows me to keep these videos free for everybody so I wanted some new ways to show my appreciation now I know that this isn't much but I hope it's something at least now I also added a perk for getting early access to videos I usually upload videos a few days early anyways before I release them publicly just to let them you know process correctly and give YouTube a chance to tell me if there were any upload problems or anything like that so I just decided I'll go ahead and give supporters access to those videos as soon as I upload them and then a few days later they'll be available to everyone for free just like they've always been so you know don't worry if you can't support financially then that is completely understandable and nothing will change for everyone else all the videos will still be released for free here on YouTube these were just a couple of ways I thought I could give something back to the people who do support through patreon and YouTube now like I said in this video I only touched on my patreon supporters but in my next video I'll show how we can connect to the YouTube API and go through this same process and then I'll combine these scripts together so that I'm listing both patreon and YouTube members in the credits so with that said you'll likely start seeing credits roll as I finish up videos from now on I'll likely throw those credits up on screen right now just so you can take a look at the final product of what it is I was building here in this video so I hope you feel like you got something useful out of this video this will you know likely be a similar process when working with other api's I do plan on covering more api's in the future so that we can do some more cool projects like this but with that said if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that these is ways to simply LIKE the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon or YouTube and there are links to those pages in the description section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник