Deploying AI Models with Hugging Face – Hands-On Course

💬 Chat with this Video
Ask anything about this video…
This tutorial is a comprehensive end to-end guide to the hugging face ecosystem showing how modern AI moves from research ideas to real deployed systems. Hugging face is a leading open-source AI platform and community. It connects models, data sets, libraries, demos, and deployment into one coherent practical workflow. >> In the past few years, artificial intelligence has moved incredibly fast. We now have models that can write, translate, see, hear, and even reason across multiple modalities. But one question remains for most developers and learners. Where do all these models live? And how do we actually use them? That's where hugging face comes in. Hugging face is more than a library. It's the open platform that connects AI research, real models, data sets, and applications into one ecosystem. In this course, we'll take a practical end-to-end journey through the hugging base ecosystem. We'll start with a transformance library where you will learn how to use state-of-the-art language vision and multimodal models and how to use them for tasks like text generation, classification, translation, and question answering. Then we'll move into diffuses library. The library behind modern image video and generative AI systems like Sable Diffusion where you will learn how these diffusion models actually work and how to use them to generate and control high quality outputs. Then we'll dive into Gradial the tool that lets you convert or turn any machine learning model into an interactive web application in minutes without any front-end experience. We'll also deal with video and audio models for tasks like speech recognition, audio generation, and many more. By the end of the tutorial, you won't just understand hugging phrase, but you will know how to navigate it, build it, use it, and how to deploy real AI applications into hugging phrase ecosystem. Whether you are a beginner, developer, or researcher, this course will provide you a solid and future proof foundation into opensource AI. Let's get started together and let's dive into one of the most brilliant tasks in the world of natural language processing which is text generation. We will download and load the model GBT2 from the hugging face platform and use it to do this task particularly text trans text generation. So the first thing let's put a title here a nice title as text generation using GBT2 model from hugging base library and let's put here the icon hugging as you can see. Then let's dive into the first thing which is importing the libraries. How to grab or fetch a model from inside the hugging face platform. So first here we have the main page or the homepage of hugging face. You can see here we have models, data sets, spaces. These are the three main components inside hugging face. Models which are machine learning deep learning models. Dead sets which are the data sets the data that you want to use to train a model and to test the model. spaces which are a visual visual gradial interface that visualizes the model and how it works how it operates. So let's go to models. Here you can see we have the uh models number. We have 2,285,99 models, a large number. Let's search into here GBT2. You can see we have OpenAI- community/GBT2. Let's go and click on it. Here we are directed to the main page, the main model card. They call it model card. As you can see, model card. This is the model card of GPT2. And you can see here how many likes did they get? They have 3,000 likes. Follow. You can follow that if you like. I can give this a like. You can see now I liked it. Here you can see we can copy the name of the model. OpenI-/GBT2. And if you go down, how many downloads did they have? Downloads last month 8,868469. Okay. And then you can go here, you can see the number of parameters, the model size. Uh and here feel free to read about this. This is the the explanation and the description some meta information about this model. So you can see here how to use it. Actually there's there there is some sales that explain how to use this model. You can see generator equals pipeline pass text- generation. This is the name of the task. The task want to conduct is text generation model equals dity tool. Then you can see they have they have passed some info here some prompt. Hello I am a language model. And then and this is the answer of the language model. Okay, let's go ahead and use this model by going here and then click on transformers. Here we have a model that shows two uh blocks or two sections. The first section uses a highle helper which is a great option and the second option is load model directory. This way the way that we that we will use in in this lesson and uh that we used we we saw that from transformers import auto tokenizer comma auto model for com and this way uses a highlevel wrapper or helper called pipeline let's use the both options let's copy this go ahead and paste it over here from transformers library import pipeline this is a highle helper then we use that function and pass here two arguments just two parameters is the task you want to do text dash generation and the model that you want to leverage openai-d2 let's run that you can see now it is trying to download this model the uh from the using the pipeline function now it's connecting Okay. Here you can see it's now loading the model. Uh the task as we said text generation. So this model tries to generate some text. The model that we that we need to leverage or use is GBT2. Now it takes some time to to download and load the model into the environment collab. And you can see here now it's executing. It's taking 27 seconds so far. By the way, you can go to hugging face and then models and then go to tasks. Then choose the task text generation from here. NLB natural language processing. go to text generation here. We have plenty and a plethora of models of text generation models that you that you can use. Okay. So, so for example, we have this model from OpenAI. It's called circuit sparity. Nvidia also has a model called Neometron orchestrator orchestrator none none biggy. You can see llama also you can use llama model. So these are all the text generation models. You can see here we have text generation. How many models do we have? Well, we have here 303,000 models all dedicated to the task of text generation. Here we can see that the model is loading currently. You can see it's trying to load some libraries some for example models tenses. This is a sub library generation config.json and we have obvious then device set to use CPU. So this is the process to load a model using the haba using the pipeline. Now as you can see the model now is successfully loaded. Let's use that model by going to here and calling pipe. You can see pipe and then pass into here some text. Consider this as a prompt. So you can define a a variable called prompt equals prompt equals what is machine learning. Then pass this prompt directly to the pipe. That easy. It's easy as that. So you can see now the model is trying to pass this prompt to the pipe. You can see here the benefit of using the pipeline here is that you don't need to tokenize the sentence. So you don't need to pass the sentence as we did to pass it to the tokenizer. Then you get token ids. Then you pass to the GBT model. No. Here you can see we have a list. Inside this list we have a dictionary. Then we have the key called generated text. Now to fetch that key specifically, we can go ahead and store this inside a variable called output like that. Okay. Then we can step through that output, step into it and fetch the value of the text. Okay. So we can go output and then add index zero to get the the dictionary. Then we can go the key called generated underscore text. So wait until this finishes loading. So you pass the sentence to the pipe. Then we store that that value inside the variable. Then we can use that that variable freely. Now you can see run that. Nice. Now we have this text. What is machine learning? It's not very hard to understand. This is the answer of GBT. You can see this is my prompt. Okay. Then this is the answer. It's not very hard to understand. It's one of the reasons that why we've been be able to develop the neuronet for some time and blah blah blah. Now, if you want a nicer and neater format of this, we can pass this to the print function. Okay? So, pass this because why? Here you can see we have back slashn and it's it's it's not interpreted well. So, yeah, here we have back slashn. So print function will interpret that into an actual line into a new line print. You can see we have a a nicer output as if you ask GBT in its interface and it's it answers like that. What is machine learning? It's not very hard to understand. It's one of them of the reasons why we've been able to develop the neuron for some time and you can feel free to read that. So give whatever prompt you would like and the Jeep will answer GP2. The second approach is that we can go ahead go up use this model. You can see the library here is transformers. Then we have another option here which is this from transformers import auto tokenizer, automodel for com. Let's go ahead and use that approach. Run run run run it again. You can see uh this approach is uh is a lot faster. Now we have a model this model. Okay, we can go ahead and this is the archae of the model GP2. But keep in mind you have to tokenize your text before passing to this model as we saw before. So that that's it that is for text generation. You can go ahead as as we said models and then choose the tasks from here choose the task as text generation. Now let's move on to another task in transformers library. Now as an alternative way rather than copying those codes from hugging face platform we can write them straight away in here. In this section we will use GBT2 model from hugging face platform. So the first thing the very first thing we need to do is to import the transformers library. So let's go from transformers import auto tokenizer. So this is auto tokenizer class from transformers library. Then we will call the method from pre-trained and then pass in GBT2. So as you can see now it is trying to import the class autoto tokenizer from the library transformers. Then the next step is to instantiate a new object called tokenizer equals auto auto tokenizer and then dot from pre-trained pass into here GBT2. So as you can see and then run that. So now we are uh fetching the the model GP2 using the method from pre-trained that is coming from the class auto tokenizer. As you can see here this class this is a generic class tokenizer class as you can see that will be instantiated. Then we call the method from pre-trained and then use one of the language models that is provided in hugging face for example in this example or in this case we use GBT2. Then we have a tokenizer ready. So let's try this tokenizer by going sentence or sentence equals unsure. Okay. Then we need to pass this sentence to the tokenizer object by going input ids equals tokenizer and then pass into here the sentence. Then I want you to notice here if you pass this sentence as you can see tense then we didn't specify the parameter return tenses as pt it will return list. So let's take a look at this input underscore ids we pass the sentence into here as you can see now we have uh this is a dictionary then the input ids are in the form of list. So if we go ahead and access this key input ids then we will get here a list. If you want to retain these ids inside of a tensor inside pytorch tensor let's specify return tensors equals pytorch pt. So pt is short for pytorch and then let's run that again. And as you can see successfully now we have pytorch tensa. Now let's take a look at unsure word. Why unshaw word is splitted into two numbers or into two ids? Well, because unshaw is a word that is divided using the sub level tokenization level. So we have un as a separate token which is this ID 13,271. Then we have sure uh we have shore a separate word a separate token as the ID 495. Okay. So some words you have to keep in mind that some words will be splitted will be segmented into more than one segment. So not necessarily one word is one token. Maybe one word generates more than one token gen more than a single token. Okay. So as you can see we have no ideas how to get back to the word unsure. Well to get back to the unsure word we have to use the method decode by going tokenizer. Decode as you can see. Then we pass into here the input underscore ids. Then let's access at index zero. It token it decodes that into the word unsure. So we got back into the word unsure as you can see by passing the ids to the method decode. Okay. Then it gets back to the unsure word as you can see. The next step is let's try another word. Let's try for example the word unbelievable by going for example sentence equals unbelievable like that. Then we pass this sentence to the tokenizer by going input ids equals tokenizer and then pass into here the sentence sentence then we specify the parameter return tensors equals pt for returning the tenses in the form of pytorch tensor. So please so here we are saying hey please so canera return the ids stored into a pytorch tensor then dot input ids so we get right up the pytorch tensor then we have the input underscore ids as you can see we have these ids so here so as you can see here we have the word unbelievable and it is divided into three tokens let's figure out what are the actual parts what are these actual parts by doing a for loop. So for token id for every single token id in these ids in input ids as you can see add index zero to get this segment here this list the inner list then we go ahead and print tokenizer dot decode and then pass into here the token underscore id. So if now if you run this 3 2 1 we have the actual segments the actual parts that these ids correspond to. So 403 correspond to un then we have 667 correspond to corresponds to bill. Then we have eable. So as you can see unbelievable. Then let's figure out another word. Let's take another example. For example the the the word homoscadasticity by going word. for example equals homo skod skadicity skasticity like this. Then let's pass it to the tokenizer by going tokenizer dot decode and then pass word. Then we let's set the parameter return underscore return tenses equals pt short for pytorch.input input underscore ids and let's let's store this value into a variable called for example my ids then let's print that my ids as you can see here we have input ids let's run that so now this tokenizer will work on the word homoscadacity and tokenize it segment it and return the ids let's see what this error is so ids can't extract string to vic So yeah I think here we have to return tenses pt we pass yeah we need to specify the function as tokenizer. Okay so now we have these ids as you can see. So I used decode and in fact I have to pass the word straight away to the tokenizer. So as you can see here we have these ids 26452 418 771 and to the rest. So the word homoscadaci is being divided up into one, two, three, four, five into five different tokens into five different words. So I want you to imagine or have an idea that a single word doesn't necessarily represent one single token. It could be splitted up splitted up into several tokens. It could generates multiple tokens and generates multiple uh multiple segments. Okay. So let's take also another example like for example let's decode it. So tokenizer do decode and let's get back to the real world homoscadacasti. So now I have ids. How do I know what these ids correspond to? What is the word behind these ids? By passing my ids to the function decode. And we have to specify here at index zero or for example dot squeeze dot squeeze. Okay. Then we can pass it here. We have here homos dacasti. So if you use here add index zero, it will also work in a nice way. And if you specify here dot squeeze, so you squeeze it, you get rid of this outer list brackets, then it also works. Homoscadacity. Okay. And feel free to use this tokenizer. So this tokenizer is based on what? Based on GPT2. If you call this tokenizer on its own to get some information about it, you can see that hm name or path is GBT2. So this tokenizer is based on the tokenizer that open AAI used for GBT2 model. The vocabulary size here so the number of vocabulary words is 50,257 tokens. So keep in mind these are not words, these are tokens. So maybe there are words that was splitted into multiple tokens. So these are the tokens 50,257. We have model max length. So the model maximum length is 1,024. This is in terms of GBT2. But here you can take a look at uh several information about this tokenizer. So this tokenizer now is using the GBT2 model tokenizer. Feel free to change it to any word. Now let's try a a long word. For example, uh the word numino ultramoscopic silicico volcano coniosis. If you go to Google and write in here numo numino u ultramicroscopic silico volcan volcano conosis there. So this is the longest word in the English language. Let's copy it and go word variable equals this word and then let's tokenize it. I wonder how many tokens this word results into. Let's figure that out together by passing this word to the tokenizer. So, let's go. My ids equals tokenizer dot tokenizer. Then pass into the word. Pass here the word this variable. Pass it to the tokenizer. Then let's specify here return tenses. Should I return tenses? Yeah. And in the form of PyTorch dot input ids. Then print out my ids. Show me your ids. Wow. You can see here we have multiple ids. So one, two. Oh, let's get the length. We have the length method. We have uh at index zero, we have 15 different tokens. So this word, this long word, this is the longest word in English. Actually, it results into 15 different segments, 15 different tokens. Okay? And if you want if you want to if you want to see them they are as this my ids then these are my ids 79 256 68 261. So these are ids. So the first thing we have tokenization. Tokenization is the process of tokenizing or segmenting or breaking up the sentences the words into tokens. Then we map these tokens into ids. Then after that we pass these ids to an embedding layer. The embedding layer maps these ids into vector embedding representations. Then we have vector representation objects. We can uh preserve the positional encoding. Then pass these embeddings to the transformer encoder. Then we have a GBT model. Okay? Or or to a decoder then we have a GBT model. So the first thing we tokenize the text into tokens into segments. We map these tokens into ids. We convert these ids into vectors. Then we preserve the position coding. Then we pass it to an encoder or decoder depending on the architecture you are using or leveraging. So now uh that's enough for the uh tokenization process. We saw multiple words also. We can do a for loop on this by going for token ID. So for every single ID in my ids dots squeeze. Okay, let's go ahead and print tokenizer dot decode tokenizer dot decode. So decode it and then pass here token id. Uh these are the segments you can see numo uh p is a p is a separate token h n is a separate token on numino ultra microscopic silicico volcano chinosis. So GBT model sees the the this word this long word sees it as these are as these segments. Okay. So it processes the word numo ultramicoscopic silicico volcanois as these segments. You as human you see it like that uh in in in a string fashion numo ultra microscopic silicico volcanois. But for the GBTs they see it as these segments separately. Now let's move on to the word for example anti-isestablishment turnism by going sentence equals and then let's search on Google anti- disestablishment terism. Let's copy this word. This is I think the second longest word in English language. Let's paste into here then pass it to the tokenizer. Let's see. Let's discover how many tokens that will be resulted when we pass this word pass it to the tokenizer object. So by going my ids or for example let's name it uh token ids. Let's verify the name of the variables. Then pass here tokenizer. Pass here the sentence. Then comma return tenses equals pt dot input ids by going dotinput the attribute input ids. Then let's print this this variable token ids and see how many ids that are being generated. Well, as you can see, we have these ids. And if you get the length length and then pass token ids at index zero, we have five different tokens. So, 1 2 3 4 5. So, this word is being splitted up into five different tokens. Also, this uh there is a last word called flexo fluxification. So, let's go word equals search here. Flock uh flocks hillification which is also considered uh one of the most longest words in English and then pass this to the tokenizer by going my ids equals tokenizer tokenizer dot and then pass word return tenses specify it as pt for pytorch token.input input underscore ids then let's spread out my ids and these are my ids as you can see and how many ids we have let's go my ids add index zero dot or pass here the length to get the length I have nine different tokens nine different segments that this word is being spitted into as you can see these are the ids and we can loop through it as you as we saw before for each token id in my ids at index zero. Then go ahead and print print print the tokenizer decode and then pass into here my token id. So we have f l is a single token o so flocken si helibilification as you can see which is a word that indicates nothing. Then let's move on to a another another section which is how to generate. Now we we saw how to tokenize the words. We saw the ids. Now what if I wanted to generate to use GP2 and actually generate using GP2. Well, we have to we have to import another class. So let's go from transformers import automod for causal lm. So we have a class we have a nice class called autom model for causal language model. So this is a real causal language model. Let's import it. Then let's instantiate a new object. Let's call it GBT2 equals. So my nice GPT2 model equals automodel for causal lm. I like that class name. Then let's pass into here GPT2. Run that. As you can see uh we have to call the method from pre-trained. So we have to go from underscore pre-trained and then pass into here GBT2. So do not forget you have to call the method from pre-trained always when you use a class from hugging face. Now as you can see we have a warning. Uh don't worry about this warning. It just warns you that detected not written. No worries. As you can see now we have successfully downloaded the model GPT2. Okay, let's go ahead and see the archetype. So what is the architecture looks like of GT2? If we type here the name just the name GT2 and run that you can see we have the real architecture here. So this is the architecture. First we have embedding layer then we have another embedding layer. I think this is for uh converting ids into vectors and this is for adding the positional encoding. We have drop out then we pass it to the HBT2 block and we duplicate this block 12 times. Inside this block we have layer normalization layer to normalize the inputs. We have GBT to attention. We have curve layer convey convolution. So this so this convolution is the attention. They implement the attention via a convolution layer. Okay. So feel free to explore this architecture on your own. But now let's dive in and use this architecture use this really clever architecture to generate. So the first thing we need to uh to build a sentence by going sentence sentence equals and let's use a sentence that is that has a tendency for chity to complete it. So if you say that I like machine learning then we ask jubility to complete then jity will complete on this onto this sentence. Okay then let's go ahead. So I like to machine learning too for example uh to to do something or to be able to do something. Let's let's figure out what GBT will will generate as a next token prediction. So let's go ahead and use GBT2. As you can see we have GBT2. Then pass into here this sentence. That's all we have to do is pass this sentence to the model GBT2. Then let's run that. As you can see here we have to so the size uh string has no size. Yeah we have to tokenize this string. Yeah we have forgotten a important step uh before we pass this sentence to the GBT. We have to tokenize it. So we have to get the ids as we did before. So here we have token ids equals tokenizer then pass my sentence. Then this tokenizer will work on the sentence and then return underscore tenses equals pt pytorrch and then get the input underscore ids. Then we have a token underscore ids. So these ids now has the capability to be passed to the to a gb model. So don't pass the string straight away to the GBT model. You have to tokenize it. Why we explained this tokenizer before? because we need to tokenize any string before passing this string or this prompt to the GBT model. So this is a prompt we tokenize it we process it. So this is a data processing uh processing technique. Then after we proc it we can we could then pass these to ids to a GP model by going GPT 2 and then pass token ids. Hooray. Now we have here the output of GT2. Here you can see we have logits. Let's access the logits dot logits. Now how many how many vectors do we have the same number as the word here as the W. So we have I 1 2 3 4 5. Here we have 1 2 3 4 5. So the same number of words you have here, the resultant logists will have the same length as the number of words you have. So we have five words and also we have here five corresponding vectors. Okay, I care mostly in the last vector. So let's get at index 0, minus one. So because I my my vector of interest is the last vector. So let's tap into that and get it. And now we have it. Now let's store that in inside a variable called outputs. Outputs. Okay. After that let's show it our outputs. Then let's call the function argmax. The arg max function. It will give me the the index at which the highest probability exists. Okay. So let's pass this to the tokenizer. Decode to decode it. So this is a a token ID. We pass it as we learned before. We pass it to what? To the decode function and then it decodes it. Uh B. Now I like machine learning to let's put here B able to predict the then we put this to predict the future. As you can see we have the word future. Okay. Then we have a dot. So as you so as you saw we predicted the next token using a gypy model here we have logits okay then we got the arg max so give me the position so returns this function basically returns the position at which the highest probability exists so model generates probabilities then we decode it and then we generate okay let's take another example for example the sentence Sentence I learn machine learning to enhance then let's ask GBT to to generate the following words the following tokens by passing this sentence to the tokenizer first to do data prep-processing. So we have token ids equals tokenizer my little tokenizer and then pass in here the sentence comma return says we have to specify it as pt short for pytorch input ids. Then let me scroll down here to see the output. Then let's pass these token ids to the GPT model by going outputs equals GPT2. Then pass in token ids. Then get the logits tab into the logits and index 0, minus one to get the last token to get the logit of the last token, the last word. For example, enhance. And then we have tokenizer decode. I then pass into here the outputs. But please give me or return the arc max the position at which the highest probability exists. Run that we have here to enhance our so you can see here GBT2 now is now predicting the next token as our so let's put in here our to enhance our understanding. So GP now is predicting the word understanding as the next token. understanding of so you can see of the world around let's uh inject that word to around us then we have a full stop so you can see this is the way that GBT is running the way GBT works the way GBT operates it predicts the next token So it chooses the highest probability of the token that it thinks or it believes that this word should be the next word. Okay. So this is another example. Now what are these sampling strategies? Well, we have many sampling strategies. The ways you can extract the token to be selected as the next token to be chosen as the next token. First we have a function inside torch called topk. So let's use that function by going let's first use our sentence for example sentence equals I learn machine learning to enhance the same the same sentence and then let's tokenize it using the tokenizer by going token ids equals tokenizer and then pass into here the sentence return tensors equals PT pytor dot input ids input ids then let's pass these ids to the gbt2 model by going outputs equals gbt2 pass into here the token ids so remember you have to preprocess your sentence by passing it to the tokenizer then let's get the logits at index 0 minus one and then at the last tokenizer decode and then pass Here outputs.orgmax. Here we have the outputs.orgmax. Let's write. Let's read the error. Retrained our unexpected keyword argument. Yeah, we have a typo in the return underscore tenses parameter. So we have our Now let's apply the torch.topk top k by passing the logets into the top k function. So you can see let's get here the output final underscore logets equals torchtop k and then pass into here the logets the outputs and then comma 10. So we need to choose the first top 10 lojets by passing the outputs to the torch to topk and remember we have to import the library torch by going into here import torch. Run that again and now we are able to use that function. Now let's first visualize those final logits. As you can see here we have a tensa a nice tensa with 10 logs. Okay. So we have min - 100 - 100 comma 4 and so on. What if we limit this to one? Well, we have then just one logit. Okay, so this is the way of top K. Top K is a strategy of sampling or is a sampling strategy that selects the most top K highest probabilities from the token pool and then we limit it to a specified K number. For example, seven. Then we have here seven tokens or seven logits. We just have seven logits. If we make it here for example 30 then we have 30 logits. If we limit it to three then have just three logits. Okay. As you can see this is the way of operating with topk. Now let's decode them by going for index. So for each index now let's visualize what are these tokens? What are these chosen tokens by doing a for loop. So for index in top 10 which is this final logits dot indices. So let's get the indices. Do the following. Print tokenizer. So as we saw before tokenizer dot use the function decode and then pass in the index. So all we're doing here is we are looping through the final logits dot indices. Then we are storing that index step by step into the index variable. Then pass that variable to the decode function. Run that. Nice. Now we have our the my. So these are the top most tokens that the model thinks that this is our token is the most high is the highest probability. The second highest probability is the the third highest probability is my. So to enhance this could be to enhance our or this could be to enhance the the world for example or this could be to enhance my understanding or my skills. So let's put here my then it will change as you go we have work to enhance my work or to enhance my own things to enhance my own life or to enhance my skills as as I told you to enhance skills. So I predicted that I didn't know that GBT will output the word skills to enhance my skills as you can see and in comma. So let's choose for example and my for example life. So I learn machine learning to enhance my skills and my life. So this is the way that topk sampling strategy works. It limits the outputed logits or the outputed tokens to a specified number called K. Feel free feel free to play around with the K value. It's very fun to play around with the K value. Let's change it to seven to suggest seven candidates. Then we have here seven candidates. Let me get rid of this to trigger GBT to complete the sentence. So as you can see I learn machine learning to enhance our the my human to enhance a and for example let's choose human to enhance human life for example human intelligence or human performance or human cognition or behavior learning cognitive understanding. So now we have seven candidates here. Let's make the list bigger and let's for example go go crazy 20. Now we have here 20 candidates inside the list. GBT now will choose one of these candidates. Okay. So and then if you choose for example performance then it will also suggest another 20 logest or another 20 tokens. For example let's here choose the word intelligence. Intelligence intelligence. Then we have these are the candidates and in by is and you can see based on what the previous word is or was the token see changes or the token Z had changed they are varied depend what what is the previous token was okay let's take another example now we have saw the top K the top K is a function remember inside torch library. Let's search into here torch top K. Remember always your documentation is a reference. Please feel free to read here in your own time. But but you can see here top K returns the K largest elements of a given input tensor along a given dimension. So from this definition we have a full summary of what this function does. Returns the k largest elements of the given input tensor along a given dimension. We give it the input tensor of loget. then it returns or gets back the k largest element of a given tensor at a given dimension and then what you pass here is the input tensor just you provide it with input tensor and keep in mind you have to provide the number of k the k in top k let's go ahead and see what are the remaining sampling strategies are let's take a look at what are the different sampling strategies are so we have several many method methods or methodologies to sample using different methods from the token pool. The first method is greedy decode. This function receives from me logits and then let's put a nice documentation here. It returns or return token index with maximum probability. So all it does this function it returns the token index with maximum probability. So the index or the position at which the maximum probability exists and lives. So let's return torch dot arg max and then pass into here the logets comma dimension equals minus one. So keep in mind minus one. We have to provide here -1 as the last dimension. Then let's use this nice little old function by going greedy decode and passing here my outputs. So the logits let's read the error torch has no attribute arg yeah I have a typo a small typo in the function arg max classic error arg max as you can see here we have the tensa at index 13 so now it is indicating that at index 13 the maximum probability exists the maximum probability lives so I wonder what is this token by going tokenizer.de decode. Let's decode it. Let's visualize it. It's a full stop. So now GBT is suggesting that the highest probability token should be fully stop. Okay. If we change this sentence here for example to enhance human intelligence to enhance and then run that again. These are the candidate tokens. Let's do a greedy D code. Now we have our as you can see this is the greedy code. It simply returns the token index that has a maximum probability value. Then we choose that token. Let's visualize another sampling strategy by going def top k sampling. So this is the strategy top k sampling. So we are we are limiting the top k the top the tokens to the top k. Okay, top k sampling and then let's pass into here logits comma and then and then you have to define the k. So how many tokens you want to keep? How many tokens you want to preserve? I want to preserve 50 tokens. The rest will be set to zero. The rest will be discarded. Then we have here a nice documentation keeps this method keeps only top k logets normalize normalize them into probabilities using the softmax function. then sample one token one token from the filtered distribution. Okay, so this is a nice little explanation of what this sampling strategy does. This sampling strategy which is topk sampling keeps only top k logets normalizes them into probability using softmax function. Remember logets are unnormalized scores. Then we pass them to softmax. The softmax takes care of them and normalizes them. What is the normalization process? It makes the sum of all those values add up to one. And all those values will be limited between zero and one. So currently if you see here these are the the logits. You can see that they are negative. They are unnormalized scores. But once we pass them to the softmax function. So let's pass this value to the softmax function by going torch dots soft max. And remember we have to we have to to specify dimension equals zero. Here we have normalized scores. So soft max now makes the sum of all these values add up to one. This is the first point. The second point is that every single value is limited between zero and one. So we don't have negative values and also we do not have uh values that are larger than one. What is the proof? Well, if you try to take the sum of these values I think sum like that well it is one. So the sum or the the total summation of all these values is one because they are normalized. Unlike when we just have the final logits which are unnormalized scores they are ugly. You can see dot values these values when you when we take the sum of it sum it is a unnormalized value but once we pass them to a torch softmax this this is a magical function softmax the most important function in the world of machine learning. Then we specify dimension equals to zero. So here we have to pass into here dot values. Okay. Then here like that dot values. Okay. We have a sum of one. Okay. As you can see. So let's delve into the top case sampling by going values comma indices equals. So we so we we are unpacking unpacking the returned values into a values variable and indices variable and let's go torch do topk let's use the top k function from pytorch library and pass in my logs my magical logs k so the k will be defined by the parameter k equals 50. The second step is that props we want to normalize them into probabilities. Hence we we wrote here normalize them into probability. So we have to pass these values into torch or f do soft max and then pass into here values my literal values comma dimension equals minus1 and remember we have to import at the top there the f function from the pytorch by going import torch.n nn as do functional. So import torch dot n.functional as f like that to be able to use this f in here f.s softmax and then pass in my values and then specify dimension as minus one. Then lastly sampled equals torch dot multinnomial. Let's use the function multi-nomial and then pass into here props my probabilities comma one at the end return indices and then indexing on the sampled like that. So you can see sampled we are passing this as an index to the indices variable and then we have here multinnomial function. Okay run that. So now we have top k sampling top k sampling this function expects from me logits. Let's pass my outputs here. You can see it chooses the tensor at the index 674. If we pass this to a tokenizer decode to visualize what is what is this token? What is this willing token? Well, it is hour. So, top case sambling now chooses the token hour. If we change slightly this function function to enhance for example hour, it will give me another candidates or results into another candidate words. Let's run that again to see the this is a dynamic function dynamically changing. Run that if to change our customer. So if you want to see this word into here, this is the chosen word customer understanding ability work lives. If you write into here customer for example to enhance our customer then it will give me another candidates you can see. And then if you choose this tokenizer decode run this again experience. So one of the words here is experience and I saw it here experience. Okay, this is the way of operating using top K sampling. It just returns the top K logets and then samples from it. The third step is that we have the top probability sampling top B sampling and then it takes from me logits comma P equals 0.9. And let's write a little comment into here to separate the code and make it neat by going top p which is called also nucleus nuculus sampling. So uh you can name it nucleus sampling or top p sampling. This is a nice method to sample from the token pool. It is called top p sampling and it returns the smallest set of possible tokens whose cumulative probabilities add up to a specified threshold called P. So let's go and write a little documentation or documentary here by going star or sort sort tokens by probability keep smallest. So keep smallest number whose cumulative cumulative probability values probability exceeds the threshold P then sample then sample one token. So this is the the the explanation of what this top B sampling does. All it does it sorts tokens by probability values. So it first the model when it generates logits it it it says okay I need to sort these tokens based on their probability values. Once the probability values are sorted from highest to lowest keep smallest number whose cumulative probability exceeds the threshold P. I need to write a threshold exceeds a threshold value P. This P is the hyperparameter that you need to specify. Here I'm specifying it as 0.9 90%. Then sample one token. So the first thing is we need to sorted tokens or logits. Let's call it logits. It's better to call it logits comma sorted underscore indices equals torch dots sort. Let's use the function saw and then pass into here logets that is passed to the function logets. pass it to the function sort sort it and then descending. Do you want to sort it descending or ascending? Well, in my case, yes, I want to sort it in a descending order, in a descending manner. Then let's go ahead and sort it and score probabilities. Let's normalize these logets by passing them to the softmax function. So all we need to do is pass the logits to a softmax function. Hence the softmax will normalize these logets and make the addition or when when you sum these values add up to one by going sorted underscore logits pass it to the function to to the function softmax comma dimension equals minus1. So we have to specify here minus one. Then we have to calculate the to calculate the commitive probabilities. So cumulative commulative props equals sorted probabilities dot sum. So I like the name of the of this function sum meaning cumulative sum. So we have to come sum cumulative sum and then pass dimension equals minus one. So come is short for cumulative sum summation. Okay, this is the commutive probabilities. Then we need to mask tokens outside nucleus nucleus by going mask. So a little masking here operation equals cumulative cumulative probabilities that is larger than the p. So please go ahead and if this cumulative properties exceeds P is larger than P then mask. So then we have here the variable sorted logets and then pass the mask equals float and then pass into minus infinity. So I I want to explain this by going to the polar club here because I have a little explanation. If you can see we can go to polo club transformer explainer of polo club. You can see when we go to the top B probability here we set the value as minus infinity. If we choose top B let the tool work. Now it tries to generate as you can see data visualization empowers users to visualize. And now the tool is trying to generate the next token. Now if you go to top B top P and then probabilities you can see here if you choose the method top P and go to probabilities it sets the rest of the let's make the sampling here for example like that. So the rest are here zero 0%. As you can see, if you choose top K, then we choose the top K five. So the K now is set to five. Whereas if you set the sampling strategy as top, it sets the rest as zero and then it just chooses the smallest set of possible tokens whose cumulative probabilities add up to a specified threshold. For example, 0.5. Okay, so the sum here you can see the sum is 0.5 around that. And if you increase that the the sum takes more logets takes more tokens until it satisfies the the cumulative probability that is you are specifying here. So the sum is 0.81 close to this value 0.8. Okay. This is the idea behind this. The rest we are setting them to what? To 0%. Here we are setting them to minus infinity. At the end let's sample. sample from filtered logits by going filtered filtered underscore probabilities equals f.oftmax. So this function softmax and then pass sorted logets and specify the parameter and dimension equals minus1. Then sampled equals torch dot multi-nomial function and then pass into here the filtered probabilities. We can copy that comma one and here remember to add a equal sign. So sampled equals torch dot multinnomial and then pass filtered probabilities and then specify the dimension as one. At the end return return token index in original vocabulary vocabulary by going return and then we have to specify the sampling here as sorted indices sorted indices and then pass the index here as sampled. So this is this is the variable that we have to specify inside the square brackets the variable sampled and this and that is top P sampling. That's it. Top P sampling. Now we have a function that uses the top piece sampling strategy and samples from the token pool by keeping the smallest set of tokens or of logits whose cumulative probability value exceeds a threshold p value. After we wrote this function top p sampling, let's try it together. So let's call this function top piece sampling and then pass into here my outputs which are the normal logits. You can see my logits. Pass it to the top P sampling function and then specify the P as a a threshold value equals 0.9. Let's run that. As you can see it returns a tensor with the value 1,998. So I wonder what is the corresponding token value or the corresponding word value by going token or tokenizer decode and then just pass in here the token ID. It will simply return the corresponding token or word that corresponds to this ID value experience. So now the top sibling shows us the experiences word. If we if we go ahead and for example to enhance our customer to enhance something let's try this together you can see the the sentences I learn machine learning to enhance then these are the candidates performance to enhance learning to enhance user to enhance data social let's see what is the chosen word using the top piece sampling strategy to enhance human so the top piece sampling thinks that hm The most word I believe should be the next token is the word human which exists here human. Okay. Then if you write here human is just another set of tokens to enhance human. You can see creativity to enhance human health judgment knowledge interaction skills. Let's see here what is the chosen token or word judgment. So as we saw it chooses the word judgment but the top K let's compare this to the top K earlier here it chooses to enhance performance. So the top K sampling thinks the most high probable high probable value should be performance but the top P sampling suggests that judgment. So you can see the difference here. Top P enhance uh chooses empathy. Well uh it's random. So uh when you run it multiple times maybe it will change its sensitivity to another uh word. Okay the top case sampling is also random. Okay. So you can see here when you run again it changes its decision. Now let's go ahead and go to the another uh sampling strategy which is called temperature sampling. So this is one of my favorite strategies. It's called temperature temperature dampling. The temperature is a hyperparameter that is specify it and it changes and it redistributes redistributes the probability distribution. What it does is that the higher the temperature value is, the more creative and the more random the model outputs are. And the lower the temperature values are, the lower you set the temperature to, then the model will be deterministic. The model is deterministic. And it it isn't it isn't creative. It just it just does what it thinks is more deterministic. So def it's called let's call it temperature temperature underscore temperature sampling and then pass in my here my lo jets set the temperature value as a default value equals to 1.0. So feel free to play around with the temperature value. It's fun to change and adjust this value to different values the temperature. Then let's write a nice little documentation here by going scale logets. So remember temperature always scales logets. It returns a scaled version of the logets. Scale logets by temperature by temperature before sampling. So before it samples it scales those logets. Then lower temperature. This is a note lower temperature. Keep in mind that lower temperature values leads to sharper more deterministic. So sharper more deterministic distribution distribution. So if you search here in Google sharp probability distribution to see its image go to images this is a sharp distribution. So it's a sharp probability distribution. But if you if you search here flattened flattened probability distribution this is a flattened one. You can see here you can see this these are the different probabilities there. We have here sharp probability distribution. We have a flattened probability distribution. Okay. And this is also the image of a flattened probability distribution. Okay. The steps here are simple. We have to we have to create a variable called scaled equals scaled equals logets and then divide the logets by the temperature value temperature and then we have probabilities props equals f do softmax and then pass into here the scaled variable scale variable specify the dimension as minus one okay negative one. So these are the uh settings or the the steps. First we divide the logets by a temperature value. This value you specify it as 1 0.5 0.3. Then we take those scaled logets and pass it to the softmax function to normalize it and then store this returned value into a variable called props. At the end we have to go ahead and return torch do multi-nomial and then pass probabilities props comma one. And that's it. We have a temperature sampling strategy. Let's try it together by going ahead and call this function sampling or temperature temperature underscore sampling and then pass in my outputs. as you can see and then let's specify the temperature value. Temperature equals to let's try first 1.0. So let's try to set the temperature as one. So remember when you divide anything by one it will be the same. So if you take the logist and divide it by one then it's the same. Okay let's go ahead and run that. Nice. Now we have a tensor of 4,430. I wonder what is this corresponding token value or word value. Let's go tokenizer do decode. Pass it to the decode function. Run that. It's performance. Okay. So, let's go ahead and see the candidates here. These are the candidates. We have performance. Now, if we change the temperature value a little bit, for example, let's set the temperature to a lower value. For example, let's set it to 0.1. Now remember, lower temperature values leads to more sharper outputs, leads to more deterministic outputs, less creativity. Run that intelligence. So you can see now the model chooses the word intelligence as the next token. Why? Let's read the sentence again. I learn machine learning to enhance human intelligence. So it it is less creative and it chooses the word intelligence. But if we increase the creativity rate of the model by going ahead and set the temperature value to for example 0.5 cognition. So you can see the model now is thinking in in complex manifolds it chooses the word cognition. You can see go ahead here this is the word that it chooses cognition. Okay. And if you increase the temperature further and further 0 9 for example physical. So the the model now is random and choosing uh creative words choosing a very hot words. You can see here I learn machine learning to enhance human physical let me write physical physical for example abilities or performance health functions capabilities let's see what it chooses to enhance human physical function okay and the temperature I think the uh you can increase further 1 for example three it chooses and okay if increase further to 1.5 it chooses Enjoy. So the model now chooses the word enjoy as the next token that it thinks the most probable word. I learn machine learning to enhance human physical enjoy. Enjoy. Okay. Like that. Then we have several several candidates here. It it it will choose one of them vulnerabilities at the temperature 1.5. So these are the different sabling strategies. Okay. And then at the end we have the last uh subling strategy which is called random sampling. So this strategy is isn't common. You will not you will see it rare in the world of machine learning. You will not use it as common as the the previous ones but it's called random sampling. Random sampling. And then let's write the function define. It's called let's call it random. Let's name it random sampling. Then pass into here my logs. Then specify a little documentation here. So your your future self or someone else comes here, he doesn't confused. He doesn't get confused what this function does. He is he has a little explanation what this function does. So if you come back later after 6 months for example or or after one year and you come back to these functions, well I don't remember what this function does. No, you don't get to this situation. You have a explanation that tells you what this function does. This is the benefit of writing a documentation. Sample directly directly from softmax distribution distribution without filtering. So it samples directly with softmax or from softmax distribution without any filtering strategy. props equals torch or f let's use f dots softmax and then pass glogets comma dimension equals minus1 then simply return return torch dot multinnomial and then pass my probabilities one this and that's it now you have a random sampling strategy let's run that let's call it together and see what happens random sampling and then pass in my outputs Here as you can see it returns a you can see when I run that run it again it changes a decision so every time it chooses another uh token it's random so tokenizer tokenizer do decode let's decode it let's see what is the word uh meant meant of I meant let's change the sentence I learn machine learning to enhance so to to trigger GBT to to complete the sentence in a correct way to to enhance every day to enhance my to enhance my doctors to enhance abilities our so it's a random sampling strategy it's a random sampler sample directly from softmax distribution without filtering what it does we pass the logist this to softmax function. It normalizes these logets. Then we pass these probabilities, these probabilities to a multinnomial function and return that. And that's it. We have now a uh four methods, four methodologies to sample from the token pool. Let's try to create another another sentence. For example, sentence equals the sentence today I decided to go to the and let's go ahead inputs equals tokenizer. So let's tokenize the sentence. Remember you have to pre-process the sentence before passing it to the chity model by passing this sentence to the tokenizer. Comma return tenses or return tenses equals PT short for PyTorch. Then we have output equals GBT2 and then pass inputs here. So these are the input ids. These are ids. We pass them to the GBT2 model and and remember you have to put two asterisks here to to unpack it. then logs equals output dot loss and then pass 0 comma minus one to index to the last word. So at the end let's print here print f string a little fing and try to print the first method the first methodology which is greedy decode as then inject the function tokenizer do decode. So we need to decode to decode to the corresponding token by passing the list greedy decode call this nice function and pass into here my logits then the same idea print fing let's name it here top k sampling then print the function or inject the function tokenizer decode tokenizer make sure we read that right dot tokenizer decode and then pass here a the function top k top_k sampling and pass my logest into here specify the k feel free to change it to your own k I will set it by default to 10 then let's go ahead and print the third method which is top p sampling and the top p sampling remember it is called also the nucleus sampling let's go tokenizer decode and then pass into here the function top_p sampling and then pass to here logets comma p specify the p as you would like but in this case I would keep it simple and pass 0.9 the fourth methodology is remember the temperature then we have to pass into here the function tokenizer do decode and then pass into here the temperature temperature sampling and then pass into here loget and then specify the temperature with any value between 0 and one. I will keep it here 0.7. Then at the last we have the random sampling methodology which is a simple tokenizer decode a simple uh sampling strategy random sampling and then pass in my logistics. And with that being said we can run that again. So let's go ahead and 3 2 1 run it. And I'm excited to see that we have no typos. We have no errors as you can see greedy code local. So the greedy decode chooses the the word local. Top case sampling chooses doctor. Top piece sampling chooses lesson. Temperature chose nearest. And you can see random chose military. Let's change the uh sentence here. I today I decided to go to the local doctor lesson. Let's choose for example local. Then how this would change the outputs here. Run that. Here we can see the greedy chooses library. So I today I decided to go to the local library. Top case choose library. Topy uh library. Okay library. And you can see they they are all now unified. They chooses the word and and here we have uh the gre said read and it's reasonable because I go to the library then I would do the what I would do there is reading. But the top K here says find. So let let me go with find and find you can see find out. Yeah because you find find out in English we always put the word out after a find. So it is reasonable then find out what. So the greedy says what the top case sampling says the top piece says what. So let me you can see that the greedy now is equal to the top p sampling strategy. Find out what what was what they what was let me say what was going. Okay. So you can see the top P here says in what was in for example in the in there or in my for example in my wallet. You can see now we have the word wallet as the top case sampling. The temperature says wallet al uh also the temperature says wallet. Let me go ahead and you can see now they are all saying that we need to put a dot here. Then if you run it again they they would say I. Okay. And as another example quickly uh sentence equals I am really happy because you can see I ate they let me say because I have for example then you can see the temperature I have gone it uses gone back and if you change the temperature here you can feel free to play around with that make it 0.1 it will say temperature two but if you make it here for example one really really creative it will say temperature in I will go I have gone back in time you can see I am really happy because I have gone back in time okay and feel free to change and adjust the sentence and also change the K the P the temperature and play around with that and always remember you have this nice tool to visualize analyze and learn about top P, top K sampling and also the temperature here. If you if you want to play around with the temperature, you can see let me write here the the next sentence. I like machine learning because then try to generate now it is uh it will be fast. You can see the tool is already loaded. Then we have here temperature. Now if we make the temperature 0.1 you can see the distribution here is really sharp. It's really just pointing to one token. The rest are zero. But once you increase the temperature, it it distributes that value. So it doesn't make the the distribution goes towards one token, but rather it makes the distribution more flattened flatter. So if you increase it, it gives some proportions to the next and to the and it chooses another tokens other tokens. So it gives some some uh possibility to choose other tokens. Okay, rather than just uh centering all the mind towards one token, we give some opportunity to other tokens to show up. Okay, as as you can see the sampling here methodology is K. Let me increase the K. So you can see the K here is five. So just you want to keep five tokens. The rest are discarded. But let me make it for example 17. Now you can see or for example six. You can see 1 2 3 4 5 6. If you increase that again 10. Now we have 10 tokens. The rest are discarded. We just skip 10. And also if we go to the top P, now you don't have here K, but rather you have a P, which is the cumulative sum, the cumulative probability. And it chooses the smallest set the smallest possible set of tokens whose cumulative probabilities exceeds a threshold P. For example, let me make the the threshold 0.2. Then these are all makes up to uh 0.2. And if we go ahead and increase that, you can see it chooses different tokens. Uh let me decrease the temperature a little bit 0.5. You can see here when we make the top P 0.3, it chooses 100% I. The rest are discarded. If we increase that again, it will choose we here because we and if you go for example like that increase it, it will redistribute the probability distribution. So these are different sampling strategies that are employed to manipulate the distribution or the probability distribution of the token pools and changes the decision of models like GBT and other any other model that is considered a generative model. So keep in mind you can feel free to play around with these values in our collab. So now we have finished about GPT and generation and let's dive into another topic within the transformers library. Now I have a little code that visualizes the probability confidence rates associated with the corresponding tokens. So to write this for loop first we need to construct a sentence sentence and then set this sentence variable to any sentence you would like. For example I would say I learn machine learning to enhance. Then I will ask GB to complete that. Now let's go ahead and pass this sentence to the tokenizer by going token ids equals tokenizer tokenizer dot and then pass into into here sentence return tenses equals pt pytorchinput ids. Now if you visualize this token ids you will see that we have here ids just a normal tensor a simple tensor with these ids 40 200 and it all now let's pass these ids to the gt by going output equals gpd2 and then pass in my token ids the gb here will return if we get this output as output you will see this whole output which which which consists of logits plus also dynamic layer, dynamic layer and so on. We need just to fetch the logs just to retrieve the logist. So let's go ahead and tab into dot logist. So we need just to fetch the logits. If you print that you can see now we just have the logits the raw unnormalized scores that the model outputs. So these are raw values raw. Okay, we can see here row unnormalized scores or values. Now let's go ahead and go to outputs. Override that again equals torch dots softmax and then pass the outputs here. But keep in mind we have to index and get the last out item. So if you do that again like that outputs and visualize it 0, minus one. Well, zero will get rid of this outer bracket. So here if you goes at index zero, it gives me here these brackets. Then if you go comma minus one, it will fetch the last token, the last word. So as we said, we have 1 2 3 4 5 6. We have six words. I learn machine learning to enhance. So we have six words here. We have six vectors. 1 2 3 4 5 6. Inside every single vector, how many values do we have? We have 50,257 logits or values. Why? Because when GPT takes this sentence, it rolls out on it and then predicts 50,000 tokens or 50,000 probabilities or logits for every single word. Okay? And then we we need to access the last token the last word which is if you go ahead outputs we have to put s here you can see we have the last token the last item. Now we need to call the function as you can see torch dos softmax on this. Now note with me what would happen to these values and then we have to pass here dimension equals minus one 3 2 1. Note that these are negative values. What would happen to it now? They are converted into what? Into positive values. Some values are really small. You can see they are they are multiplied by the ula number raised to the power of negative6. And some values are really high. The most high value you can get it by going to argmax argmax. Okay. And then call the argmax function here. You can see the most high value is at index 674. But I don't want to get this. I need to store all of these values inside the outputs variable and override on it. Okay, after that let's go ahead and get the top 10 equals torch do top k. This function is a really helpful function inside torch. It's a really helpful function. Let's pass into here outputs, specify the k as 10 since I named the variable top 10. If you visualize top 10, we have a nice top 10 values here. So that's really cool. Let's go ahead now and do a for loop for index comma value in zip and then pass into here top 10 dot indices comma top 10 values. Let's go ahead and print into here tokenizer tokenizer decode and then pass into here the index dash dash put a curly brackets here injected values and then get there just one number after the uh the dot. Okay, then put the percent sign. Now let's go ahead and run that 3 2 1 values isn't defined. So we have to yeah we need to call this variable value just one value. So here note we have values but here value is referring to this variable. So we unpack this zip object into index. So the indices the indices value gets returned to index and the values value gets returned to value. Then we loop loop loop and then print that print those outputs. And then hooray now we have the tokens associated with their confidence rates. So juby thinks that the most probable word is our. So if you read the sentence again I learn machine learning to enhance our our is is inserted is being inserted 11.5%. If you choose now to enhance for example our understanding is 4.3% ability is 3.9%. Let's go to enhance our understanding. Uh feel free to choose any word from this list. You can you can actually choose any word understanding. Then we have you can see here of 91% soy thinks that 91.8% the this word of is should be the next token. Then if we go the how you can see how human we can choose now uh of them for example the world human brain. So we can say to to enhance our understanding of the brain for example then we can see we have here comma and comma in let's choose for example in the order in ways in general and so on and so forth. So here we have the tokens associated with their confidence rates. GBT is assigning probabilities or probability distribution to these tokens. Okay. And this is how you can visualize and print what is the confidence rate for for every single token. So not only choosing the next token using top K and top B, but also visualizing the confidence rates. And this is a really cool feature you can have in the Python library uh of the zip function and also how to uh print the index passing it to the decode function and get the value. Let's dive into the second task of NLB, natural language processing, which is the task of sentiment analysis. So, let's name this as a title, sentiment analysis. Now, we need a dips set. We need a dips set to be able to classify the the text as positive or negative or even neutral. Let's go to hugging face and then go to their website and search into here. Go to dets and let's go to the filter by name and search for IMDb by Stanford NLB. Then straight away go to use this data set and then you can see we have a library called data sets. Click on it. Then let's copy this code. You can see here this code is simple from dets import load data set. Then we've used this function and pass into here the name the username of the account Stanford NLB/ IMDb. Here you can see we have a nice visual of the samples. You can see here we have some text and its label negative. So ne is short for negative and then we have positive. You can see we we can scroll down and see all the samples. Then we have many pages. Page one, page two. Feel free to explore this data set in your own time. Keep in mind you have to become one with the data in order to be able to model it. Okay. Then we have here if you scroll down you can see we have if you go to this IMDb again we have here also a way how to uh use the data sets using code. So let's go to our collab and paste this code. Run it away. Now we have here readme.md which is a file readme.m markdown. You can see plain text we have this data. The data now is being loaded and downloaded. So all we've done is we've copied it from from hugging face and straight away pasted into the into the Google collab. Now after this code finishes loading, let's go ahead and get the type of this data s data set which is DS. You can see now it's loading. Now it's loaded successfully. Now let's go ahead and type this data set. Now since my variable name here is DS, I'm going to use DS. But you can feel free to name it whatever you want. So here the type of this data set is data sets. Dictionary dot data set dict. So the type of this data set is what is data set dictionary. Let's go ahead and go here data set and then let's access this data set as this. You can see we have training data set. We have testing. Then we have unsupervised. So we have the train data set. Test data set and unsupervised. The train data set is a data set object or a data set class. Then we have features text. Every single text is associated with a label positive, negative, neutral. And the number of rows here is 25,000. And for the test data set, here we have features. We have text column, label column or text text key and the label key. Then we have num rows as 25,000. Okay, let's go ahead and now explore this set in your own uh in in our own way. The first thing is we need to go DS and then choose the key train. You can see now we are indexing and fetching the key train from this DS variable. You can see we have a del class inside we have features and we have num rows. Let's go ahead and try to pass this into our import pandas as pd and then let's go ahead and pass this ds train into a pandas column. So data set and then choose train column or train key dot2 pandas. So now we are converting the data set into a pandas data frame. You can see we have a nice little data frame text. I rented I am curious yellow from my video. This is the text. Then label is zero negative. So the label is zero or one. Zero for negative one for positive. Now let's go ahead and try to index on this data frame by going my data data set frame data frame equals DS2 pandas and then let's fetch the key train by this way. Then we have we can go my data set data frame and then access the column text. You can see we have the column text. Okay. And if you want to know how many samples do we have, we can go ahead and fetch the length of my data set the frame and then choose the key the the the column text. We can get the length as 25,000. Now we need a model to classify the sentiment. So from transformers import the pipeline function pipeline. Then let's go ahead and import that. The second step is we need a model. So let's go pipe equals or you can name it also classifier. Let's use classifier equals pipeline and then pass into here the task you want to conduct. In this case is sentiment sentiment analysis. Also you can write into here text classification like that text classification. It will be the same but in this case I want to use the task sentiment- analysis. Then let's go ahead and and you can specify the model here. Feel free to choose any model. You can go to models and choose whatever model that is used for sentiment analysis. You can go to tasks NLB and then go to text classification. It's the same as sentiment analysis. Then you can choose any model. If you go to to sort the models here and choose most downloads, you will see that it will it will be dist which is the default. So let's keep the default here. And straight away run this as this like it like this. You can see now the model is being downloaded model. Tenses tokenizer_config.json and we have vocabulary text device set to CPU. So now the model is loaded. Let's go ahead and use this model on our text. So we have so we can go classifier and then pass into here my text as this day is great. the classifier will work and it will label it as positive. So you can see now we have a positive label for this string and the score the confidence rate of the model is 99%. So let's go ahead and also uh do another example classifier and then pass here the string this day is terrible is terrible and I am so sad and the model will classify it as negative. Hooray we have label negative and the score is 99%. So you now you have a ready classifier that is uh performing really well pretty well. You can see uh the performance rate here is really high. The model is really is is really confident. Now let's use it on our uh text data set which is IMDb from Stanford NLB. Let's create a function called def score. This function take takes from me a text a sample text. You can name it review text as review text. Then this function will return the classifier and this classifier will work on what on the review text. But we need to specify the limit here as to 500 because this will beert the maximum length is 512. Then we can go at index zero. Then we can fetch the label. We need just the label. So here the same idea you have a list inside this is we have a dictionary. What if you want to just return the label? Well that's easy. index at index zero. It will fetch only the dictionary. Then after that we have a dictionary. Now how to grab the label? We can go label and it will step into that label as negative. Now here we need to pass this function by doing data set or my data set data frame and then choose the column text or let's name a new column called model prediction. the model prediction equals the data set or my data set data frame and then choose the column text dot apply. We have to apply the function score. So here all we are doing is we are applying this little function score. This is a really helpful function. we are applying it on our text column and assigning the value of this function the return value which is the label whether it was negative or or positive we are assigning it to a new column called model prediction. So let's straight away go ahead and run that. Now keep in mind it might take a little bit of time because we have so many samples. As we saw we have 25 rows. So it might take a little bit time. We have to wait until it it generates those predictions. Now in the meantime we can go to distal B to the paper distal B paper we have here this B you can see a distilled version of BERT smaller faster cheaper and lighter as transfer learning from large scale pre-trained models becomes more prevalent in NLP operating these large models in on the edge. So keep in mind this this DLER is really a small model but it's faster, smaller, cheaper and lighter. So it is it has a state-of-the-art performance but also it is pretty fast. So it can be uh it can be it can operate on the edge on the edge. Okay. Under constrained computational training or inference budget remains challenging. In this work, we propose a method to pre-train a smaller general purpose language representation model called distlbert which can then be fine-tuned with good performance on a wide range of tasks like its larger counterparts and we saw that it is performing already pretty well. While most pry work investigated the use of distillation for building task specific models, we leveraged knowledge distillation. So distillation is a one of the brilliant ideas in the world of deep learning. It was proposed by Jeffrey Hinton. Distillation is you train a student model to behave like a teacher model. So rather than using a large model, a pretty massive model, you train a student model that tries to mimic the output layer of a teacher model during the pre-training phase and showed that it's possible to reduce the size of of of a B model by 40%. So they reduced they reduced the size of a BERT model of the original BERT model by 40%. While retaining 97% of its language understanding capabilities and being 60% faster to leverage the inductive biases learned by larger models during pre-training. We introduce a triple loss combining language modeling distillation and cosine distance losses. Our smaller, faster, and lighter model is cheaper to pre-train when and we demonstrate its capabilities of for ondevice computations in a proof of concept experiment and a comparative ondevice study. So by the way feel free to read through this paper. You have this paper here. You can see here this visualization they are comparing distal bird of hugging face by other models like we have GBT. We have here Bert large transformer Elmo GBT2. We have XLM by Facebook or Meta and we have your Nvidia. You can see dist is a really fast model and really performing well. Okay. And you can see here also uh they they present their work here in in the present work. We the student Bert has the same general architecture uh as BERT. The token type embeddings and the pooler are removed while the number of layers is reduced by a factor of two. And you can read this in your own time. But now let's get back to our collab. You can see it's still running. Now the loading has finished. We have applied the function score on the column text successfully. And as you can see here, we have now a column called model prediction ready to go. Let's now go ahead and my data set data frame and show this data frame. Now, hooray. We have a column called model prediction that shows negative, negative, negative, positive. Shows the labels that the model has made on our text. So, let's compare the model predictions to the ground truth labels by going choose the model prediction. We can choose both both columns label comma model prediction. Now you can see here we have label and we have model prediction. Now let's show the first 20 rows. As you can see here we have label zero. The model has got it right as negative. 0 negative zero negative. Then we have here zero. The model hm has made it wrong. The model get it wrong and classified positive. But in fact the label is zero. But the model prediction here is positive. And here we have 0 negative 0 negative negative. And feel free to compare the labels to the ground truth or compare the model prediction to the ground truth label in your own time. But here as you can see we have the this data frame my depth set data frame and it has two columns. It has the label and model prediction. And here we have the text. For example, if you show the first row by going do I lock zero. Here we have 0 comma 1. If you go zero here we have the text. Let's get the text. This is the text of the first sample. We can print it to see what it what is what what it looks like. I rented I am curious hello from my video store because of all the blah blah blah blah. Now what if we pass this text? So this is a review. Let's pass it to my model by going classifier and then pass into here the review. You can see the review. Yeah, we need to get rid of this print function. Now we pass in the review to the classifier and the classifier now took care of it and predicted the label as positive. The score is 78%. Now to get the label we can go label. We can go add index zero to fetch or retrieve this dictionary. Then we can tab into the column or the key label. It is positive. Okay. The ground truth for it. If we go to my data set data frame, this is the data frame. Then we can choose add index zero. We get the sample zero dot eyelock. Here we have the the text sample the first text sample. The label is what? Zero. And the model has predicted that it is positive. Okay. So you can see the model is getting some are right and some are wrong. Okay. But here in this frame we have made the predictions successfully. Now let's go to the next step where we import another model. So if you go to hugging face here in the tab models if you search for a model called finnbert. Now I was exploring the uh models for sentiment analysis and I found this model which is called Finn Bert for financial B. You can see Fenbert is a pre-trained NLB model to analyze sentiment of financial text. It's built by further training of the BERT language model in the finance domain. So the author of this model uh took Bert architecture the same BERT architecture but fine-tuned BERT in the finance domain used some financial documents and fine-tuned it on this financial documents and uh financial documents using a large financial corpus and thereby fine-tuning it for financial sentiment classification. You can see now we are in the in the field or in the task sentiment analysis. Let's go ahead and use this model from the transformers. Here we have the higher level helper and we have the the specified uh class and functions. Let's use the higher level helper. So to use this we can go here. Then we can say from transformers import pipeline. Then we can go pin equals pipeline and then pass into here the name of the task. As we said sentiment- analysis then we can specify the model here as the name of the user slash the name of the model. So here we can copy this and paste it over here. And that's it. Now it's loading Finn Bert a B model archite in the financial domain and it's capable of classifying the financial documents. So let's go ahead and and try some to to predict on some financial sentences by going here. You can see for uh we have the the sentence equals the company reported a strong increase in quarterly in quarterly. So you can quarterly revenue revenue comma exceeding exceeding market expectations. So this is a sentence and you can see it's clearly its meaning is indicating that it's a positive financial sentiment analysis. So the company reported a strong increase in quarterly revenue exceeding market expectations. If you pass this sentence to Fenbert. So now use Finnbert model and then pass my sentence sentence and then go ahead Finnbert will classify it label as positive because why? Because this sentence is referring to a positive indication or positive intent. So the Finbert is using its fine-tuned parameters to classify this sentence and it got it right. This is a positive sentence. The score is 95%. And the paper for Fbert is this paper. You can see Finn Bert by Dogo Arashi. Financial sentiment analysis is a challenging task due to the specialized language or and lack of able data in that domain. General purpose models are not effective enough because of the specialized language used in the financial context. We hypothesize that pre-trained language models can help with this problem because they require fewer labeled examples and you can and you can feel free to read that in your own time. But the most important idea we introduce Finn Bert, a language model based on BERT to tackle NLB tasks in the financial domain and you can find it here on hugging face. Let's try another example with a with a negative sentence by going sentence equals shares fell after the firm reported lower than expected. So you can see the the fine-tuned language here lower than expected. So you need a fine-tuned model trained on massive corpus of financial documents to be able to work and deal with these uh kind of uh very particular terms terminology and then earnings. So here shares fell after the firm reported lower than expected earnings. Let's pass this to my friend Fenbert and then pass my sentence then go ahead. You can see the label is negative because why? Shares fell after the firm reported lower than expected earnings. And the and the score here is 97%. The model is confident by 97% that this sentence belongs to the negative class or the negative uh group. And keep in mind you can also deal with batch deal with several sentences in one in one time by going sentences equals a list. Then let's pass here several sentences. The first sentence is strong consumer demand drove record sales across all regions. The next sentence is supply chain disruptions disruptions severely severely affected production output. And let's pass these uh this list into our fin classifier. Financial BERT pass my sentences and 3 2 1. You can see now we have two different predictions because why? because we have provided the model with two different sentences. Hence the model took that took those sentences and made a prediction for every single sentence on its own. The first is positive and the second is negative. With that being said, let's move on to a third task which is in this case named entity entity recognition recognition. So this task is one of the most common tasks in the world of NLB, natural language processing which is the field of detecting and identifying the named entity recognition for example locations, countries, organizations and the names of persons. Let's go ahead and create our sentence. So sentence equals Apple. So Apple is a company announced announced. Then let's go ahead and record earnings in the United States. Here we have a name for a location on Monday. So here we have a sentence that says Apple announced record earnings in the United States on Monday. Let's pass this to a named entity recognition model by going neer. So ne named entity recognition equals equals pipeline pipeline. So we can use the same function and then pass into here neer. Now of course you can pass here a model. So feel free to go into hugging face go to models and then scroll down to tasks and you can choose from NLP the class of or the field of uh named entity recognition. But here we can see we can explore what is the default model is. So let's just explore go ahead and run this straight away and see and detect what is the default model. So the default model here is what is called dbmdz/bbert large case fine-tuned. So if you take this model and search on it on hugging face you can definitely find it by going scroll up filter by name and there we have it dbmdz and you can see this is the model uh dbmdz/bbert and and it's used for token classification it's built upon the library transformers pytorch tensorflow jax rust and so on you can see downloads last month is 1 million and 700 and about it. And you can see you can go ahead and use this model using transformers and feel free to uh pass that model alongside with the task specified as token classification. But now let's go ahead and use this model straight away by passing my sentence to the neer tag pipe by going named entity recognition and then just pass in my sentence and let's the magic trigger. Here you have a list of dictionaries. You can see the vest dictionary. Let me just show up the sentence here to compare and see. We have apple. So the first thing is we have or org is short for organization company. So here we have Apple. Apple has been detected as an organization. That's perfect. Then we have location which is United. Then we have another location which is states. So you can see United States is a location is a country. Then if you go ahead and try another sentence here you can see location is state. We can go and try another sentence together. So sentence equals for example I worked at Facebook after graduating from Harvard. Then we can pass the sentence to my neer sentence. You can see here we have organization Facebook and have another organization as Harford. And you can see if we pass here for example I for example live in for example UK. Here we have also a location I think called UK. So UK yeah United Kingdom is a location. Okay. I live in UK worked at Facebook after graduating from Harvard and it detected that so beautifully and in pretty well performance. Now let's move on to another task. It's called question answering. Question answering. And this field is also one of the most important fields in the world of NLP where you provide the model with some context, some text and the model tries to find some answers in that text and when you ask it a question, it will answer that question from the text. Let's go ahead and Q&A bot. Let's call it question answering bot equals pipe pipeline and then pass into here the task. So remember you can pass here sentiment- analysis you can pass into here text-cl classification you can pass here named entity recognition neer and also you can pass into here the task as question answering so question dashans answering let's write a answering and see what is the default model that it will provide us Let's let's write here R and then CL enter. You can see the default model here is also distilled / this base case distilled- squad. And now it's it downloaded the model successfully. Let's go ahead and use this model. So we need the text context equals some context. then it can find some answers. So let's copy this context for example and pass it into here context. Let's make that pretty uh uh pretty well visualized by going ahead and when the word is reaching this line it should cut off and go down. The line should cut off and go down like that. So now we have context. Okay, let's go ahead and run that. Then let's provide this model which is QA-bot_bot. Let's provide context equals context and also we have to provide into here some question by going question equals question question and we have also to provide we have to create a question variable equals for example here we have financial sentiment analysis is a challenging task. Let's let's ask it. What is financial financial sentiment analysis like that? This is my question. Let me pass my question. The question and the context as this 3 2 1 let's ask it. Now it works and you can see the score is 30%, answer is a challenging task. So here if we go up you can remember that financial sentiment analysis is a challenging task and it responded with that and it told us that that it is a challenging task. So this is this idea is mimicking the idea of rag retrieval augmented generation. Okay. Also we can ask another question. We can ask question as for example let's read here. We can see general purpose models are not effective enough because of the specialized. Let's ask why why generative models are not effective and then pass this question to my model by giving Q a Q question answering_bot question equals question, context equals context. Then let's go ahead and here we have quest question. Yeah, let's run that. You can see we have score 41% answer specialized language used in a financial back slash in context. And you can see we have here back slashn. If you want to show it in a pretty formatted way, we can sort this output into a variable called result. For example, then we can show this result. Then we can index on the this this dictionary and access the answer key answer. Then we can print it. Print it. You can see print. So specialized language model or specialized language used in financial back slash in the mail context. For example, let's go ahead and here find some we introduce Finnbert. Let's ask it what is Finnbert? What is Finnbert? Fen bird a language model based on bird. You can see I asked it what is fenb bird. It said it said a language model based on bird. And that's it. Feel free to uh grab or fetch another kind of kind of context or text and ask this model whatever you want. But keep in mind this model is the default model which is this still birth. And remember there are some better models, some very powerful models out there in the hugging face platform. You can feel free and go ahead and explore them. Maybe they are better than this subert. You can go ahead and specify the model name as you would like and use it. Okay, but now let's go ahead and move on to the last task which is machine translation. to the task of translating from one language into another converting from one language into another language. So the first thing is we need to define a variable called translate I will name it translator equals pipeline pipeline and then pass into here translation translation_en_2 French. So we have the task of translating from English to French. Let's go ahead and run that. Here you can you can see we are downloading now the translator here we have Google T5. So the default model is Google-T5 which is also if you search here T5 paper this is the paper behind the T5 model which is the default model at hugging face for translating exploring the limits of transfer learning with a unified texttoext transformer by coin rafael and it all. So here you can see they leverage the whole transform architecture. Unlike Bert which is encoder only and unlike Gibb which is decoder only, T5 is using both both uh both parts encoder and decoder. Okay. And they performed very well on the transition task. Okay. So feel free to read that in your own time. Let's go ahead now and use this model by going code and then creating a text or sentence. So translate. So all you need to do is just call your translator your variable translator and then pass in some word. For example, hello. You you know hello in in French is bonjour. So let's go ahead and translator. Hello it's bonjour. And if we if we also translate translator and then pass into here thanks it will say mercy you can see mercy and feel feel free to pass in whatever text you want and it will translate. So you can see how easy it is to translate how easy it is to to find named entity recognition in text. how easy it is to grab some context and ask some questions about it without even training these models without caring about what how to build these models what are these architectures. So hugging face is an open-source platform that hosts millions of models and you can access them freely. So last thing let's try some sentence here for example sentence what is your name what is your name and try to translate it to French translator pass here my sentence go ahead call est vector of veteran num okay so this is how you can translate and feel free to access the dictionary you can you can go at index zero gives you a dictionary then we can access the key translation underscore text and then we have it. Okay, so the the last thing we can go to hugging face like that. Go to models. Here we have tasks. Go to tasks. Go to NLB. Scroll down NLB. Here we have the task of machine translation. Uh translation. Yeah, here we have a plethora of models that are all about trans. You can see the first model is T5 Google T5 which we used before. We have Facebook NLB. So no language left behind. Okay. 200 languages distilled. Then we have Google M A L and feel free to to use whatever you want. If you choose this model, use this model transformers. Then we can copy this model. So this is how easy it is to grab a model from hugging face. Then we can just run it. So this is Facebook NLB model 200 distilled 600m. I think 600m is referring to 600 million parameters. And here we have the model card. You can also read here. This is the model card of NLLB. Here are the metrics. You can read the metrics. Uh there are some intended use. So how we want to use the model. We have some training data, ethical considerations. And this is the model card. And also you can see here we have it's built upon PyTorch transformers and here the number of downloads. Okay, let's go here. You can see the model has been downloaded successfully. Welcome to this section where we will discuss audio processing using Python and how to use models from the hugging face platform to process and model audio. So the first thing here let's name this as audio processing using Python. So how to import an audio in Python? First we need to import some libraries like numpy, mattplot liib and librosa. So let's go import numpy as np import mattplot lib.pipplot as plt and then import librosa. So why do we need these libraries? First numpy because we we want to convert the audio into an array of numbers. Secondly, math plot lip because we need to plot some some plots and visualizations of the audio of the audio amplitude of the audio waves sound waves. Then we have librosa for processing and reading in the audio file. Librosa is the standard library in Python for dealing with and controlling audio files. Secondly, let's go ahead and create a variable called audio path equals and then I already have here a audio file. You can see it's called audio.mpp3. The extension is MP3. Let's pass it here. Audio.mpp3. Then run it away straight away. The third step is here. We have to unpack. We have to call librosa librosa dot load. Call the function load and then pass in here my audio path comma. Then we have here the parameter that is called SR short for sampling rate. The sampling rate is an important concept when dealing with audio. Every single digital audio is associated with a sampling rate. In this case, let's set it to none. This function would return two values. I would unpack them and store them in two different variables. The first variable is y, so my audio. And the second is SR, so sampling rate. So I will store the audio file inside y. and I will store the sampling rate inside this variable SR. Let's go ahead and run that. Now it's trying to load it. And it is already loaded. If we print here why, you can see it's an array. It's a massive array with a lot of numbers, a lot of digital numerical values. Why? Why? Because we have converted and read in the audio into an array. So now we have successfully converted our audio file, our audio path into an array of numbers. And feel free to visualize it like that. For example, the first 100 samples, these are all the numerical numbers, the numerical digits when we converted our audio into an array of numbers. Second, we have here y dot shape. So let's see what is the shape of my y. The shape will be as this. You can see we have one dimension. The audio lives in one dimension and it contains 293,280 values. Then let's go ahead and let's explore what is SR. SR is the sampling rate and it is currently 16,000. Then if you wanted if you wanted to visualize the audio waves, the sound waves, let's go ahead and create a nice figure by going pld.f figure and then pass in here fix size equals then let's go ahead and set it as 14 comma 6 or comma 5 comma dpi let's set it to for example 150 then let's go ahead and go pltot let's plot the audio stored in the variable y let's go ahead and put a beautiful x table as time dash samples so the xaxis represents the time the samples the samples would go on the x-axis then we have plyy label the label of the y-axis as amplitude amplitude of the audio or of the sound okay then let's go ahead and run that and then cool we have here the sound waves you can see these are the sound waves the sound goes like that okay you can you can see here we have sharp sounds and we have then soft sounds then it goes up goes down up down up down like the sinusal waves You can see this is the audio waves. Okay. Then let's go ahead and do the next step. Then we need to divide the number of data points in the sound by the sampling rate yields to yield the total time of the audio. So if you wanted to know or if you wanted to discover what is the total length of the audio all you have to do is to grab here the y the array then get the length of it by passing the y to the length function here we have this number this huge number let's divide it by the sampling rate so the total time of the audio is 18.3 you can see here it's 18.33 okay let's go ahead and so it's it's 18 seconds okay this is in seconds, not minutes, not hours. 18 seconds.33. Then let's go ahead and divide here. You can see from ipython dot display import audio. So in order to listen to this audio, if you wanted to to know what is what this audio actually represents, you can import the audio class from within the display module from within the IPython library. So from IPython note the I is capital here dot display import audio class then run it. Now all you have to do is just call audio and then pass data equals Y comma the rate equals SR the sampling rate. Then run that again. You can see here we have this audio. Maybe you won't be able to listen it but I will run it now. It seems to me more and more as I live longer that most poetry and most literature and particularly the literature of the past is discorded with the vastness and variety. >> Let's move on to the next step because I'm recording my audio now. Then let's go ahead and we have a an important concept which is DFT. And if you don't know this concept, this concept is important in the world of audio. It's short for discrete foryear for your transform transform. And if you wanted to visualize this discrete for your transform function or integral, you can go ahead and go window equals numpy.hanning. So numpy is a pretty uh pretty powerful library. It contains so so many functions. One of these functions is hanning function. The hanning function computes the hanging window. You can see here return the heading window. The heading window is a taper or tapper formed by using a weighted cosine. Let's just pass my audio here. So you have to pass in the length of the of the y. Then we have to go and windowed underscore input equals y * window. So all you have to do is just multiply the y by this window that has created or has calculated for us by using the handling function. And then dft. So discrete for transform equals numpy. FFT. So FFT is short for fast for transform RFT and RFT I believe it's short for real valued uh it's a real valued transform for transform and then pass into here windowed_input. Okay. Then let's run that. You can see here an FFT. So it's called FFT dot R RF yeah RFT RFT is short for real valued fast for transform okay I missed I missed a typo there you can run that again you can see here we have DFT dft now is what is an array array of values okay so again numpy fft is for fast for transform dot real valued vast foria transform and if you search here numpy. FFT dot RFT you can see we have here the function showing up you can see compute the one-dimensional discrete foryear transform for real input real you can see real R is for real this function computes the one-dimensional endpoint discrete 4year transform DFT of a real valued array by means of an efficient algorithm called the fast 4year transform FFT. So f is fast this f short for for t transform and you pass it you provide it with an array input array then you specify the n here we kept we kept the n as optional value you can see here we have a lot of expressions feel free to read this in your own time but now let's go ahead and do the exciting thing of plt.plot plot and then we have to pass in here the DFT. So the discrete for your transform. Then let's go ahead and plt.title. Set a nice little title here as discrete for your transform. Then let's go ahead 3 2 1. Hope it works. And now it worked. You can see we have the discrete for transform here showing up in a nice visualization. And you can see we have sound waves in a discrete for transform function. Then let's go ahead and do the amplitude. Amplitude equals numpy.absolute. So if you wanted for for whatever reason to get the amplitude of this discrete for your transform sound waves, you can pass it to the absolute function to get the absolute value by passing in a dft discrete for transform and easily go ahead and just pl.plot pl.plot plot then pass in here the amplitude. You can see here we have the amplitude. You can see the difference between this waves and this wave. Here we have the absolute version of those waves. Then let's go ahead and continue our process by going amplitude dB. So dB is short for decibel. Decibel is the unit of measuring audio in the universe. So we have librosa dot librosa.mplitude amplitude amplitude_2 dB which is a nice helpful function to convert amplitude to decibel and then pass into here amplitude amplitude comma ref the reference equals numpy domax and then all I have to do is just go frequency frequency equals librosa dot fftft frequencies so we have here a function called fft fast for transform frequencies and then pass into here SR the sampling rate equals SR sampling rate comma NFTt FFT equals length of Y and then we have we can go easily pligure create a figure and then set the fig size to make it look pretty as 515A 4 and then the DPI as our faithful value 150. Then let's go ahead and plt dot plot and then pass in my frequency comma amplitude db. So remember we have converted our amplitude unit to to to decibel and stored it in the variable amplitude db plt.x label and then set it as frequency in heads in the unit of heads. Let's go plt.y label and then pass in here amplitude in decibel. You can see decible is written as B small B capital. Then we have here plt.x scale. So you have to if you if we go ahead and just run that as that you can see it's now it's now the x scale isn't measured in a logarithmic measure. It's measured in linearly. But once we set the x scale and then pass in log short for logarithm logarithm function you can see now the measure changes. It's now uh showed in a logarithmic fashion. So you have to set the x scale as log to show the x scale as in a logarithmic fashion. And keep in mind you can see here the scale 10 raised to ^ 1 10 raised to the power 0 10 raised to ^ 1. If we now get rid of this log, it will be measured in linear units 0 1,00 2,000 3,000 4,000 and so on. But when once we open this comment or uncomment this and measure the X scale logarithmically, this these numbers will be in logarithmic world. You can see. Okay. Now let's go ahead and continue our process. Here we have a a code for converting the audio into STFT by going D. Librosa STFT and then pass in my Y. Now you can see this D what it looks like. This is the S stft version. Then we have to go ahead and just go D DB. So convert it to decibel by going librosa.mplitude_2 amplitude_2 decibel and then pass in numpy.absolute and then pass in my d. Just we have to pass in my d inside of wrapped within the function absolute and then wrap this function within the amplitude to db to convert from amplitude to decibel and then set reference equals numpy.mmax. Now all I have to do is just create a figure plt.figure figure and then pass into my figure here the fixed size to set the fixed size as 15 or 14a 5 dpi = 150 then we have plt dot or librosa let's go librosa now librosa dot display so please display dot spec so if you know spectrogram spectrogram is the standard way to plot audio spectro and then just pass d db comma sampling rate equals sampling rate comma x-axis equals sets it as the value time so name it as time and the yaxis represents the log logarithmic then we have pltc calibbar so if you want to make it pretty and visualize the calabar you can set it as format equals percent sign plus 2 then you can dot 0f db so this is the format of the numbers we want just to show just two decimal points after the zero. You can see here this is the visualization. It's a it a spectrogram for visualizing the audio. The x-axis represents the time. The y-axis represents the hertz. You can see in the unit of hertz and here we have the calaba showing from 80 decel to zero decibel. So the closer the color to this color lighter it's close to zero decibel and then the closer the color here. So these regions here represents the zero decibb. When we reach this color this darker the darker the color the more the value of the this sound wave or this sound point the closer it is to 80 decel. You can see here we have very 80 decel. Okay. Then let's move on to the next visualization. Let's go. S equals labrosa dot feature dot male specttogram. Also we have another type of specttogram. It's called MEL specttogram. So we can go to librosa. This is the library of librosa. You can see here. This is the homepage of librosa audio and music processing in Python. And here we have the documentation. You can see this is the logo of of labrosa. It's the standard library in Python for dealing with audio files. You can easily pip install it. If you don't have it, for example, if you are on a local Jupiter and you don't have this library already installed, you can go pip install librosa. Then we have librosa is also available on package. You can install it by saying install Conda for librosa. And don't forget here the second website here is the documentation. You can feel free to read about the functions. Uh troubleshooting. We have display. You can see display here. I think they will display the function as we did now. The spectrogram and also they will teach you a lot about about hertz format, chroma formatter uh and and a bunch of other functions that if you want to dive deeper into the browser. But here let's keep the things simple and just pass into here y = y comma sampling rate equals sampling rate comma n millls. So what is the number of mills? Let's set it as 125 125 and then or 128 for example. Then comma f max equals 8,000. Then let's go ahead and convert it to decibel by going db. So remember the B is capital equals librosa dot power_2 decibel. So convert the power to decibel and then we have we have to pass in s comma reference equals numpy domax then plt dot figure to to create a figure a nice pretty figure and then set the fix size as 14a 5 and then dpi equals 150 and remember we have to make our code pretty and aesthetically appealing. Then librosa dot display dotspec show spectrogram. So spec show and then pass into here s db s in the in the unit of decel. We have sampling rate equals sampling rate comma xaxis equals let's make it as time comma y_axis let's set it as log log short for logarithm. Then we have f max equals 8,000. Then on the last here you have to show a color bar by giving penalty doc color bar and then pass into your format equals percent sign plus two dot 0f then db 3 2 1 go ahead run. You can see now the code works fine and it shows us this another spectrogram which is by converting the array or the sound wave to STFT or MEL spectrogram function. So it's kind of look the same. This is a normal spectrogram and this is called MEL spectrogram. If you wanted to know the difference, you can feel free search that on Google. But now let's go ahead and just do the the other part which is now get a model from hugging face and try to classify it uh to classify this audio based on a model from hugging face. So we have to import required required libraries and remember this task is called audio audio classification. So the first thing is we have to go ahead and just import those libraries by going import torch comma transforms comma uh transformers. You need transformers because remember the default library in hugging face for dealing with audio is the same as the text. It's called transformers. So the same library transformers works for text and works for audio. Then we have to import here torch audio. Okay. Then let's print the versions of them. Torch dot just for fun version. Then we have here print torch or transformers transformers dot underscore underscore version underscore. Then we have to print here print torch audio version run it away. You can see here torch. Transforms torch audio version. It will show us these versions. So my torch version at the time of recording this video 2.9.0 plus CUDA 12.6 remember in the future you might have a slightly bigger number. Then we have here transformers version. Currently it's 4.57.3 and here we have torch audio. It's 2.9.0 plus cuda 12.6. So let's go ahead now and do the audio classification process. The first thing the first thing is we need to import from transformers. So from the library transformers inside hugging face import auto picture extraction or extractor, a st for audio classification. You can see the naming are here uh long. So you have to keep in mind the first letter of every word is capital. So a is all capitals for audio classification and you have the class auto feature extractor. Run it uh straight away. Then you can see now it's trying to import and fetch those classes from the transformers library. The second step is that we have to import leosa again. You don't have to because you have it we already have it like but we we can import it again. Then we have audio path. So maybe you need to keep this section separate from this section by importing all the necessary libraries again. So sometimes you don't want to run the whole collab. So you might in some point just run from the cell but have all the codes below the cell working. So you have to sometimes reimpport the libraries as we saw here. Then the audio path equals audiompp3 the name of my audio. Remember I have I already have an audio here file called audio.mpp3. Let's pass it to my variable here. Audio path. Then let's go ahead and we have y, sr equals librosa.load. Just have some practice. Then we have here we have we have to pass the audio path comma the sr equals none. So here all we are doing is just we are passing the audio path to the load function. The load function will take care of this audio path and read the the audio path in. It will read this audio file in and convert it from audio waves from audio file into an array stored in this variable. Y. You can see this array. It's a huge array. And every single audio is connected with a sampling rate. We store it in this variable called SR short for sampling rate. And it's currently 16,000. But now let's dive into the most important idea which is and and also you can visualize it using from ipython of course from ipython display import audio class. Now let's call this class audio and then pass in my audio path by going data data parameter equals audio path then run it. You can see now this is my audio. I will play it and you can listen it now. It seems to me more and more as I live longer that most poetry and most literature and particularly the literature of the past is discordant with the vastness and variety, the reserves and resources and recuperations of life as we live it today. Now the audio has finished. You can see it's finished. We can continue our processing and coding. So the first thing is we have to go picture extractor picture extractor this my this is a variable well where I will call the class auto picture extractor dot from pre-trained. So here we are calling the method from pre-trained and then pass into here the name of the model. So you can see it's from the MIT University-finetuned fine-tuned audio set audio set- 10-10-0 the version 4598 so 4593 okay this is the name of the model okay we are passing this string to the method from underscore pre-trained coming from the discuss auto feature feature extractor and then we are instantiating a new object and convert and sorting it inside this variable feature extractor. Let's run that. You can see now it's trying to instantiate. Then the processor the pre-processor_conig.json has been loaded 100%. Okay. Now let's go ahead and uh see the see here you can see we have a result. Let's create the result variable equals feature extract. So let's call let's now leverage the benefit of using this object feature extractor then and just pass into here my y the array of the audio comma return tenses. So return tenses set it as pt short for pytorch. So please return the tenses in the form of pytorch tenses and then let's run that. You can see here this is uh the running of this cell. Let's go ahead and visualize my result. You can see and hooray. Here we have my result. We have a dictionary. We have a key called input values and the value as a tensor. Here this class has worked on my array of values, the array of the audio and produced this tensor that contains these numbers. You can see we can access this dictionary by going result in the key input values. Then we have this tensor. Then you can also visualize the shape what it looks like. We have one. So we have a batch of one. Then we have 124. Then we have 128. Okay. Then let's go ahead and dive into uh calling in the model loading in the model by going a for audio classification. So we have imported discuss earlier. It's called a for audio classification. Remember my task here is to classify audio. We will not going to uh produce audio here in this specific task. We are going to classify audio by dot from pre-trained and then pass in here MIT/-finetuned dash audio set- 10-10-0.4593. Then we can also keep in mind you can copy this name go to hugging face and search for it. by going to models tab then paste the name into here you can see we have this model MIT and the task here is audio classification and here we have 86.6 6 million updated September 6, 2023. You can go into it. You can see this this is the name. You can copy it if you don't want to write these numbers. You can copy from here and just paste it over here. Here you have you can see here you have uh how to use this model. Use this model and go to transformers. Here we have from transformers import pipeline. You can use the higher level the highle helper and also you can use load model directory as we did together. Auto feature extractor. we have imported from transformers and also we have here automodel for audio classification. If you don't like to type code you can copy that and just paste over over there and and you will have the extractor and also you will have then the model which is automodel for audio classification from pre-trained and then pass in the username of the account/ the name of the model and keep in mind you have you you might need to read here on how to use this model okay later. So the model description the audio specttogram transformer is equivalent to vit but applied to audio and blah blah blah. Let's go ahead and just run this cell. You can see here we have some typo a for audio audio classification. Let's just choose it. You can see the model is running with no any single error. You can see we have here models save tensors. It's loaded successfully. And then all we have to do now we have a model. Now actually you can visualize this model by going model. This is the model architecture. Feel free to uh look look at this model architecture to learn from it. We have as embeddings as P patch embeddings. So you can see we have patches here. So this paper I think here they will direct us to the paper. You can see in this repository actually we can search for this and write paper. So yeah this is uh that's it. It's called AST audio specttogram transformer by Yuan Gong and it all in in the past decade convolution neuron X CNN's have been widely adopted as the main building block for end to end audio classification models which aim to learn a direct mapping from audio spectrograms to corresponding neighbors to better capture long range global context. A recent trend is to add a self- attention mechanism on top of the CNN forming a CNN attention hybrid model. So in the past they used to use a self attention mechanism on top of the CNN forming a CNN attention hybrid model. However, it's unclear whether the reliance on a CNN is necessary and if neuronets purely based on attention are sufficient to obtain good performance on audio classification. In this paper, we answer the question by introducing the audio specttogram transformer A, the first convolution free purely attentionbased model for audio classification. We evaluate a on various audio cast benchmarks where it achieves new state-of-the-art results on uh of 0.485 AMAP on audio set 95%.6 accuracy on SC 50 and 98.1% accuracy on speech commands v2. And here if you visualize it you can see the architecture is very simple. They have here some input spectrogram. Then they patchify it patch split with overlap 1 2 3 4 5 6 7. Then they flattened it using a linear projection layer. Linear projection layer. Then they embed it. So we have E. This E is short for embedding. So embedding one, embedding two, embedding three and the rest. Then we have positional encoding P 0, P1, P3. So here they have uh pre-processed the audio to add to map embeddings to map these patches into embeddings and then insert or inject some positional encodings to to preserve the positional of the audio. Then they straight away pass it into a transformer encoder block. Then they have a line layer to classify and then produce some logits to classify. Now let's go ahead and use this giant architecture. This pretty powerful archite which is uploaded on hugging on hugging face. You can see here we have a then let's use it. So this is the architecture we have already came through it. Now let's go ahead and go to the next step where we will uh see here result and then choose the key input values. So now remember I had an audio and I passed it to my auto feature extractor here feature extractor. So I inserted a new object or feature extractor. Then I use that feature extractor object to pass my audio. Then it produced a really really powerful tensor. This tensor is ready to be passed in this architecture and to be processed further further further until the model decides what is the actual uh what is the actual class of this audio. Then let's go ahead and just use this tensor this magical tensor and pass it to here. So prediction logs I really love the logits equals model and then pass into here result and then also step into input values dot loggets. So here all we are doing is we are fetching retrieving that input values tensor passing it to our model this model as then this model will go through some several steps thanks to these authors. These are really kind authors. They have created a really powerful model here. Then we can just go ahead and get or grab the logs. Then we can go ahead and get the logs. Now you have logits prediction and the score logs. And these are the logits. You can see these are unnormalized scores the model has produced and they represents how much the model or how much the model believes that this audio belongs to every new class. though this number represents how much ofeness the model thinks this audio should belong to this class and so on for every single class. Now let's go ahead and create a variable called predicted class ids and then go ahead and torch.orgmax argmax and then pass in prediction logits comma dimension equals one. So all we're doing here is we are dimension equals minus one. You have to grab or fetch the last dimension. Here we are passing my logits to the arc max function. The arc max function will return the index at which the highest value would be the highest probability value is. And then just give me that item and that's simple. Then we have this predicted underscore class underscore uh ids. Let me just yeah write ids. Then you can see here we have ids. It's now zero. But I wonder what is this class? What does zero represents? What is the corresponding human readable class name that corresponds to zero? Well, you can get it by going model.config. So short for configuration do ID2 label and then all you have to do is just uh pass you can see here these are all the classes the available classes within this model. So here you can see zero is speech currently this audio is speech one male speech second female speech woman speaking three child speech uh conversation they have via babbling uh speech synthesizer shout bellow whoop yell yell children shouting screaming these are all the different classes and different categories that exist in this model. You can see here also we have via uh goose, honk, wild animals, uh bird. You can uh fetch some bird sound from the internet and classify it and it will classify it. Here the most important idea is the our model predicted that the most believable loget should be at this position here at position zero. Okay, so the predicted class ids is zero and we know that zero is speech. So let's just go ahead and index on this by going model.config do id2 label and then just pass in here predicted class ids. Then run that and the model successfully told us that this audio belongs to the speech class. So what a surprise. Okay. So the model is successfully. So look at look at how much easy it is to use a model from a hugging face to classify audios. Feel free to to retrieve or grab your own audio from the internet or your your your favorite music or whatever you want and try to run this model on it and this model will classify it and return you a class name for what this audio belongs to. So you can see hugging face is now a truth treasure. Hugging face contains 2 million models and they are all open source to us. They are all available to us. You can easily within five lines of code I think here if you compress them there are actually two lines of code to have a model to classify for you to classify audio without worrying about without you don't have to worry about how to train it you don't have to worry about the about the hyperparameters you don't have to worry about what the arisha how to complete how to combine this arisha what are the embeddings what are the the position coding how to construct a transformer they they have done all the work for you they you have uploaded this architecture onto hugging face trained on a massive data set. The model has really powerful parameters then you can easily leverage them for free. Okay, so this is how to classify audio and let's dive into another task in the audio world. And also keep in mind you have you can go to hugging face, you can go to tasks, models, tasks, then go to audio here. Here we have audio under the NLP we have audio, we have text to speech, text to audio. Uh we will do this. We will do text to speech and also we will do text to audio and uh we already have done uh audio classification, audio classification. So feel free to play around this. And also we have automatic speech recognition. Now let's dive into another task of the world of audio in machine learning which is converting converting audio to text. So this is the modality converting the model audio into the model text. The first thing is we have to from transformers from transformers import pipeline. So we have to import the pipeline function from the transformers library inside hugging face. Then let's go ahead and create a pipe equals pipeline and then pass into here automatic- speech dash recognition recognition. So this is the task of converting audio to to text. It's called automatic speech recognition ASR. Yeah, you can see we have a typo, a classic error. Now the model is running successfully. You can see here it's downloading model safe tenses uh same weights some weights we have vocabulary special tokens they are all loaded and downloaded successfully. The next step is let's use this model pipe and try to convert the audio to text. So the first thing is let's go pipe. You can see here the pipe. This is my current pipe transformers.pipelinesautomatic pipelines dotautomatic speech recognition dotautomatic speech recognition pipeline at this stored at this location in the memory. Then let's go ahead and dive into pass uh pass in here my audio.mpp3mpp3. So currently I have an audio file here stored here. It's called audio.mpp3. Let's pass th this file path into my pipe which is this model that I have loaded previously automatic speech recognition and then we uh loaded a pipeline and stored it in the variable pipe. Now let's run this command pipe and then pass in my audio. Now you can see this is my audio and it converted that audio into text. You can see here we have a dictionary text. It seems to me more and more as I live longer that most poetry and most literature and particularly the literature of the past is discordant with a with a vastness and variety that uh the reverses and resources and recorruptions of life or recap recapations of life as we live uh today. So this is the text we have converted the model audio into the model text successfully. You can see feel free to change this audio into whatever audio file you have. For example, you can record your own voice and pass it to here. You can download or load the file here. Then you can pass it to the model and the model will transcribe that audio into the text. Now let's dive into another task which is converting text to audio. So now let's do the reverse. Let's do the reverse option which is converting text to audio. What if you have some text and you want to convert it into some audio file? Well, you can do that easily using hugging face platform. The first thing is let's go from transformers. So remember when you deal with audio you have to deal with transformers not diffusers. From transformers import pipeline. This is a function a highle helper. a high level helper that you want to use or that you will use to load in models from the platform hugging face. Then let's go pipe equals pipe equals pipeline. Then let's pass into here text to -ash2- speech. So convert text to speech the reverse oper uh the reverse process. You can see the model here is loading. It's it's trying to fetch it's trying to fetch that model from the pipeline of hugging face using the library transformers. Now let it download on its own and then once it's finished we can go and write some text. For example, I like coding in Python. For example, this is my text. Then we can go ahead and show it. You can see this is my text. I like coding in Python. Let's pass it to my pipeline pipe. Here we can go. You can see output. Let's create a variable called output equals pipe and then pass in here text. So all you have to do is just create some text. You don't have to store it in variable. I stored it in variable to make my code neat. Then we pass that variable text into the pipe function. Then it will produce an an audio out of this text. Let's go ahead and run that. You can see now it's trying to create and produce an audio file audio waves from this text and it's finished. Now we have output. This is my output. You can see it outputed a dictionary of audio and sampling rate. As I told you, every single digital audio in the computer is connected to a sampling rate. And the sampling rate here is 24,000. The audio here is in the form of array. So this model as we know machine learning is the art of converting data into numbers and then passing these numbers into models. Then the model will produce also numbers. So the model will not produce here straight away a audio file path or audio file but rather it will produce an array of numbers. Let's go ahead now and uh index to it and have this output. You can say we can see here output and then get the key audio. This is my array. Then also we can get the shape of it. We can go here and then at the new cell output and then audio. Then let's go and print the shape out of it. The shape is 1 comma 50,90 59 59,840. So it contains 59,840 values. If you go ahead now and do like that output and then index on the audio dot squeeze. If you squeeze it, we will get rid of this one. You can see our output here is written output audio and then do squeeze. Now we have this shape without the one here. You can see just we have this value. We can pass this. So here we can we can get this and pass this array to plt.plot. So plot it using mattplot lip. Okay, then we can go ahead and run that. You can see these are the audio the audio waves the sound waves that the model has produced. So this audio didn't exist. The model we provided the model with this text I like coding in Python. Then the model has produced these waves and stored it in an array that is like that a massive array that contains 59,000 and and it's about values. Now let's go ahead and from IPython. So if you wanted to listen to this audio you can do that easily by going from I from ipython dot display import audio. So you have to import the class audio and all you have to provide to this class is the audio. Then go ahead and you can see data pass in data equals output and then index on the audio key, rate equals output and then pass in here sampling rate because remember the output of the model is a dictionary as you saw here that contains two different keys two distinct keys audio and sampling rate. To access sampling rate you have to go output this is the name of the dictionary and then access the sampling underscore rate and it will provide you with the sampling rate and the same with the audio it will provide you with the array with those with these values and if you show output it will be a whole dictionary. Now let's go ahead and run this as it is. You can see now this is my audio. Let's play let's play it. >> I like coding in Python. And keep in mind these models uh these models are open source on hugging face. They are not the most perfect models out there in the world. So maybe the sound will be uh noisy a little bit. Maybe it contains some noises in the background, but that's fine. All you have to do is go to hugging face, go to tasks here, then scroll down until you go to audio, then choose text to speech. This task converting text to speech. Then you can choose uh the best models from here. So maybe try to use Microsoft vibe voice vibe voice maybe you want to use Araco T5 GMA and so on. So feel free to choose whatever model you you would like to use you prefer to use from here. Here we have you can see 3,000 models dedicated to this task which is text to speech and also we have text to audio which is the task of converting text to audio. You have models 2,623 models. You can see stability also has a model called stable audio open. Also have Facebook music gen large. We have also Marvis AI/ Marvis. And you can see we have tons and tons of models. Then also we can go to here ASR automatic speech recognition. Then we can find heaps of models. How to use it? You can go to here for example open eye whisper. Then all you have to do is just go to transformers then copy this code or this code into the environment collab and it will work for you. Just as easy as that. Here we can go ahead and so by uh with that being said we finished the model audio. We have finished this section of audio. You can see we have done three different tasks. The task of audio classification where we classified some audio into speech. Here it told us that it's speech. You can see here these are the logists that the model has produced and then the we have provided with some speech and it says that it is zero which means it's a speech here you can see speech and then we have another task which is converting audio to text the process of converting audio into text and we have provided it with some audio file you can see here we have loaded a model called automatic speech recognition and be careful about the typos previously I written here auto in a reverse way and it did load. You have to be careful when you write these words. Then here we have converted the audio into text. You can see it seems to me more and more as I live longer. So we have provided an audio and it converted it into some text. At the last we have the last task which is converting text to audio. The reverse you provide the model with some text and the model tries to tries its best to convert this text into audio using some deep learning mechanism. And you can see these are the sound waves. And then if you want to save this audio file path you can go with that. You can go with that easily by going you can see here we have a from ipython. So let's go from or from pi dub from python dub import audio segment. This is a class. Then we have to go ahead and create an instance called audio. Audio seg equals audio segment the class audio segment. You can see segment and then provide here the output and then index on what on the audio to get the the array with the with these values dot two bytes. Then let's go ahead and comma provide the frame rate equals. So the frame rate is the same as the sampling rate but another name. So output and then index on the sampling underscore rate and then you have to provide or supply this function with the sample width equals output and then index on audio dype dot item size comma. So here you can see we have here the type. So the data type okay then at the last we have to provide the parameter channels. So how many channels are there? We have one channel 3 2 1 run that. And now we have successfully uh saved our model. Let's go ahead and audio seg. Let's use that object or that instance dot export. So we have a function called export that will export my audio and then pass in the name of the audio. For example, my audio saved dot and you have to provide the extension as MP3, the format of the audio should be in this format MP3. Now let's run that and you can see it saved the model with this name my audio saved.mpp3 using this name. If you open this file section in collab, you will see that I have now a new file my audio saved mp3. And to download it, just double click on it and it will download straight away. In this section, let's dive into diffuses models for images and generating images using hugging face platform. The first thing let's name this cell by going image processing. So let's take the first some techniques to process images in the Python language using Python programming language and then let's convert it into Macdown. You can see image processing using Python. So the first thing we need an image. You can see here I already have an image and it's called whiteflower.jpg. You can see it here. Now let's process this image using Python. The first thing is let's go from pill import py import image by going from pill import image. So from Python image library import the class image and the class image will read in our image file and then convert it into an array full of numbers by going pick equals image dot open. Then let's pass into here let's pass into here my image path by going flower dot. You can see here my extension is jpg. So let's write white dash blower.jpg. And now it's read successfully. If you go ahead and show this pic short for picture here we have this picture. Then let's go ahead the next step. So now we have done the the reading of the image. The next step is what if you want to check the type of the picture. What is the type of the picture? The tab is JPEG image file. And keep in mind if you read in a PNG image, it will the type of it will be PNG image file. And if you read a GIF image, it will be GIF image and so on. So whatever the extension we have, this end part, this ending part will change depending on the extension of the image. Let's go ahead. Then we need to to import numpy as np to convert our image into an array into a numpy array. And remember numpy is the fundamental computing library inside the python ecosystem for data science. Let's go ahead and do picture array equals numpy as array. So we have a helpful function inside numpy. So within numpy we have a function called you can see numpy numerical python we have a function called as array. This function is responsible for converting the image into an array in in numpy by passing in my picture. Then let's go ahead and show my picture array. You can see we have this we can show data and then convert this image or this picture or this image into an array full of numbers. You can see these are 255 255 255. It's a white pixel corresponding to this region where you can see I have here so many white pixels and these are all white pixels. Okay. Then we have here some yellow pixels and so on. Now let's go ahead and retrieve the shape of this array by going pick array dotshape and the shape of it is as you can see we have 360 comma 360 comma 3. So here we have the height, the width and the color channels. So every single image is containing a height dimension, a width dimension and a color channels dimension. The number of color channels, if the image is colored, so it's a if it's a colorful image, then the number of channels would be three. And if the image is a grayscale image, so it's a silver image, or a gray image, then you have just one channel. In this case, it's a colored image. So here we have three different color channels and these are red, green, blue. Now if you take a a closer look at my picture array, it contains integer values. These numbers are integer. These are a whole numbers. If you want to normalize the image, we have to divide it by 255. So 255. Then it will be normalized. As you can see the where the most white color would correspond to one and the most dark color so the most black color would correspond to zero and every other color between zero and one. So you can see here once we go ahead and import mattplot liib import mattplot liib.pipplot as plt. So mathlip is the default library in Python or the standard library in Python for visualizing and plotting some visualizations. Let's go ahead and pltim show and then pass in my picture array. So you can see here by passing my picture array to the im show function. IM show is short for image show. It shows our image the flower image. You can see and here we have some axes. If you want to get rid of these axes, you can do that easily by going plt dot access and then pass here false. You can see here it will turn off the axes, the x-axis and the y-axis. Now let's go straight away and picture red. So what if you want just to view or to display just the red channel? You can do that easily by going picture red equals picture array.copy. So first I advise you to copy the picture array into a new variable. So rather than manipulating and damaging the actual array here where you could you could do that but I advise you I recommend I highly recommend that you copy this array and store it into a variable called picture red. Then you can see here we have the same exact copy. So here pick red currently is the same exact copy because we have done nothing but copied the array into a new variable called p pick red short for picture red. Now let's do the manipulation part where you will go ahead and you can remember we have RGB. Now we want to zero the green channel, zero the blue channel and just keep the red channel. And look what happens here. We can see pick red and then give me all the height dimension. No problem. Comma. Also give me all the width dimension. I don't want to get rid of any the width or height. I don't want to cut anything of the image. But just set the one channel which is G. So remember R zero, G is one, B is two. Please set the one channel. This green channel set it to zero. So here you can see green channel green channel set to zero. So zero it then the same with the blue channel give me all the height all the width and then the second channel which is B. Remember in programming we start counting from zero set it to zero. So zero out the blue channel. Then here we have blue channel set as zero. You can see here my picture red now is a red image. So you can see now we have got rid we have removed the blue channel the green channel and only kept the red channel. You can see here we have this array. It just contains you can see here every single blue value and every single green value is now zeroed out. The green channel is zero. The blue channel is zero for all pixels for all values. just the red channel is kept and you can see now we have a very reddish picture. Now let's go ahead and do the same with the the rest and the remaining of the channels by going RGB. Remember here we have to go ahead and copy the array by going pick green equals pick array. So give me the picture array the original array but copy it dotcopy. So make a copy of it. Then let's go ahead and say pick underscore green and then give me all the height all the width but please go ahead and for the red channel zero it out and the same here pick underscore green give me all the height all the width but please for the blue channel zero it out here we have remember zero corresponds to what the red channel so red channel is zeroed out is zeroed And here the blue channel, blue channel is zeroed. Set to zero. And here also set to zero. And now let's see what would happen here by printing out my picture underscore green. 3 2 1 run that. And here you have a green like image. So you can see the red channel is zero out is zeroed out. The blue channel is zeroed. While we have kept all the green channels, you can see now we have a green image. Let's do the same with the last channel by going ahead and copying out the picture blue equals pick ray dotcopy. Let's go. Picture blue. And then just set the zero channel to zero which is red. And then do the same with the one channel which is green to zero. Then let's visualize my picture blue where you have a blue image. Okay. So we have red, green, blue. We have three color channels. Red, green, blue. Now you can see that these are the manipulation of images. We can go ahead and also do some feather processing using now CV2. Import CV2. So CV2 is a library inside Python and it's short for computer vision 2. So CV is has also pretty much functionalities to manipulate and to process images in Python. So let's go ahead image equals CV2 im read. So please image read the image by passing here the path of the image. So let's copy here the path of the image. You can go ahead and just copy the path and pass it to this function m read. Here we have image. You can see it read the image here. But you can see there's a difference. Why? When we read the image using the normal pil library in Python, Python image library, it read that image and it displayed that image as this. You can see here these colors are yellow. But here when we read the image using this library CV2, you can see here we have different color. We have different color hues. Why? Because if you notice the real image or the actual image actually is the same as the way that the PIL image has read it in. So CV2 keep in mind that CV2 library here it changes the order of the channels. So rather than red green blue it's blue green red. So let's go ahead and change that. Here you can see image RGB equals CV2. If you want to get it in the in the original format, if you want to get back to the original format and the original form, you can do that easily by going CV2 dot CVT color. So you have a nice function here. It's an amazing function. It's called CVT color. And then pass into here image comma CV2 dot you can see here color uh write it all in caps so all in capitals color underscore B G R so blue green blue uh blue green red to red green blue so this is the the name that you want to write color underscore blue green red two red green blue as I told you this library or this package that uh which is called CV2 when you read an image using it it reads that image and it manipulates and damages the color schemes how to solve it well there's a helpful function a very amazing function you can use it just pass in the image and then write this flag cv2 color_bgr2gb then let's go ahead and run that you have a image underscore RGB. So you can see we are now having the same image. You can see we have returned that image to its original format to its original form. You can see now this region is now not anymore blue but now is the is the original form which is yellow. Okay. So this is how you can get back to the original format. If you read an image using CV2, please keep in mind you have to call the function CVT color. Pass in the image you want to apply the manipulation on it. Then write this flag CV2 dot CV2C color blue green red to RGB red green blue to the normal and regular format. So now let's convert this image into a grayscale image by going image gray and then equals cv2 dot m read. So we have to read in the image. So remember m read short for image read. So please read in the image and we have to pass into here my image file path by copying the path and then pass into the my function here. Then let's go ahead and also provide this parameter cv2 dot im read underscore. So image readers gray scale. So if you want to convert this image into a gray scale you have to provide this flag cv2 mread grayscale. Let's go ahead and run that. And now we can easily go ahead pltim show and then just pass in my image gray comma cmap set the color map equals to gray. So you have to set the color map as gray in order to display the image in a gray format or a gray mode. You can see now we have a gray scale image. So an image in the fashion of grayscale it has gray colors. Okay. Now let's go ahead and do the next step which is image resize. So it's an important skill of how to resize images. You will see it a lot especially in hugging face models. There are some cases where you need to resize some image in order to meet the predefined criteria or the assumptions of the model. So it's an a really important skill to have. Image resize cv2.resize. So just use the function resize then pass in my image. Then you have to define the size 200 comma 400. For example, set it as 200 comma 400. These are the the dimensions and the dimensions of the of the image. So let's go ahead and just go plt.mshow dot imshow and then pass in into here image resize. You can see it will resize my image using this function resize. Go ahead and run that. And now we have a resized image. You can see here the x-axis. So the width here spans until it reaches 200. So you can see here 200. This corresponds to the x-axis. Here we have from 0 to 200. So here we have 200. And the yaxis spans from zero until it reaches 400. So you can see at 350 it reaches 400. So these are the dimensions. If you change it for example 150 by 150 then it will change into 150 by 150. You can see we have a squared image 150 and here we have 150. Okay feel free to play around and have fun with that with those values. Now let's go ahead. W ratio equals 0.5. Then we have height ratio equals ratio equals 0.5. Here remember when we resized the image into 200 comma 400 the image scaling wasn't equal. You can see the image here is squeezed is squashed it's not in equal dimensions it look like a real image. So in order to have a re in order to resize the image without damaging its scaling without damaging its dimensionality keeping the image uh to be in equal dimensions you have to specify W ratio as 0.5 height ratio 0.5. So the half let's go ahead new image or new image equals cv2 dot resize and then pass into here my image and then comma z uh pass here 0 comma 0. So for the D size then comma FX equals W ratio. So W ratio stands for width ratio comma FY so the Y-axis corresponds to the height ratio H ratio. Then now let's go ahead and just just display my image using the new image. You can see here we have resized our image successfully but keeping the dimensions equal. keeping the dimensions to be in a not damaged way. You can see here we can set a W ratio, height ratio, pass these variables to the parameters f_sub_x, f_sub_y to the resize function. Rather than specifying these dimensions here, we passed here 0 comma 0 and then determine f_sub_x as w ratio, fy as the height ratio. Then we have this image with a neat scaling. You can see it's now 180 by 180. So it halves the image width and height. Then let's go ahead and generate. Now let's dive into the actual generation. So that's enough with how to pre-process images, how to deal with images. You can see here we have done uh plenty of skills of reading the image, converting it into array, then how to get the red channel, green channel, blue channel. And you can see here we have used the library CV2 as an alternative. Then we have convert the the format from blue green red into red green blue. You can see here from blue green red to red green blue. And then you have here you can see the way to to convert it into grayscale. And the last thing here how to resize it with unequal dimensions and with equal dimensions. That's enough with the skills and on how to pre-process images. Let's dive into how to use im uh models diffused models from hugging face to actually generate images by going let's name this generating faces using diffusion models or diffuses diffusion model. So here you can see this task is one of the most tasks in the world of generating images and it's pretty well served. You can see here from diffuses import the DPM pipeline. So DP DDP PM pipeline pipeline. So from diffuses import DDPM pipeline. If you wonder what is DDPM, DDPM is a is a diffusion model and it stands for denoising diffusion probabilistic model. And if you we current here d noising diffusion probabilistic model. Okay, this is a DDBM pipeline. We want to import that pipeline from the diffuse library. Go ahead and import. You can see now it's importing. This model has a paper. If you search here DDPM model paper, this is the model D noising diffusion probabilistic models. And you can go here you can see it's by Jonathan Ho and it all. So here you can see we present high quality image synthesis. So image synthesis is a fancy word for image generation results using diffusion probabilistic models a class of latent variable models inspired by considerations from non-equilibrium thermodynamics. So remember the diffusion model is inspired by the physics science specifically non-equilibrium thermodynamics. So particularly this field has inspired this deep learning model diffusion. Our best results are obtained by training on a weighted variational bound designed according to a novel connection between diffusion probabilistic models and denoising score matching with lang dynamics. And our models naturally admit a progressive lossy decompression scheme that can be interpreted as a transition of auto reggressive decoding on the unconditional cipher 10 data set. We obtain an inception score of 9.46 and a state-of-the-art FID score of 3.17 and you can read that in your own time. So this the paper behind this class. Feel free to read it in your own time. But now let's go ahead and use this class. It's called DDPM pipeline from diffuse library and you can see here the paper is loading where they generated faces. So the actual interest of this paper is to generate faces and we will do the same as they did. We will go we're going to generate faces and you can see here they have so many equations the paper you can see also not faces but also images. So you can see you can see from here these are uh this is the for the forward process where they start with non uh non- noisy image then they slowly add noisy or they start from random noise then the model slowly but gradually den noises that noise until it reaches a point where we have a coherent logical object. We have a forward process and we have also a reverse process. Okay. So now let's go ahead and use that model. You can see here DDPM equals DDPM pipeline then from pre-trained and then pass in Google/ DDPM-sellip ahq-256. Then we have two cuda. So here we have from pre-trained method and then pass in Google. So the provider of this model on hugging face is Google/ denoising diffusion probabilistic model- celib is a data set of faces. Celip ahq256. If you search here and say here data set it's a huge det. It's also provided on tensorflow. You can see tensflow library is providing this data set celip a_hq. So in case you don't know what this is, this is a data set for faces. You can see here high quality version of the cilip a data set consisting of 30,000 images in 1x,024 resolution. And you can see here you can download the image. You can download it from this GitHub uh repository. And you can go down this some code to download and get the data set. And you can see these are faces faces for people. So CLIP is a data set of faces containing tons and tons of human faces. You can see DDPM-sip ahq-256. You can see now it's downloading. So it's trying to load in this model from the hugging face platform. Now let's go ahead and just use this model by going. So you can see here we have this model DDPM. This is the model DDBM pipeline. It's a pipeline. Let's go ahead and just generate an image equals DDPM and then pass in num_inference steps equals 30 dot images at index zero. So all we're doing here is just we are calling the ddpm dn noising diffusion probabilistic model passing in num inference steps equals 30. Then we are stepping into the images property and then getting or retrieving at index zero. Let's run that. You can see it's now trying to generate that image and you can see wa you are going very fast. Why? Because I have here a GPU. Go to runtime change runtime type. You can see here I am using currently L for GPU. So don't be surprised if you are using CPU and you are slow or your model is going slow. Currently I am using GPU. Okay, that's why my model has done that quickly. Now let's go ahead and just show this image. You can see this is a face for a human. Okay. So this is the this is the diffusion model the same as they did in the paper. So remember in the paper here they have generated faces. Okay. Here you can go down or up. Yeah. Here you can see they have a lot of faces. They generated a lot of faces. And one of these faces now is showing up in our collab environment because why? Because we used the model DDPM-sip ahq-256. Now let's go to the next step and go from diffuses import from diffuses import DDPMuler now you can see we have here DDBM scheduleuler comma unit to the model and also we need to import the unit 2D model run that now let's go equals ddpmuler then let's go dot from pre-trained and then pass into this from pre-trained the name of the model by going here you can see passing Google slash DDBM so remember dn noising dn noising diffusion probabilistic model dash celib or ahq-256 just like that we are passing here the name of the model to the method from underscore pre-trained coming from the DDPMuler. Let's run that. Now we have a scheduleuler. We can check it outer. Okay, this is my scheduleuler. You can see it has a bunch of info. Class name, DDBMuler, diffuses version 0.56.0, beta end, betaul, uh beta start, clip sample, clip sample range, and a lot of other properties and attributes. But now let's go ahead and focus on how to use the the model unit by going model equals u net 2D 2D model. So the unit 2D model two-dimensional model dot underscore uh dot from pre-trained. So use from pre-trained and then pass in google ddbm ahq-256.2 cuda. Keep in mind you have to to move this model to the to CUDA to CUDA environment or to CUDA device because otherwise CUDA otherwise this model will live on the CPU and it will take forever generating one one simple image. Okay, run that. Now it's getting my model. We can check out my model and this is my model. These are all the layers. You can see this is the deep learning. You go deep. You you stack deep layers on top of each other. You can see we have here cellu activation function. We have convolution drop out. This is the unit model. Okay. Module list. We have reset block 2D group addition convolution 2D linear group norm drop out convolution. And they replicated these blocks many many times. Okay. You can see here the scroll goes forever. We have so many layers. Okay. Feel free to explore this architecture in your own time. But now let's go ahead and use theuler. scheduler then dot set time steps and then pass 50. So I want to set the time steps as 50 run that now if you check out the scheduleuler dot time steps. So how many time steps do I have here? You can see we have 50 time steps and these are as 980, 960, 940, 920, 900, 80, 880, 860, 840, 820 and so on so forth. Now let's go ahead and import torch. Then let's go sample size. set the sample size variable equals to model dot configuration dot sample size and then show the sample size. So here we have tapped into the configuration of the model dot sample size. Then we have here the variable sample size. You can see we have here 256. Okay, this is the sample size. So all we have done is model.configur configuration model sample size then all of a sudden the sample size is 256. Now let's go ahead add noise equals torch dot rand in rand n and then we have here 1 comma 3 comma sample size. So we are passing the sample size inside the tpple. Here we have a touble the uh one represents the batch size. So how many image here inside this batch only we have one image we have just one image comma then we have here three color channels red green blue comma we are passing the sample size here as a value. Then let's go ahead comma device equals cuda. So now we have a variable called noise and it stores a random torch random tensor. We can show it here. You can go noise. This is my noise. So just noisy numbers, noisy values. Okay. Rand n pass here 1 comma 3 comma sample size. Then device ascoda. Now let's go ahead and create a variable. You can see here we need to duplicate the sample size. Sample size two times. Okay. We have to pass them twice like that. Okay. Because here we have color channels height width. Okay. Now let's go to the next step where input equals noise. Then let's go a for loop for t. So for every single t. So time step for every single time step inuler dot time steps. So loop through the time steps. Then do the following with torch.inference mode. So we need to enable the inference mode. We have to enable and turn on inference mode. And when you enable and turn on the inference mode using PyTorch, then you are basically turning off the back propagation algorithm. You are turning off the gradient tracking in in PyTorch and you are uh you are in the inference mode. Okay, let's go. noisy underscore residual residual equals model and then pass input comma t dot sample and here let's call it noisy noisy residual equals model and then pass input comma t. So the time step that we are looping through in scheduled time steps and remember this time steps is just a tensor with these values. It contains here 50 values. Okay, we have we have 50 different values. They are representing the time steps. We are passing every single time step alongside with the input to the model and the input is what is random noise. So we are taking the random noise passing to the to my model the unit model and providing also the time step here and then taking the sample. Then we have your previous underscore noisy noisy sample equals scheduleuler dot step and then pass into here noisy residual comma t comma input and then dot previous sample. So here we are getting the previous sample the previous step. Then at the last you can see we need to set the input variable input equals previous noisy sample and run that. Now it's running. So now it's looping through the time steps and now it's finished. It's done this kind of steps with torch inference mode. Please enable the inference mode. Then call the model pass in my input. So input is what here my input is just random tensor if you want to show it here you can go dot shape you can see here this my shape let's squeeze it by going squeeze here squeeze function so now we don't have anymore that one dimension now let's permute it to be to be compatible with math lip permute pass one to zero why we need to pass here the height here so height has one put it at the the width put it here. Then the the color channels move it to the last dimension. Now we have a compatible tensor. Let's go dot numpy. Now dot detach first. Here we have dot detach then numpy because we need to detach it and then numpy. You can see dot and then convert it numpy version. device. Yeah, we need to CPU then numpy. Okay, then we need to pass this to plt dot im show. You can see here we have random noisy image. So we are starting from this noisy image. Okay. So the the error here was you are uh we were converting this tensor which is living on the CUDA device. We were converting it to numpy. If you see here, this is a pytor torch tensor. And then once you convert once you turn it into numpy, okay, by going numpy, it gives you a huge error saying that hey, you are sorting that tensa on CUDA can't convert CUDA device to numpy because numpy lives on the CPU. Numpy always always works and deals with arrays stored in the CPU. So use here they gives they give you a hint please use tensor CPU or two CPU you can see now you can go ahead and CPU okay you can see now we are moving our uh tensor CPU then we can go dot CPU okay it turns it into CPU then we can go numpy and it returns a numpy version of it then we can pass that to our uh plt.m show function and it will show random noise image. So you can see here we have random random noisy pixels. So nothing nothing to infer from this image just random pixels and every time you run that you get random shuffle of the pixels. Okay, we are starting from this noise and then passing the t which is the the the time step alongside this input noise input and then getting the previous sample. Then we are taking this previous noise sample and assigning it to the input variable. Okay, let's go now from pil. So let's go ahead and we have another another idea of showing a distribution or another concept of showing an a the distribution of this array. So all you need to do is go ahead and copy this array. Then just show its distribution by going here. You can see we have this numpy array. It contains all these dimensions. We can go do flatten flatten it. You can see we have now one dimension because the histogram just deals with one dimension. Then we can go and plt dot hist to show a histogram. Here if we put semicolon you can see we have a nice little amazing histogram and it's showing this histogram. You can see it's like Gaussian distribution. Okay, it's like the normal distribution. So this is noise image and it is representing Gaussian distribution. Okay, so random Gaussian distribution. If you search here Gaussian distribution images, it's like that. You can see we have this like of shape the same as here. Okay. So let's go ahead and input or from pil import image the image class then let's go import numpy as np you don't have to but let's recreate it then you can then we can go image equals input divided by two plus 0.5 so we are dividing our image by two then we are adding 0.5 dot clamp and then also need to call the clamp function pass in 0 comma 1 then dots squeeze. So you can see here we are again squeezing our image. Why? To get rid of that batch dimension. Then we have here image equals image dot permute. So we can see permute we are again permuting and reordering the the order of the height width dimensions by going 1 2 0 time 255 dot round. Then we are rounding here two. Then we are moving to the torch dot torch dot u integer 8 dot CPU you can see and then numpy. Then we can go image equals image dot from array and then pass in my image. And here we have my image. So this is the image of the face. As you can see, we need to run this again. You can see here. Let's let's write another face image. Then another face. Then we can go down and use this code again. You can see this for loop and then from p import image then divide the image. Okay, you can see this face. Okay. So because we have overwritten over the variable image using this you can see using this code. Okay. So in order to get this image you have to rerun the codes above. Okay. So you can see here image it's showing this image. And if you run again we have the same image but here we have done it using auler from the library diffuses. So you can see here from diffuses we have imported the scheduleuler function DDPMuler and unit 2D model unit 2D model. So we've done here manually instead of this doing it automatically here we have done it manually using a for loop we started from this random noise used a for loop as a loop across the time steps here. So we are looking here through this time steps and then slowly but gradually den noising that that noise and recrafting this image. You can see we have crafted this image from scratch from pure noise. So we have we had pure noise then we turned it into this face humanlike face by doing this code. We use the unit 2D model. You can see here this model is representing the unit 2D model. Then we pass input comma t. Okay. Now let's go to the last task which is generating generating images using a prompt a prompt with diffusion. So this task is one of my favorite tasks because we are we're going to generate images using a prompt with diffusion models or using diffusion models. So here remember we need to import torch then we have to go to from diffusers from diffusers import diffusion pipeline pipeline. So we need to import diffusion pipeline from within the diffuser library. Let's go ahead and uh set a pipe here. So pipe equals you can name it whatever you want. I will name it I will name it as image generator equals diffusion pipeline and then dot from pre-trained then we have to pass in here the model of the stability I so if you go to hugging face here hugging face we can go to models tab then go to tasks then choose the task which is converting text to image text to image you can see we have it here computer vision It's under cubit vision which is text to image. Choose that. Here you can see the first if you choose or if you sort the models based on most downloads. Here we have the stability AI stability AI/stable diffusion-xl 1.0. The same model that we want to use. If you go to use this model and then diffuse this. You can see you have a plethora of images here. Let's copy this code. You can see the same code. import torch from diffuses import diffusion pipeline. Then we have here some diffusion pipeline from pre-trained and then pass in stability aai/stable-defusion-xl. So xar-base-1 then the d type here is torchbe float 16 device map equals cuda. Then here we have some prompt aster in a jungle cold color palette muted colors detailed 8k let's copy that code and then go here. So rather than writing this code you can easily paste that code here. So feel free to paste it here and then run that again. You can see now it's trying to download that im that model and it's now generating the image which is astronaut in a jungle. You can see here we have astronaut in a jungle cold color palette muted muted colors detailed 8K. So here in this model card you can see they have SD XL base model card. You can scroll down here. We have the model architecture. We provide a prompt. So add the prompt here. Then we have some base architecture. Then we have some latent space. Then we have a refiner. So there's an internal refiner that refineses your prompt. So your prompt doesn't get inputed the same as your prompt. There is some refiner text refiner that refineses your prompt or or your instructions. Then we have some image of the size 1 to4 by 1 to4. So here you can see uh model description developed by stability AI model type diffusion based textto image generative model license. This is license model description. This is a model that can be used to generate and modify images based on text prompts. So based on a text prompt, you can generate a model. It's a latent diffusion model that uses two fixed pre-trained text encoders. And here if you go to polo cup polo cup diffusion model it's a an explanation for stable diffusion. So you can see here diffusion. If you go to outside here you can see it's called stable diffusion explained with visualization. If you go here you can see first we have some prompt a cute and adorable bunny with huge clear eyes holding a bunch of flowers in the style of cute Pixar character. So then we have some text representation generator. If you open this here we have a tokenizer. So first your text gets tokenized and as you know tokenization is the process of segmenting breaking down or breaking down your text into several tokens and every single token represents a single chunk. So it's the process of chunkifying your text. Then we have here 77 tokens. Start token that triggers and motivates the model. Then we have a cute cute is a single token and is a token. You can see adorable is a single token. Bunny is a token with huge clear. Then we have some text encoder. The text encoder here as you can see we have image encoder and a text encoder. So you can see photo of white dog you have image encoder text encoder. It tries to understand the text and then tries to generate an image. Okay. So you can see stable diffusion uses a special text encoder that connects text with image for an image caption pair. The text encoder converts the captions tokens into a vector that is close to the images vector produced by a pad image encoder not used in simple diffusion in hybrid text image space. Then after that these tokens gets mapped into a vector for each token. So these tokens are mapped to ids. Then for every single ID we map it we map it into a vector into a vector. So you can see vector for each token start has its own vector a has its own vector and every single vector has some numerical values 0.03 minus 1.33 0.31 and so on. So for every single token we have a single vector and these vectors contains numerical values. After that after the text representation data has finished here we can say we can see we have the image representation refiner so we have the unit so we have the same archition that we used earlier which is the unit model the unit is a convolution network you can see predicts noise you can see here this is the unit here image representation it starts with random noise then it does several steps several many many steps you can see 8 9 20 27 20 30 until it gets to the coherent last image. Okay, until the clear image. And here after this image refiner, we have the upscale. You can see here we have this time step. We can go to one. You can see here we start with random noise. We start with pure noise and then slowly but gradually the diffusion model dinoises it denoise it and gets rid of the of the noise until it creates this really clear clear image. It's a very clear image. Okay. So this is the process of diffusion. Diffusion is one of the greatest ideas in the world of deep learning. It starts with random noise and then slowly it tries to remove that noise. It tries to delete that noise to get rid of it and then slowly build coherent objects like eyes, like hair, like airs and then it shows us this nice really appealing image which is an adorable bunny. Okay. So now the model has finished. You can we can visualize the image by going image. You can see here it's an astrand in a jungle with cold colors muted 8K and detailed you can see we have this astrand in a jungle. Okay. This is the the the image from the stability AI stable division and that is how to generate images using stability AI diffusion model. So that is how easy you can see it's really easy how to use a model from hugging face. All we've done actually is just we've gone to from diffuses import diffusion pipeline class dot from pre-trained method and then pass in stability AI/stable diffusion xl base then just created and crafted some prompt and then pass that prompt into a pipe dot images at index zero. So let's go to sub AI or to the expression here we can see section the prompt we can actually copy this prompt and then go to here. So all we've done is prompt prompt equals this prompt a cute and adorable bunny with huge clear eyes holding a bunch of flowers in the style of cute Pixar character. Then we have here image equals pipe and then pass my prompt into here inside the pipe dot images at index zero. Then we have here image. So all we are doing here is just crafting some prompt passing it to my pipe and then images. Then we are here you can see we are generating the image. Okay. Now behind the scenes it's starting with random noise. Then slowly it's trying to remove that noise and trying to draw that image, trying to print to paint that image for us, which is a cute and adorable bunny. So if you go to here, you can see this is the resulted image in the polar club tool. Let's compare it to what will be outputed in our collab environment using this model SAI. And if you choose another prompt here, for example, a very very very beautiful titcape, you can see run that again. It starts here from random noise. Then slowly it's trying to remove that noise and shows a really clear city. You can see here we have the cityscape. Okay. And if you select another prompt for example a a for example here you can go to a cute and lovely 4year-old baby. You can see this is the clear image the end. Then if you time if we play the time steps you can see now it's trying to add some noise. You can see starting with noise then slowly denoising it until it creates that logically coherent and logically and appealing image. Now if you go to here you can see here we have an adorable bunny image. You can see we have this rabbit. Okay using that prompt a cute and adorable bunny with huge clear eyes. So you can see it he he it has huge clear eyes holding a bunch of flowers. So it's holding here you can see a bunch of flowers orange flowers. Then we have here in the style of cute Pixar character and it's in the format of Pixar character. If you know a Pixar character this is one of the this is one of the Pixar characters. Then let's go and copy that prompt here which is a cute and lovely 40year-old baby and paste it over here. We have here prompt paste it over here. Then just all all you have to do is to go ahead and image equals pipe. So go the pipe and then pass into here images or prompt pass the prompt dot images then access index zero then actually show the image. So if you know the TV static TV static images it's the same as the random noise. It's starting from random noise and then slowly getting rid of that noise and painting or drawing the image that you ask here. And this model is considered a a conditioned latent division model because why? Because it's conditioned upon our text prompt. You instruct it and it's conditioned based on the prompt. So if you go to here to the polo club tool and you can see here what is a stable diffusion model. Stable diffusion is a text to image. So it's a model that converts text to image model that transforms a text prompt into a high resolution image. For example, if you type a cute and adorable bunny, stable diffusion generates high resolution images depicting that a cute and adorable bunny in a few seconds. Click select on the prompt here to change it. And there they have discussed how it works. Stable diffusion first changes the text prompt into a text representation. As we said, it first tokenizes our prompt. So here this prompt is first gets tokenized. Then every single word gets mapped into a vector. Then it tries to understand that vector semantically and contextually. Then it tries to generate an image. You can see here image. This is an image of a cute girl for and cute girl. Okay, as we asked in the prompt and the last here we have a prompt. Let's try a prompt that we write here which is a giraffe a giraffe with top hat and then pass this prompt into my pipe the model by going model and then pass in my prompt then dot images at index zero. Then let's show that image and here we have called it pipe. Okay. So image equals pipe pass in my prompt do images at index zero then show that image. We can go ahead and run that. Now it's trying to generate or trying to produce a giraffe with top hat. So as we said here you can see in the polo club tool they have said that they have a tokenizer. So first this prompt gets tokenized. So for example like that a giraffe is a single token with is the token and then every single token gets mapped into a vector like this 0.5 0.3 0.2 and then this vector represents the contextual meaning the semantic meaning the spelling and so many different perspectives about this word. Then we pass it into a text encoder. Then it understands the meaning of this text and pass this rich representation vectors with its understanding to an image encoder. Then the image encoder will take this and understand it and tries to direct the image using a diffusion model. So the main idea here you can see we have text representation. Stable diffusion converts a text prompt into a text vector representation. Then image representation starting with random noise. Stable diffusion refineses the image representation little by little with the guidance of the text representation. Stable diffusion repeats the refining over multiple time steps. For example, 50 in our diffusion explainer. Then we have image upscaling. Stable diffusion upscales the image representation into a high resolution image. And feel free to read through that in your own time. But this is the main idea of the diffusion. And you can see here we have this image of a giraffe. You can see with top hat. Okay. Okay. So that's it. That's how to use diffusion models in hugging face diffuses models and how to generate images with a prompt using a text prompt and also how to generate faces without impromptising diffusion probabilistic models and we have taught some skills on how to process images using the Python programming language ecosystem. Let's dive into another modality and section of this course which is video models and how to use video models from hugging face platform. The first thing is let's go and name this as video models. Let's import the the required libraries that for example torch import diffuses. The diffusers library is a really important library in the world of video and images. Whenever you want to deal with video modality or video files or to generate videos using deep learning, you have to import the diffusers library from hugging face. Then let's go import transformers and then at the last import. Now let's run that. You can see now it's importing those libraries including torch, diffusers, transformers and CV2. The next step is that let's go ahead and name this as generating start new section as generating video with diffusion. So now let's take how would you generate a video using a diffusion model diffusion model from hugging face. The first thing let's go from diffusers import stable video stable video diffusion pipeline. So here we have this class. You can see it's called stable video diffusion pipeline. Let's import this class from the diffuses library. You can see now it's importing this class. And let's wait until the class is imported. You can see now the class is imported. The third step, let's go ahead and dive into it. Let's construct a new instance from this class by going pipe equals and then let's call that class which is called stable diffusion or stable video diffusion pipeline. Let's use that class and then pass into here. You can see dot from pre-trained. Let's call the method from pre-trained and then pass stability AI slash stable dash video diffusion dash image to vit. So vit is short for video xt. So you can see here this is the name of the model. Then let's set the torch type. So the data type of the torch should be as torch dot float 16. So why you have to set this parameter? If you don't set this par parameter, you will get the error out of memory because remember or keep in mind videos are really large files and generating them isn't easy. So you have to change the precision of the numbers to be float 16. Okay, this a really really really important setting you have to care about and you have to provide it otherwise you will get out of memory error variant equals FP16 so short for a floating point 16 and here keep in mind you have to write stability AI/Stable video diffusion stable- video diffusion- image tovide-xt then let's go ahead and load this pipe Let's run that. You can see now it's trying to load in our model. You can see the model is now loading model and index of JSON. It's now trying to download that model. So all we did is just call this class stable video diffusion and pipeline dot from pre-trained and then pass in the name of the model, torch dype as float 16 and then set the variant setting as FP16. Okay, like that. And then we have the model here or the pipe. Let's now go the pipe to see it. Now this is the pipe. You can see here we have this stable video diffusion pipeline. We have class name stable video diffusion pipeline. Diffuses version 0.36.0 name or path stability AI/stable video diffusion- image to video-ext feature extractor transformers clip image processor and so on. Now let's go ahead and you can see here I have an image. I already have an image here called Elmo.jbg. If you open it, you can see this is an image of Elmo. Let's let's take the copy of this image and paste it inside the variable called my image or for example path equals Elmo.jpg. So this is the path. This is the path of Elmo.jpg image stored inside a variable called path. Run that. You can see a path is a string a normal string a regular string containing the word elmo.jpg jpg. Now to show this image let's go ahead and from diffuses diffusers dot utils. So inside the utils library or utils package which is short for utilities import the following. The first is load underscore image. So this function is really really helpful. It's from the utilities library from within diffusers. It helps you to load the image and show it. Then comma we have this also function export to video to later export our video frames into a video. Okay. So let's from diffusers dot utils import load image, export video and let's go ahead and image equals. So here we have a path. Remember we sort the path of the image inside a variable called path. Let's use this function load image and pass into here the path of the Elmo image. Now once you write here the name of the variable image, we have a surprise. The Elmo image is loaded into the environment of Google Collab of Google Collab. You can see we have Elmo image loaded inside the collab environment successfully without any problems. So the idea here all we have done is from diffuses utils import load image comma export video then we pass the path to load image and we showed that image successfully. Here you can see we have an important setting that we have to do which is pipe dot enabled_model CPU offload. This is a really important setting that you have to use this function enable model CPU offload. You have to call this function on top of pipe. Why? Because to not get the error of out of memory as you can see. So keep in mind you have to run this code. This code is necessary. Then let's go ahead and dive straight away into how to use this model. First let's set a generator equals torch dot manual seed to set a manual seed to get reproducible results. So in order to get reproducible results, the same results, you and I have the same results, the same video frames, you should have to set u manual seed as 42. So now we have a generator generator. You can see it's a normal uh torch manual seed function set as 42. So feel free to play around this value. You can set it whatever you want, but in this case I will keep it as the regular normal seed 42. Now let's dive into the step of of creating the actual frames by going frames equals pipe. So remember we have created this pipe earlier. You can see here pipe at the top here we have here pipe equals the class that we have imported earlier stable video diffusion pipeline dot the method from pre-trained and then pass here the information about the model. Now let's use this pipe and pass in my image and then the model will work and produce a video and generate a video out of this image by going image. So pass my Elmo image. Here we have image. You can see it's an it's an Elmo image. Let's pass it to our pipe. Then comma decode trunk size equals 8. So set the decode chunk size as eight. This is a really important parameter. You have to set it set it as eight comma generator and then pass in my generator which is if you remember our seed okay dot frames at index zero. Why? Because this class will return a a kind of object. You have to access the attribute frames and get the frames at the index zero. So this is a really important chunk or really important piece that you have to provide in order to get the frames straight away. Let's go ahead and run that. You can see now it's trying to generate a actual an actual video out of this image which is Elmo image. Now the model is working. You have to keep in mind I got I went to runtime change runtime type and then chose L4GPU. Otherwise, if you are working on CPU, it will take at least 40 minutes to generate a video. So, keep in mind you have to rent GPUs. You have to buy GPS from Google Collab and then use L4 GPU or A100 GPU or whatever GPU you have available. The the more powerful GPU, for example, L4, A100 will take less than 1 minute to generate a video. But otherwise, if you are using CPU, keep in mind it might it might take at least 40 minutes. You can see here we have little nice progress bar showing us the progress of this model. Now this pipe is running behind the scenes running behind the scenes a diffusion model. The diffusion model is the model that is responsible for generating pixels and generating the video frames from this image. So here only we are providing the image. We are not providing a prompt. Later in this lecture we will see that we will use another model from hugging face. Then we will provide an image alongside with a prompt. Then the model will be able to generate a video. But here this model which is the default model here that we have used which is called stable video diffusion pipeline. We have imported it from this library from diffuses import stable video diffusion pipeline. This model is generating a video out of a single image. We are not providing any prompt. And if you go to here and search stable video diffusion paper, this is the the real paper or the actual paper that introduced and proposed this model from stability AI. You can see stable video diffusion scaling latent video diffusion models to large on nove on 25th November 2023. And if you go to VPDF, it will show us that here we have stability AI. This is the the paper that they proposed this model stable video diffusion and feel free in your own time to read this paper at your own pace. But here in the abstract they said we present stable video diffusion a latent video diffusion model for high resolution state-of-the-art text to video and image to video. Here we are using this modality image to video. We are using this paradigm converting an image into a video but also you can use text to video. So you provide a text prompt then it converted into a video. Recently latent diffusion models trained for 2D images synthesis have been turned into generative video models by inserting temporal layers and fine-tuning them on small highquality video data sets. However, training methods in literature vary widely and the field has yet to agree on a unified strategy for for for curating video data. And if you go down, you can see they generated so many images and so many you can see here we have so many images and so many videos. These are video frames. So one frame, one second frame, third frame, fourth frame. So this is a video. Okay, you can see they provide one image and then the model tries to manipulate that image and create many many many frames. Here the model has finished. You can go and show the frames. You can see here we have a nice list whoa containing so many images and every single image is in the form of pill. And if you don't know pill, pill is short for python image library or python imaging library. So if you wanted to access one of these images, you can go at index zero. Then it shows us that image. You can see this is the first of this is the first image of Elmo. This is the second image of Elmo. This is the third at index two. The fourth image. You can see Elmo is going down. Every time Elmo is going down. Okay. And these are the frames. So feel free to play around with these images. Here you have a nice list containing of if you take the length of it here we have how many frames do we have? We have 25 frames. We have 25 images different images inside this list and every string image represents a single scene represents a single frame. Now let's go ahead and export it by going export to video. Remember from the utilities library or from the utilities package we imported here a function called export to video that will help us to export these frames into a combined video. It will combine these images into one video file and store it in your collab environment. Then you will be able to download it and visualize it. So let's use that function. Export to video. Then just pass in the frames. Pass in the list. this list this great list of frames pass it into this function frames then we will you have to name this video I will name it as Elmo Elmo do mp4 elmompp4 then all we have to do is just set the fps equ= 7 so here frames per second this parameter is short for frames per second so how many frames do you want to show per second I want to show seven frames per a second. Okay. Now let's open this section and 3 2 1 run the cell. And you can see here when we refresh we will get a video. You can see it's called Elmo.mpp4. Now let's click that video. Double click it will download that video automatically. You can see it takes a little bit of time but no worries it will download that in any time. Now let's click on that video. You can see this is a video of El of Elmo jumping up and down. You can see Elmo now is a video. Elmo isn't anymore one single image. It's now a moving video jumping up and down. Okay. So, feel free to grab any image to to fetch any image of your of yours and try to pass it to this model. It's called stable video diffusion. And you can see how easy it is to use it just in four lines of code or five lines of code. You have the ability to use a deep learning model to convert one image into a video. As they mentioned here, it's easy to convert one image to a video or the second modality text to a video. So you can see here we have here two options text to video or image to video. Now we have used this paradigm image to video. We provide it with one single image. with one single image which is this Elmo image a static Elmo. Then we convert it into a video using this pipe our model. Pass in the image decode chunk size as eight and then set generator as generator to get reproducible results. Then get the frames add index zero. Then all of a sudden all the surprise you have a massive list of all those images. Then we tried to export it to a video and it did that. And then we have a video here called LMP MP4. Now let's go to hugging face here. You can go to tasks or models tasks. Then we have here multimodel. We have here computer vision. We have NLB and we have audio. Let's go to here to multimodel. You have the option to convert image to a text. So image text to it's called image text to video or let's call it image to video. Yeah. Yes. This is the option that I want to point out. Image to video like we did here. We have a plethora of models. You can see we have so many models. We have mountains of models. You can see 4484 models. A big number. Uh the first model is by Quark Vision Live Avatar. Uh updated 7 days ago. You can see it has 151 likes. Here we have also stability AI stable video diffusion model image to video. And I believe if you go to saw and then choose most downloads here the most or most likes most likes here stability AI stability video diffusion is the most model that has the the most amount of likes. So if you sort by most likes here the first model is the model that we have used previously stability AI/stable video diffusion image video and if you click on it these are the images that they have made. You can see these are some videos. If you grab some earth earth image and pass to the model it will round that earth make it moving. The same with the with the clouds and the sea. You can see we will try with the sea. We will try to pass an image of C and it will animate the sea and make the waves animating and there we have we have these buildings. So feel free to play around with these models to explore explore explore experiment experiment experiment. Here we have use this model diffuses. So you can remember that previously when we clicked on use this model it was here transformers. It was pointing out to transforms. But now once we got into the models of video, hugging face automatically changes this option to diffuses. And you can see we have here we have diffuses library. If you click on it, it will show us a model. Then here is the uh the guide on how to use this model. First from diffusers import diffusion pipeline. Then diffusion pipeline. From pre-trained pass in here stability AI/Stable diffusion. Then we have here a prompt. A man with short gray hair plays a red electric guitar. Then we have this image. So they provided here with prompt and image. Then the pipeline will work and produce output a MP4 video. Now let's get back to our notebook and complete our lesson. Let's jump into another topic here which is generating video using another diffusion diffusion model. This time using image and prompt. So not only an image but also a prompt. Provide the the model with the image and prompt by going import torch. Then let's go torch.cuda CUDA dot empty cache. Then let's call that function. You can see here we have empty the cache. So you have to empty the cache or empty the cache before you move on to the next step. Why? Because torch. CUDA empty cache makes sure that our our CUDA isn't busy with any other task. Let's go from diffusers from diffusers import a function or a class called I2 to V gen XL pipeline. So what basically this class is short for I image to video. So converting image to video generator or generation Xlarge model pipeline. We need to import this class from the diffuses library. So from diffusers import I2V gen XL pipeline. Then let's go ahead and here you can see from diffusers from diffusers import dot utils. So from the utility functions or from the utility library please go ahead and import the following. Load image, export video. And here you can see oh we used this function before. Load image is used to load an image. Export video is used to let us export a video. So we've seen that before. Then we have uh to create a pipeline. Pipeline equals diff I. So image to video generator XL pipeline. So I I2V generator XL pipeline. Then let's go ahead and pass into here dot from pre-trained. We have to provide into here the repo ID. So this time let's store it in a variable called repo id equals ali dash vl vl / i2v it's its meaning is image to video generation or generator dash xl xar this is my repo ID so a li-v i l/ i2 video generator - XL then let's pass here the ripple id. So instead of manually writing the ripple ID here what if we store it in a variable and use that variable it will make your code a lot neater. Then you have here torch dt type equals torch.flat6. Please keep in mind you have to set it like that otherwise you will get a out of memory error because as we told you we are dealing with video data video modality which is a really massive or intensive computing modality. When you compute on images on videos on audio the model will be heavy in computing will be in compute computationally intensive. So you have to lower down the precision to be float 16. If you use float 32, you will be out of memory. So we have keep keep in mind make sure you are using float 16. Then let's go ahead and set the variant equals to FP16 floating point 16. Now let's run that. You can see now it's trying to download in the model to load the model in which is this model I2V generator XL pipeline from pre-trained. So as you can see the progress bars are going are moving forwardly. Then let's go ahead and set the pipeline. So by by by going pipeline dot enable underscore model cpu offload. This function is really is really important because it will make sure that we not that we are not getting the out of memory error. You have to enable model CPU offload. Then let's go ahead and here I have you can see an image of C. If you open it, you can see we have now another image which is a view of a C or an image or a picture of C. Let's now use this picture to generate a video using another model which is this model from the repo ID. This it's called I2V gen XL pipeline by going ahead and loading the model as we did before. Here we can we can go C equals load image and then pass in my C.jpg. So all you have to do is just grab an image, store it over here, call the path of this image, pass it to this function, load underscore image, then you have to store it inside some variable. I called it C. If you now visualize or print out the C variable, it will show us that we have now a picture or a view or a scene of a C. You can see we have this image of a C, normal image. It's a static image. Note that when we pass it to a model, it will animate that C. It will make this C be animated, moving. It's not static anymore. So by going prompt equals the sea for example and uh you can be as as creative as you want. So the sea waves heavily. I will keep it simple here. You can feel free to prompt and to to ask or to instruct the model as you would like. Here I just told the model, hey take this image and try to make the sea waves heavily. You can get as creative as you would like here. But now let's go ahead and just set the generator equals torch dot manual seed as 42. Then frames. So get back the frames. This pipe will return back a frames a set of frames stored inside the form of a list by going pipeline and then pass in prompt equals the prompt equals prompt, image= c, comm, num frames. So, how many frames do you want to generate? In this case, I want to generate 16 frames. Keep in mind, the higher the number, the more time it will take to produce that video. And the lower the number of frames, the faster the model will run to generate your video. So, you have to keep it balanced. But if you have infinite amount of resource, if you have infinite amount of computing, feel free to set it as to for example 164. But let's keep it simple and quick by setting this to 16. Then we have here generator equals generator dot frames and then get or fetch the frames at index zero. So you don't have then to access it later. Here we are accessing straight away dot frames fetch at index zero. Now let the model run. So by the way this model which is called I2V gen XL pipeline if you copy this name go to hugging face this is the stability AI model don't forget go to models and then filter by name you can see we have this model I2V image to video it's it's called this ripple you can copy the name of the ripple from Yeah, you can see this is the model. Okay. So this is the model V gen. It's called it's from Ali Alibaba company-VAB/I2 imagetovideo generator-XL. You can copy the name from here. If you don't want to type it later, you can give it a like if you want. You can follow this account. Here you can see downloads last month. They have 2,729 downloads in the last month. Here you can see VGEN is an open- source video census codebase developed by Tongi lab of Alibaba group featuring the state-of-the-art video generative models. This repository includes implementations of the following methods and you can read through that in your own time. But here the most important idea is if you go down they have here some guides on how to use this model. You can see from diffuses import I2V gen XL pipeline. So that's what what we did before and then you can provide it with image URL you can provide this model with a you can see image then prompt papers were floating in the air on a table in the library then they provide the image they supply the model with image and prompt then they pass it as we did you can see frames so this pipeline returns frames they pass here prompt equals prompt so as we did here you can see if you go down scroll down here we have prompt equals prompt image equals C and they passed it like that. Image equals image generator equals generator then dot frames at index zero. You can see here they did what we did exactly. We have here dot frames and then they accessed at index zero. Then at the last they export this uh frames into a GIF. In this case we will export it into a video and then they passed straight away the frames. Okay. So you have here a plenty of explanations on how to use this model, how to use it. Okay. And this and this is the result. You can see papers. They ask the model to generate papers were floating in the air. So here you can see the papers are floating in the air. And also this uh prompt is really important on a table. You can see here on a table. So they have a table. So you can see how how great this model is at capturing the meaning and the contextual meaning of the prompt. understanding the latent of the text and then combining that understanding with a visual understanding of the image and then using a diffusion model they generated this great masterpiece of art. Okay. So feel free to go as creative as as you would like. Now the diffusion model the first paper that introduced it was by Josh which is titled deep unsupervised learning using non-equilibrium thermodynamics. This is the original paper that introduced the model diffusion by Josha S Dixon. You can see a central problem in machine learning involves modeling complex dead sets using highly flexible families of probability distributions in which learning sampling. Sampling is another word or is a fancy word for generating inference and evaluation are still analytically or computationally tractable. Here we develop an approach that simultaneously achieves both flexibility and tractability. So all the models like VAE GANs and Bosma machines they are all generative models but they are intractable. But diffusion is a model that is both tractable and flexible capable of modeling complex probability distributions and at the same time it's yet tractable. The essential data inspired by non-equilibrium statistical physics is to is to systematically and slowly destroy structure in a distribution. So so the way the diffusion model operates is it it starts with a with a random noise. It starts with an initial random noise. Then it slowly slowly uh uh during the training phase it starts with a the original image. Then it tries to destroy that structure in the image. Then at the inference time it starts from random noise. Then it tries to generate this image. For example, a coherent and logically inspiring and logically appealing image. So it starts with random structure. It destroys structure in a data distribution through an iterative forward diffusion process. We then learn a reverse diffusion process that restores structure in data. So as I told you during the training phase, the diffusion model starts with a logically coherent image. Then it slowly adds noise adds noise until it destroys structure in the image. Once the image is destroyed, there's no any meaningful logical coherence or there's nothing to infer from it. the diffusion model starts to redraw that image or to get how to reverse how to do a reverse diffusion uh process to get to the original image. Then during the inference mode, the the the model is asked with a prompt to generate a new image or a specified image and it starts from random noise then it tries to generate that image and as we saw here with the Elmo video we give it an image then it tried to move and animate Elmo image. So this these are all diffusion models and evaluate probabilities in deep joint models with thousands of layers on or time steps as well as to compute conditional and posterior probabilities under the land model. We additionally release an open-source reference implementation of the algorithm and later there's a paper by Yang diffusion paper you can see by Yangsung the principles of diffusion model. So if we go to yeah this is Yangsung here we have scorebased. So Yangong here what he did in this paper with his friends they avoided modeling the pro distribution by computing a score based generative modeling through stocastic differential equations. So in this paper which is was in 2021 they avoided modeling the complex probability distribution. So it is it was submitted on 26th November 2022 uh 2020 and last revised 10 Febru uh 10 February 2021. They here in this paper they proposed a way to avoid modeling complex complex and in highdimensional probability distributions via using a scorebased generative modeling through stocastic differential equations. So you can see they have this we present a stocastic differential equation SDE that smoothly transforms a complex data distribution to a known prime distribution by slowly injecting noise. So you can see here by slowly injecting noise. The the deficient model operates by injecting noise and destroying that image structure, then slowly getting back and returning back, learning how to return back to this to to the image and a corresponding reverse time SDE that transforms the prior distribution back into this distribution by slowly removing the noise. Crucially, the reverse time SDE depends only on the time dependent gradient field aka score. So they named it as score of the of the perturbed data distribution by leveraging advances in score-based data modeling. We can accurately estimate these scores with neural networks and use numerical SDE solvers to generate samples. We showed that this network or this framework encapsulates previous approaches in score-based generative modeling and diffusion proistic modeling allowing for new sampling procedures and new modeling capabilities. So feel free to read that in your own time. Here just we are uh giving an introduction to diffusion model and what is the core band diffusion. So the core idea is that diffusion model is a is a genative model mostly used to generate videos and images. It starts with random noise and slowly building structure and coherence and coherent meaning in the image or in the pixels by reordering the pixels by shuffling the pixels around. Okay, you can see it has heavy math. Then you can you can go down you can see the fields. These are these are the gradient fields that the score you can see overview of score-based generative modeling through SDS. And if you scroll down you can see here they generated some faces using a diffusion model. Now let's get back to our collab. You can see now the model has finished uh generating. Now we have here frames. These are the frames stored inside the list. And if you wonder what is the length of this of the frames, we have 16 frames, 16 scenes, 16 images as we have specified over here. So feel free to play around and it's fun to play around with these values to play around with the number of frames. Here the number is 16. The same as we did here. Now let's go ahead and export it by going export to video and then pass in my frames, C name it whatever you would like. I will name it as C waves_mpp4. Then let's go frames per second equals 4. So I want to show four frames per second. Here you can see cwaves.mpp4. Let's go ahead and download that video. You can see it's a video.mpp4. And these are the frames. You can see now the C is moving. It's now animating that image. It's now it's no more it's no longer a single image. It's now a an a a an animating video animation. And you can play around this value. FPS make it as eight. You can see now we will visualize eight frames per second. And then download that video again. You can see it will show us eight frames per second. Okay. Now it's showing us eight frames per second. So here we have reached the end of the video models. You can see we have used both modalities using an image or a single image to generate a video and also how to instruct a model via a prompt plus an image to generate a video. Keep in mind hugging face has a plethora of models. You can go to models then tasks then choose here the task image to you can see here we have image to video and also we have here text to video as we did here we have 6 863 models dedicated to the field of text to video for example 10 cent huan video it has here a way on how and on how to use this model and here we have the they have the model card okay so Feel free to play around with any of these models in your own time. But now we have taught you the way on how to use video models from hugging face. See you in the next section. Now in this section, let's dive into Gradio. Gradio library allows you to create graphical user interfaces for your machine learning models. So enables you to create GUIs for your models. You don't have to worry how to create the front end web development only you need to just to create a model wrap it inside a function then pass that function into gradio library and it will do all the job for you and create a nice front end interface for you. The first thing is let's name this as gradio or gradio and then import it. Import gradio as G. Then import torch. Import numpy as np. And then from pil from python image library import image. Then if you need to check the gradio version, you can go that you can go with that import gradio and then tab into gradio dot version underscore underscore. So we can go gradio and dot version and it will retrieve the version of gradio and currently at the time of recording this video it's 550.0. zero. Maybe in the future you will see a higher number here but it will work for you as we do here. So the first thing let's go and deal with gradial numbers. So how to deal with gradual numbers? How do you create a number field or a number input in gradio? We have to create a function define called add underscore numbers and then pass in x comma y. Then all this function does is just return x + y. So this function is a really simple function. It's take it takes here x comma y. It takes two parameters then it adds these parameters and returns them. So return x + y. And if you call this function add underscore numbers and then pass 10, 20, it will add these two numbers and return 30. And if you pass here 50, 20, it will add them. So 50 + 20, we will have 70. Okay, so it's a really simple function. Now let's create a gradial interface by wrapping this function inside the interface class. So all you have to do is just define a variable iface or interface. Let's call it interface equals gradio.inface. Then we call the class interface. So you can see here we have the class interface. This is the most common class that you will use inside the gradual library. It's the main class, the major class interface. It takes from you three parameters. Fn short for function. And as you can see the function is add numbers add numbers, let's pass in some inputs equals a list. Here you can see we have two inputs. So if you have multiple inputs you have to pass them inside a list and then inside this list let's define grado dot number grado dot number. So this function takes from me two inputs x and y and we have to provide two input fields. This is x and this is y. Then comma let's pass in outputs equals gradio dot number. And this function also returns a number. So the addition of x + y will be also here a number. So we have to return that as in the form of a number using the class number. You can see here n is capital number from the gradio library. Now the the last step is interface. We have to launch it. So call the method launch to launch this interface and to have it ready. Now let's run that. You can see now it's preparing a gradio interface. And it will show us these inputs. You can see we have now x. We can type here whatever number you want. For example, five. 5 + 10. Submit. It will return here 15. And if you type here, for example, x as 10, y as 30, 10 + 30, it will be 40. Okay? Feel free to try whatever numbers you would like. Here we have it looks like you are running gradial on a hosted Jupiter notebook which requires share equals true. If you are running this code on a local Jupyter notebook it will not give you this warning or this kind of information. But if you are running it on collab then you have to provide here the parameter share share equals true then it will disappear. This info will will disappear. Okay. So you can see three two one run that this notification will disappear. You can see now it disappear. Here we have another kind of info collab notebook detected. So now it detects that we are using collab to show errors. If you want if you want to show errors if you have some errors here and you want to debug those errors set debug equals true. But in this case we don't have any errors. So this is a little notification. Okay. If you want to debug just set debug equals true. In this case we don't. Then here we have some kind of important information. This share link expires in one week. So we have here a live link. If you open it in a new tab it will show the gradio app. You can see here we have another uh interface GUI graphical user interface using gradio library or gradio package. If you pass here 100 plus 200 it will be 300. Submit. You can see it works. Okay. So this link here expires in one week for free permanent hosting. If you want to have a permanent hosting forever and GPU upgrades run gradio deploy then you can deploy it on hugging face to hugging face spaces and we'll see that later. So now let's go ahead and continue learning about what are the different capabilities and features offered by gradial. Also we can do the same thing by the function sub numbers which subtracts numbers x comma y. Now we we can go faster than earlier return x minus y. Here this is a function called sub numbers. So subtract numbers. It takes from me two different numbers x and y. Then it returns x minus y. Now let's go ahead and create an interface by going interface equals gr. So gradinface and as I told you this is the main class the most important class inside gradio it creates an interface a graphical user interface for you a user friendly interface function equals sub numbers so the name of the function comma inputs equals x list and then pass grado dot number and then grado dot number and we have also Now it puts equals gradio dot number. So it takes from me it receives two different numbers and it returns the the subtraction of that of those two numbers in the in the form of a number. Now let's launch it interface.launch and then all you have to do is just run the cell. You can see now it's showing the interface. Here we have X if you provide 8 and then Y 4. 8 - 4 we have here four. If you provide 12, 12 minus 10 is 2 and so on. You can see how easy it is to create a really pretty web interface or front-end interface using gradial. Now let's go ahead and do the another task of dividing numbers. So divore numbers and then it takes from me x comma y. Then it returns return x / y. Then let's create an interface interface equals gradio. So grin interface pass in fn function equals this function div underscore numbers or div number we can call it div numbers then we can pass in here div numbers comma inputs equals a list so it takes from me multiple inputs x and y equals grado dot number and then we have to put here parentheses or open and close parenthesis and also we have here grado dot number then we can get some outputs by going grad number and then at the last don't forget to launch it. dot launch launch start then run that again. You can see we will have another gradio interface and it allows us to divide different numbers. For example, if you have here x as 15ide by 5, 15 / 5 will be 3. 3 * 5 it's 15. Okay. So this is how to calculate or create a mini calculator using radial. Now let's go to the text. So what if a what if you want to manipulate text or to deal with text? How gradio offers us the text capabilities and how can we make the most out of it? We can go def and then name this function. I will name it as reverse text. So I will provide the gradio interface with some text and I need this interface to reverse my text. So provide here text then it returns input text we can call it input text input text then we can reverse it as colon colon minus one. So the most simple way or the simplest way to reverse any text in Python is just passing here square brackets then colon colon. So start from the start and end at the end but just pass here minus one to reverse the order. So if you have here some text for example python this is a normal text in python we can pass into here or index on it and then pass give me all python. You can see here we have all Python. It's the same. Start from the start until the end. And then provide here another colon. Then pass into here minus one. So start from the start and you can stop at the end but start from the end. Okay. You have minus one. You can see Python in reverse order. You can see py. Okay. In a reverse order. You can also pass here language. You can see language in a reverse order. Okay, so this function just receives some text and returns the reversed version of it. So returns returns the reversed version of my text. It's a really simple function. Now we can go reverse function or reverse text and then pass in some text. For example, I like Python. Then it returns I like Python in a reverse version. Now to create a grad interface we can do that easily by going interface equals gradio dot interface. So create an interface then pass in here a function. So you need to provide the interface with a function to perform it. So you have some inputs and you need to create some outputs. Then what is the link? What is the linking process between my inputs and outputs? This function represents the linking and the connection between my x and y equals reverse equals text, inputs equals a list of so here we can pass here gradio.ext. So this time we don't need to pass multiple inputs but rather just pass one text. Okay. So gradio text and you can see we can pass in some text later and it will be reversed. Comma outputs equals gradio dot text. So we are setting the inputs as a text and setting the outputs as a text. Then we can go interface dot launch. We can launch this app and and remember we have a public URL here that will be expired after one week. Here we have some input text. You can see now we have input text. We can write I really love the programming language Python. Then we can submit it and it will be here reversed. I really love the programming language Python. Okay. If you provide us some word for example the word machine, it will be reversed. You can see machine. Okay. So this is how you can create a grad interface to deal with text inputs. Now let's dive into grad sliders. How do you deal with sliders and the the slider input or component? First we have to go def and then define a function called slider example and then pass in a value. Then return f. So let's return some string formatted string as slider slider current value is. So let's just keep it keep it simple and just return a string that is saying slide the current value is as this value. So this function will be passed to interface and then here we have some value. We inject this value inside this string and then we we are printing slider current value is value. Now let's go ahead and use that function. We can go slider example and then pass in for example 20. Now it will return the text slider current value is 20. But if but if we want to pass it to interface gradio we can go gradio or interface equals gradio.inface and then pass here fn. So fn is short for function. Provide this interface with a function as slider example. And note in here you don't need to pass here two parenthesis. Okay. Because why? You only need to execute this function when the gradu interface is being displayed. So you don't need or you don't want to execute it when the interpreter reads that function. Then you have your inputs equals grad slider then pass minimum equals zero. So what is the minimum value you want to set as maximum equals 100. So that's up to you. whatever the minimum value you want to set and the maximum whatever maximum value you want to set. Then we have here step equals for example one. Let's set it to one. Then we have here outputs equals gradial.ext. Let's go ahead interface launch dot launch. So launch the app and we can run that. Feel free to pass here share equals true to not display that notification anymore. So you can see we don't have that notification and here we have a small info to show errors set debug to true but now we don't have errors you can see we have now a slider you can choose whatever value you want then for example 46 if you submit it will return this text slider current value is 46 if you set it to 100 it will be slider current value is 100 and you can see now the step size is one so when you decrease it will be decreased by one 99 98 98 94. You can see 93. But if you want to change the slider step, you can do that by setting by resetting the step parameter for example into two. Now you set it to two, it will jump by two steps. It will increase or decrease by two steps. So you can see here increasing by two steps. You can see two 4 6 8. Now the scale is increasing by two. And also when you decrease it will be decreased by two. Okay. So now the range here is by twos. Okay. So that's how to deal with sliders. Now let's move on to gradio drop-down dropdown menu. So how to create a drop-own menu in gradial? First we need to define a function as always def drop-down underscore example and then pass in some value then return f string current value or current value is as value and then let's go ahead and call it dropown example pass in some value for example the value python so I choose python language You can see current value is Python. Now let's wrap it inside interface gradial the grad interface by going i iface equals for example gradio.inface dot interface. So creating an interface a GUI then pass in a function equals drop-down example example inputs. What other inputs you want to input? For example here gradio dot dropdown. So the class here you can see it's called drop-down. These are different components are all available for us in the gradial library. So the grad library has so many components. It has buttons, drop-downs, sliders, text boxes, number boxes, number inputs and so many components. Here we can pass choices equals a list cause called options. So this options list we have to create by going options equals a list that we can list here a b c. So here we have some options for example a the option a option b option c. So for example, if you want to customize a habarameter, if you are hosting some machineing model, then you then you have some different values for some habarameter. For example, learning rate, you set some different values. Then you let the user choose whatever learning rate they want to use. This is one idea on how to use and leverage dropdowns in gradio. Then we can go comma outputs outputs equals gradio.ext. So it returns a text. Why? Remember in this function we we are returning what text. So you have to keep in mind what are my input shape and what are my output shape and also how do you present your output and how do you present your input and let's go ahead and then call iface equals launch. So you can see this time I called it IPAC here because since we have just one one input we don't need to pass it into a list although it doesn't produce any error. So let's run that. You can see options. Yeah here I called it options and I didn't run that. You have to run this list then run this list. So you can see this is my radio interface is being loaded. Here we have some dropown menu. You have a b you can switch to c and then for example choose b submit it you can see current value is b so you can see how easy it is to create dropown menu you don't have to worry about the html thes javascript to create this front-end web development as they say in the in the tool gradio here and then go to the website build machine learning apps in python create web interface faces web you can see web is using HTML so behind the scenes there there are some HTML files CSS files JS files are being run and loaded behind the scenes and you don't know what's happening behind the scenes so create web interfaces for your ML models in minutes deploy anywhere share with anyone and you can see here down they have everything you need to build so they have uh so many components you can see here import grado SGR Then we have greet to greet someone. Name hello plus name. Then you pass the function as we did fn equals greet. This is a simple function like us. Then inputs equals text. We have a text input. We can write here my name is Muhammad. Then submit. You can see the output here. Hello Muhammad. And then the outputs here as text. So feel free to read here in your own time. You can see so many documentations as I have here IPI. But let's now go to our notebook and complete the codes. Now if you wanted to change for example here the options you can do that easily by going A change for example into Python Python B change it into P ph PHP and for example C change into SQL and you can run that again. You can see now our gradio interface is being loaded and it will show us the names of the Python or PHP. If you submit you can see current value is PHP SQL you can see here current value is SQL structured query language. Now the the next step is if you want to create gradio image how do you deal how do you deal with images? Well you can do that in easy steps. First from pill import image. We have to import the image class. Then def convert and then pass in image path. So this function will convert my image from a normal image from a regular image into a grayscale image which is amazing. You can see load the image and then we have image equals the image class dot open and then pass in this function image path. So we are receiving this function receives image path the path to an image. Then we are passing that image path into the open function. It will open that image and return a pill image instance into this variable. Then all we need to do is just go ahead and convert the image to into a grayscale format by going return image.con convert the function convert and pass in L capital L to convert any image you would like into a grayscale image. Now if you have here some images I already have some images here you can see I have this image of C a picture of C. We can pass this image copy this path. We can pass the path of this image into this function. As you can see here it's called convert. So we can say convert and then pass in my image path. Here they ask for image path. We can run that. It returns an image converted into a grayscale image. You can see now the image is a grayscale. So to to incorporate this into a gradio interface that's easy. We can go iface equals gradio.inface then pass in the function the function that you want to execute the function that you want to run behind the scenes. Here we have convert, then we have input equals gradio dot image. So we have the image component then pass type as a file path. So the type of this image will be a file path a path to the image file. They have outputs equals gradial dot image. It receives an image and it returns an image but in a grayscale format. Sometimes you will receive an image and return a label to classify the image. But here we are inputting an image and also outputting another image. Here you can see iface.launch launch then pass here S share equals true to not to get that to to to not to get that error or notification share equals true. You can see now it's loading a gradial interface. Here we have drop image here. We can for example take this image and drop it here or you can go to Google search for C images. Here you have a plethora of C images. We can for example take this image go to gradio there you can see to the collab drop it here now it's dropped submit now we have a grayscale version of the image so you can see here we are inputting a colored image we have colors submitted then we have a grayscale image converted successfully so now we have a nice app and we can also present it using this public URL So running now this app is being running on a public URL for a duration of one week. After one week this app this link will be expired. So you can see here here we have this app. You can drag any image. For example if you search for flower images flower images this image for example. If you go to here drop image here. Now this is the image of a flower. submit it. You can see now we have a grayscale image converted. Let's dive into gradio JSON. So let's put a title here gradio JSON. And then let's define a function called number details. So number details to retain some details about a number. it takes from me or it receives a number and then you can see it creates a details dictionary. This dictionary contains several information and details about this number. The first information is original and it contains the original form of the number the same number. So we the number that we pass in will be stored inside the key original original comma we have the squared version of the number which is number then double asterisk two. So we raise this number to the power two then we have square root where we take the square root of the number by raising this number to the 0.0.5 half. So if you raise any number to the power 0.5 then you are basically getting the square root of that number and also at the finally is and the score even is the number even or is the number odd in this case you can discover that by going number modulus 2 and then equals equals zero. So you can see now we have a dictionary that contains several information and details about this number. For example, here if you have the number 10 and if you put double asterisk sign then two then basically you are rising raising 10 to the power two and then we have here 100. So we have 10 * 10 then we have 100 okay 10 * 10 the same number double twice and here we have square root where you raise 10 to the power 0.5 then you have 3.16 and if you raise here 100 to the power 0.5 it will be 10 you are taking the square root and also at the end you have 100 modulus 2 then you have here zero Does this equal equal zero? In that case will be true. So this modulus sign in addition to double equal sign zero will return true or false. Whether this number is an even number or odd number. For example, 50 is considered an even number, it will be true. Whereas 51 is an odd number. So you can see here we have false. Okay. It's a it's a clever trick to retain to return and discover whether this number is even or not. Then at the end return details. As you can see now we have a nice function an amazing function that returns some information and details about whatever number. So you can call that number underscore details and then pass in for example the number 400. There you can see it returns here some information original 400 squared 16,000 square<unk> 20 is even true if you raise here for example 20 you can see it changes dynamically based on what the number you provide to the function. Now let's go ahead and wrap this function inside a gradio interface by going interface equals gradio dot interface dot interface and then pass in here fn equals number details. This is uh this function and then comma inputs equals gradio number. So remember this function receives from me a number a single number then it outputs so the outputs equals gradio.json JSON. Then at the end, let's go interface.launch. Let's launch this interface. Now we have this fascinating gradio layout. You can see it's loading. Here we have number. If you for example input the number 70 submit, then it will return a JSON format data. You can see original is 70 squared 4,900 square<unk> 8.3 is even true. So you are retaining some information some really helpful and rich information about the number you are providing in. If you change it for example to 99 you can see submit it changes based on the number that you are providing. If you input here 100 to see whole numbers, you can see here squared is 10,000 square root is 10 is even true and original is 100. Okay, so that's it dealing with grad JSON. Now let's go to the next step where we will deal with another label. So the gradio label labels in gradio. So the label is the name of the class. So imagine you are creating a classification model and you want to classify into different categories. You will return then a label that labels whether this data point belongs to one class or another class. For example, you are classifying several different types of flowers or this flower is a red flower or a yellow flower. So let's define a function called classify underscore number. It receives from me a number then it's it checks if condition if number is larger than zero then return positive. So that's it. If this number is larger than zero if this number greater than zero then return positive. L if so else if L if this number is less than zero. So this number is smaller than zero then return negative. Else this condition is false. This condition is false then basically return zero. So if none of these conditions are met then at the end we do an else statement and then return zero. But if this condition has met has been met so if number is greater than zero return positive. L if number less than zero then return negative. So here we are basically classifying numbers into positive negative zero. Now let's go ahead and use this function. You can see here we have indentation error. So expected colon. So you can see here we have yeah here we need to put semic colon. Okay you can see now we have a classify function ready to go. Let's go classify underscore number and then pass into here for example 50. 50 is positive then it classifies it as positive. If we pass here -1 then it classifies it as negative. If you pass here -50 it will be as negative but if you pass here zero it will be classified as zero and so on. So here we have a nice function that classifies into positive num negative zero. It classifies and categorizes different numbers into these different categories. Let's wrap it inside the gradio interface by going interface equals gradio dot interface and then pass in the function fn equals classify underscore number. So we pass in the name of the function. We are taking the name function and passing it to the fn parameter. Let's insert an inputs here. Inputs equals a list or a graded number. Let's pass in just one number a grad number component, outputs equals gradio dot label. So the output here is a label. You can see now we are using the component label to label the class. Then let's go ahead and go interface.launch to launch our app. Run that. And you can see now we have this interesting layout is being loaded. You can see loading. Now we have a number. If you insert 80, it's a positive number and it will be classified as positive. You can see now we have a label. This is the label component. It's different from the text component. You can see here we have the text component at the top where you type something and it produces you can see here you insert some text Python that it produces some text. Okay, it's still within the text input. Here we have a label. A label is different. Here you don't have an input but a label but rather a label. So you can put here whatever number for example minus five then submit it. Then you have here negative. And if you pass here zero it will be classified as zero. And feel free to try whatever number you would like. Now let's go ahead and dive into another component of gradial which is grad layout. So gradial layout. So now basically we have finished. So congratulations we have finished all the components the most important and common components that you will use inside gradial. If you go ahead and search here gradio or gradio components components documentation then here you can see components here we have a great list a massive list of all the components that you can use. So it's a huge list. You can see we have here introduction, audio, you can set some audio, bar plot, button, chatbot, checkbox. You can see have clear button. We have here the data set date time and also you can see image that we have used earlier. So remember image grid image where you pass in an image and then it will opens that image. And remember we have specified the value here as or the type here as file path. Okay. Then you can also search here for whatever component you would like to use. Also here we have JSON that we used earlier. You can see JSON. Also here we have the markdown dropown menu. And feel free to explore that in your own time. But now let's go ahead and dive into the gradual layout code. So now basically what we are what we we were doing is just creating components and throwing them straight away into this interface. But how do you lay out? How do you organize these items? How do you organize them and control the layout and the way of displaying these items? So rather than just displaying them in random order, why don't we just organize the way of displaying them, making them organized, neat, and a lot more uh beautiful way. So render it in a beautiful way by going with gradial do.blocks. So now you can see this class interface controls the rendering process. So interface is an automatic class that automatically sets the organization way of the items. So the interface is an automatic way. But if you want to use a manually created layout way, if you want to create layouts manually, you define you the you are the person who defines how to display things, then you would need to go ahead and with so use a with context in Python grad. Then open and close two parenthesis as demo. Then we have here with gradio dot row. So create a row in this layout. So you can see we have a class row. So now we are manually defining the layout. How do you want to display these items inside this row here? Here goes whatever you want to put inside the first row. For example, the first thing is text one equals gradio.ext and then pass into here the value equals output one or output one. Okay. Then we have text two. We need to insert another text item equals gradio.ext another text component and pass value equals output two with gradio row. So please insert another row. Please add another row here. A second row. And inside that row go ahead and insert whatever item you would like. For example, text 3 equals gradio.ext. and then pass in value equals our bottom row. So we have bottom row and then let's go ahead and do demo launch. So demo.launch. So here these values are just really strings. You can define whatever string you you would need to add. Now let's launch our app. Make sure you pass in SH equals true if you don't want to get that notification anymore. You can see here we have this gradial layout and beautiful. Now we have two rows. You can see now you are controlling the way of displaying the item. See we have two rows. The first row contains two text boxes. You can see here we have output one output two. Then the second row contains a text box with bottom row. So here again we are instantiating a new instance of blocks by going with with grid.blocks as demo. Then inside this blocks define two rows row and row. Inside this row insert or inject two text boxes and you can see them here. Here we have two text boxes. They are siblings. Inside this first row we have injected two input boxes. Then we have inside the next row we have one text element that is say that says bottom row. As you can see now we have this beautiful layout being rendered in our customized in our customized way. Now let's go and move on to the next step. Import gradio asg with gradio.blocks as gra as demo. So you don't need to import gradio again. But if you want to run this cell as the starting cell again, you need to import it again. So if you if you don't want to run all the cells later when you come back later, for example, after 1 hour and the runtime has disconnected the when you import from here, you don't need to run all the cells from above. You just start from here. Okay. With gr.blocks as demo, let's go ahead with gradio row. So insert a new row. Then inside this row, insert text one equals gradio.ext. And then pass in value equals output one. And then we have here text two equals gradio.ext. So insert a text component. And then pass here a value equals output 2. Then we have here with gradio. So with gradio. So with is a context manager in Python. With grad row, it manages the context. Then text three equals gradio.ext and then pass in the value as bottom row. Let's go ahead and demo.launch to launch that app. And here we you can pass share equals true or without it. You can see now we have this gradio layout is being displayed and rendered for us. You can see we have two rows. The first row contains two text boxes. The second row contains one text box. And you can see this because the first row contains two different two distinct text boxes. It shares the spacing between them. So you can see these are equally spaced. Whereas the second row here contains one text box and it's fully it it spans across the full width. It reaches the full width of this row. Okay? It takes up to the full width. It fills the full row. Now let's go ahead and add another code cell and also explore some more different option options with gradio.blocks to customize our layout. So here we have to go with gr.blocks as demo. Let's go ahead and add with gradio row. So add a new row. Then inside this row note here we have a new column withgrad.com. So here we are adding a column. Now sometimes you don't need necess it doesn't it doesn't necessate so in some cases it doesn't necessate to add a new column but in this case you will need to add a column then inside this column text one equals grtext and then pass into here value equals row 0 column zero. So this is a row zero call zero dash component one and as I told you in some cases it doesn't necessitate to add columns in some cases it will be necessary in case you need to add columns note we are adding the columns inside the rows. So first you start by adding a row inside the row you add columns and you cannot swap that order. Okay. Then we have here text tool equals gradio.ext and then insert some value here as row zero column zero dash component one or component two here. Okay. So here we have component one the row number zero the column number zero but component one and then component two. After this column let's add another column with gradio column. So note the C here is capital. It's a class. It's called column. Inside this column, go ahead and insert a text three component equals gr.ext and then pass in a value parameter and then specify row zero column one. Then after that let's add so you have to to de-indent here two times to get rid of this row context manager and then add another row. So with gradial row outside the scope of this row. So here we have this row scope. Inside the scope we have two columns. Inside the first column scope we have two text components. So you have to be you have to be careful when you space into the columns the rows. Inside this column scope we have two text components. Inside the second column scope we have one text component. Then let's create another row and insert here text for. So without inserting any column gr.ext text and then pass here value equals bottom row. And you can see here the flexibility here. Not when you when you add one column inside one row, you don't need to add columns inside the next row. So it's really it's really flexible here. The way you organize it is up to you. You are the person who is responsible for displaying how is your gradio layout is being rendered and displayed to others. You define the columns. Inside these columns we put components. These columns are inserted inside rows and not every single row needs to contain columns. Maybe there are some rows that doesn't contain any column. Now let's go ahead. So you can see the flexibility and how easy it is to construct layouts. So you can see now we have layout and note now we have columns. So now we have one row inside this row we have one column. This column contains two components. So component one and the component two. Here we have another row. You can see bottom row. So we can see here we have one row inside the two columns. Column column. The first column contains two different text boxes. The first column contains two different text boxes. The second column inside the first row contains one text component. And then the second row contains one text component. And it takes up until it fills the full width. Until it fulfills the full width. Okay. Okay. Now let's move on to the next step with gradio.blocks as demo. Let's go ahead and insert here a row. So with gr row insert a row here. And then we have with gradioc column. And note here the the two columns you can notice that the two columns here are taking the same amount of spacing. They are taking the same amount of width. You can see they are equally spaced. Whereas if you want to to to differentiate or to assign different width scales, you can do that easily by passing here a scale parameter. So you can go scale equals two. So here we are scaling this column to take up 2/3 of the width and then text one equals gradio.ext then pass in value equals row zero column zero dash component one. They have they need to insert another text component by going gr.ext pass value equals row zero column zero dash component 2 and this column is taking scale parameter equals 2. Let's now insert and add another column by going with gradient column. Let's go ahead and insert the scale parameter equals to one. So this column will take just one/3. You can note here 1/3. This column will take here 2/3 of the total width. Okay. Then inside this column context manager let's insert text three equals gr.ext and pass in value equals row zero column 1. Then outside of this row scope, let's add another row by going with gr row and then pass in here text for or add text for equals gradio.ext value equals bottom row. And then let's launch this app and see how this differs from the previous app. And remember to pass share equals true. So you need to make sure that you pass in share equals true. You can see here now this column takes up to 2/3 of the total spacing. If you go up scroll up here you can see here the the the difference between that layout and this layout. This layout the spacing is shared is the spacing is distributed equally between these two columns. The spacing is distributed equally between them. But here the spacing is 2/3 of the space is inserted to the first column. One/3 of the space or of the width is inserted to the next column. And you can see how the different between that all that just with one parameter. Scale equals 2, scale equals 1. You can see how easy it is to manipulate and to play around with the layouts. It's actually quite fun to play around with layouts in gradio. Now let's go ahead and do some more complex layouts by going with gr.blocks as demo inside this blocks. You can see first we instantiate a blocks object and insert an alias name via as demo. So adding an an alias name then with gr row or tab. Now let's add a tab. So here we have the tabs tab and then we have tab one. So this is the first tab. Actually you can insert tabs in gradio. Then we have here with gradial dot row with gradio dot column. So inside this row let's add a column. Inside this column let's insert text one equals grad text. Then pass in some value equals row zero column zero dash component one. We have text two equals gradio text pass in value equals row zero column zero- component 2. Let's go ahead and insert another column with grt column and then add another column inside this column. Let's insert text three equals gradual text and then insert a value of row zero column one and after this column let's add so outside the scope of this row context manager let's add another row we can see and then inside this row insert text for equals gradio text and then pass in value equals bottom row. At the last, let's add another tab by. So you can see here outside the scope of the tab class here, the tab class of the tab object. Let's add another with context manager with graduate.tab and then pass in here tab two. So you will see how nice it is these tabs. These tabs are really nice. They organize the display of the items text. But then with gradio dot row let's add a row inside this tab gradio text and actually you can add here columns but let's keep it simple text and then pass here welcome to the new tab. Let's go ahead and run the demo by demo.launch dot launch every single grade you run you have to launch the demo. Okay. And then pass a share equals true. Let's run that. You can see now it's running. Now it will show us the layout. You can see the the layout has shown up here. We have tab one. You can see we have one row inside this row. It contains two columns. The first column, the second column. The first column contains two text components. And you can see that the spacing is distributed equally between these two columns. We have the second row. In the tab two here we have just one row that contains this text box welcome to the new tab. So these tabs are really nice to organize and to make the the display neat. Here we can also insert column equals scale equals scale equals 2 and here we can insert a parameter scale equals 1. Okay. Now if you go to tab one you can see here the the spacing is distributed equally. When you run that again you can see this column will take 2/3 of the space 2/3. And if you stop the order you can do that easily by going two and here one. So feel free to customize your your layouts whichever way you want. Okay. You can see this column takes 2/3 and this column takes just 1/3. even though it contains two components. So we can also use so here the name of this is called as let's name it as gradial demo tabs. Okay, these are the the tabs that we add to to a gradio. Okay, now let's move on to the next step which is the idea of using a gradual blocks and then adding an accordion. So, how do you add an accordion? Yeah, gradio accordion. How do you add an accordion into a gradio and insert a new component inside an accordion? So, let's go with gradio.blocks. blocks as demo. Let's go ahead add gradio label and then insert here label here. So you can add a label here. After this label, let's go with gradio accordion. So you can see the accordion object or the accordion component uses this with with keyword. So you have to add with keyword in Python grad accordion and then pass into here accordion here, open equals false. So if you want to this accordion this accordion to be opened by default, you have to pass in here true. And if you want this if you want this accordion to be closed by default, pass in here false. And that's up to you. And then we have here gr image. So inside this accordion we want to open an image object or image component. Let's go demo.launch you can see here it's trying to load in the layout and it will have a an accordion object. You can see accordion here we can open it close it and if you open this accordion we have this drop image here. We can open our images. Choose Elmo. You can see here we have Elmo image. Okay, it's trying to load that. So inside this accordion, if you close it, it will be closed. Open it, it will be opened. And remember, we have a nice little parameter called open. If you pass here, it will be open by default. So this this accordion item is one of my favorite items in gradient library. In grad library, you can see now it will be open by default. Okay, choose image flower. It's loaded successfully and you can close it if you want. Okay, and that is accordion. Accordion is short is uh one of the most important items inside gridio and feel free to go to documentation to refer back and reference some more opportunities and some more option ways to use that. So you can see here methods they have expand if you want to expand it description. This listener is triggered when the accordion is expanded. So you have also a listener that could execute some code when the accordion item is triggered when it is motivated and opened. You can trigger some code to be happened and to be executed. We have collapse. So the collapse event. We have description. This listener is triggered when the accordion is collapsed. And feel free to play around with that in your own time. It's actually quite fun to play around with with gradio. So you can see how easy the syntax is of gradio. Let's go to gradio buttons. So how do you add buttons using gradio? The first thing let's go with gradio.blocks as demo. Let's go ahead and insert here some buttons by going grutton and then pass here button component one. Then we have here grbutton and then pass here button component two. And also we have here gradio image. Then after that we have gradio demo.launch. Okay. So we can launch our app. Now pass in here share equals true to be able to share it on a public URL. Then you can see now it's loading our layout and now it contains some buttons. So we have button component one button component two drop image here or click to upload. You can click here and upload whatever image you would like. You can see now we have an image. Currently these buttons when you click on them they will not do anything. In later section we will learn how to make these buttons work. Okay. Now let's move on to next step. Next how to insert some CSS into gradio. That's easy. We can go ahead and gradio CSS. Put a nice little name here. Then let's go ahead and create some CSS. So we can we can go CSS variable equals and then insert three double quotation marks. So we need to add one 2 3 then also close by three double quotation marks 1 2 3 inside these double quotation marks let's add dot your class for example here you can name your class whatever name you want. Then let's go ahead and open and close parenthesis. Inside this parenthesis, add whatever custom CSS you would like. CSS is short for cascading stylesheets. Let's go ahead and insert some height property. So the height attribute as 1,000 pixels, background dash color, and then set it as for example red. You can customize whatever codes you would like. Then let's go with gradio.blocks blocks and then add here CSS equals CSS. So insert the CSS variable inside the parameter or as a value to the parameter CSS as demo. And feel free to name this variable whatever you want. I will name it in this case for example my own demo. Then let's go ahead and with gradio row and then element_classes. So this is a parameter called lm classes and then pass in square brackets pass in the name of the class in this case your class and then let's go ahead and add gradio image as a component inside this row by going ahead and setting the height as 900 width equals 20. Now let's go and demo or my own demo in this case my own demo dot launch and then pass here share equals true. Now 3 2 1 run that. You can see now we have a custom CSS code that will run. Now this is the layout. It's being loaded. You can see now the height is longer. So you might not notice that but you can see the height here. Before it wasn't that height, but here now we have a much longer height. You can see the scroll. Now you can go down further. And then we have a background as red. You can customize whatever CSS you would like. For example, changing the background rate as yellow. It will change it to yellow. It's all up to you. the custom settings, the custom modifications that you want to that you want to apply to your custom layouts. Here we have def multiply. Now, what if you want to if you want to actually make these buttons work? How do you trigger some code when you click on a button? How do you execute some code when you click on a button? That's really simple. By going ahead and defining a function, for example, multiply. So def is short for define a function called multiply pass in x comma y then just return it returns x * y. This is one of the most simplest functions that we have created. If you write multiply and then pass in 5, 5, it will just multiply 5 by 5 25. If you pass here for example 10, it will be here 50. Let's wrap it inside gradio interface by going with gr.blocks as demo. So instantiate a new instance of the blocks class as and store it inside the the alias name demo. Go ahead and create a row to organize our display and then create two sliders. Now we have two events. The first event is called here change event. So you want to trigger some code in a change event or during a change event. So basically we have two different types of events. If you go here and right here there are two different types of events. We have one click events. Click events. We have two change events. Let's start with change events. So the first thing is change event. How do you trigger code when you for example change a slider value? X slider equals gr slider and then pass nothing. We have here y slider equals grio slider. So here we have two different sliders. How do you trigger some code whenever you change the so change event whenever you change the value of the slider. And then we have here with gradio dot row add another row and the result this row will contain the result equals gradio.ext. Let's go ahead and here add y cider dot change. So let's trigger some code when we change the value of the slider. Here we are applying this we are applying this event upon the y slider. Okay, not upon the x slider. you will see later I will tell you that X slider down will not when we change it it will not trigger any code whereas Y slider when you change it when you play around with this value it will trigger this code that I'm about to write in into here fn function equals multiply so here we are saying hey please y slider when I change your value execute the code multiply and then take the inputs as the following you can see here inputs equals a list of two numbers x slider comma y slider. So multiply the x slider value by the y slider value. Then go ahead and just display the outputs as the following gradio or result. So we have to pass in result. This result variable contains gradio.ext. Okay. The output will be in a text form. Now if if we go ahead and just app or demo dot launch. So as I told you, you can feel free to play around with this name. It's called now demo. I can change it to app and it will work successfully. You can set sh equals true. Now we will have a really exciting app where you can see here when we change the x slider, okay, the code doesn't get triggered. So feel free to change that. Nothing happens. But when you change the Y slider, grad will work and it will execute. So there's a hidden listener that listens for this event, the change event. And whenever you change the value of this, so it multiplies 15 by 42. You can see here we have 630. If you reduce this value by 10. Now 15 * 10. If you change this 15 * 10 here we have 150. Okay. So whenever you change the value of the y slider there is a hidden listener there is an a latent listener that listens for this event and tries to execute this code multiply. So this function this nice function it will be executed whenever you change the value of the y slider here. Y slider change pass in the function multiply pass in the inputs X slider Y slider multiply the Y-sided value by the X slider value and they return the output in the form of a result which is a gradio text a normal regular gradio text. Okay. And you can see here this app is fully working. It's a multiplication app that multiplies the y value by the x value. Now let's go ahead and apply some more examples to practice more. Here we have with gradual.blocks blocks as demo. Then let's go ahead with gradial dot row add a new row or insert a new row. Then we can go x slider equals gradios slider and then pass in label equals x and then also we have here y slider equals gradios slider. So a slider is a component inside gradio which is a normal slider that you can slide and change the values. Then we have label equals y. Then we have another row that displays the value displays the the the result by going result equals gradio.ext a normal text input. Then here we have x slider. So now let's step things up and apply the listener not only to the Y but also to the X by going X slider dot change. So execute a change event listener to pass in the function as multiply multiply inputs equals a list of two inputs. So here we have x slider comma y slider and then the last finally we have outputs equals result and here we we have to insert equal sign and also here here the change event will work on the x slider. Let's do the same on the y slider by going y slider dot change pass in function as multiply. You can see how fast we can go here. inputs equals X slider, comma, Y slider. And then we have at the last here outputs equals result that we have the same component for the row. The second row here you can see multiply multiply. Okay, X slider is called X slider. Okay, now let's run that after we launch this demo by going demo.launch launch launch our app and then pass and then pass share equals true run that now when we change the value of x slider it will multiply its value by the the y value so we have here if you multiply you can see now whenever we change the value it will execute and it's multiplying 13 by 0 it's zero so here the y is always zero so the result is always zero remember when you multiply anything by zero the result is zero. Now let's change the value here make it for example 3 3 * 13 is 93 by 39. And when we change the value here for example here 2 * 2 is 4. If you increase that 2 * 2 * 3 is 6. Okay. And whenever change whenever you change the value of y it will display different result. Let's go ahead and dive into another example where where we have the button and click. So now we have click event button click triggers code. So when you click on a button it triggers some code with gradio.blocks. So let's create another blocks as demo or as app. Let's go ahead and insert a row a row. Inside this row, let's add an a text x slider equals gradio dot slider. And then pass in the label as x. Then let's also create another slider by going y slider gradial dot slider and then insert the label as y. Then we need another row that shows us the output by going result equals gradio.ext that shows us the result of our multiplication process. Then we have here with gradio dot row insert a button. So you can see now we need a button element by by going button equals gradio dot button and then insert here multiply. So put a catchy and also motivating text here to let the user or to motivate the user to click on the button. Okay. Then we have button here dotclick. Now we have you can see we are using the click function to execute some code that will be triggered once you click on the button. This code or this function will be executed. pass into here multiply comma inputs equals a list of X slider comma Y slider. Then we have here outputs equals. So the outputs equals here one value which is the result. Okay. Now let's go ahead and just launch our app by going demo.launch launch and then pass into here share equals true. So all we're doing here is just we are creating some rows. The first row contains two sliders. The second row contains one text component. The third row contains a button that contains this text multiply. It motivates the user to click on this button because it it uh labels multiply. Then we have a click function that will execute this function multiply upon the clicking event. So when you click upon this button, it will run this function multiply with inputs X slider Y slider. It will take these values and multiply them with each other. Then it will render the output at the results at the result component which is the the normal text. You can see here we have X slider. We can see when when we play around this values, it doesn't run anything and the y also when you run here we have some values. Now let's go ahead and multiply it will multiply these values and give you the result. So when you specify for example here four here for example uh uh 6 6 * 4 is 24 and also change here for example 3 3 * 4 is 12. Okay, so this is how to execute some code upon the clicking event. Now let's create an app that takes one input and returns multiple different outputs. So so let's write returning different outputs. Here the first thing that we need to add or we need to create is the idea that creating a function called make_gayscale. This function takes from me image path and then and then let's open the image. So open the image. Let's go image equals image class dot open. Then pass into here image path. Then let's go ahead and convert the image to grayscale format. And let's go image grayscale equals image.con convert pass in L then let's return image grayscale comma a text output called image unage convert image converted let's run that you can see now this image when you pass in some image for example make grayscale this this function it takes from me an image path then it returns image converted into grayscale comma string. So let's go ahead and pass here some image for example the C image copy path pass it to our function make grayscale it will return back a tuple containing a pill image and the the the text image converted let's unpack that into two variables you have the gray image log the log okay here we have two variables the first variable is image gray image you can see gray image It's now a gray image. You can see a gray image. The same variable here. And we have the log variable that contains the text image converted. Okay. So here we are dealing with multi modalities. Let's now wrap that into a gradio interface by going with gr.blocks as demo. Let's go ahead and create a new row with gr row. And then inside this row, let's insert input image. So we add we need to add an input image equals gr image component dot image component. Then pass into here type equals file path. And then we have also output image equals gradio image insert an image component. And let these parentheses empty. Let's go ahead with gr row pass inside this row log equals gradio.ext. Then inside this text leave it as it is empty. Then let's create a submit button equals gradioton. And then we have your value equals convert convert to grayscale. So this is the call to action call to action of the button that you need to make it motivated motivating and catchy in order for the user to click it. Then we have here submit dot click. Then we have here fn equals make grayscale. This function remembers takes for me one input and returns two outputs. Then we have inputs equals a inputs equals input image. Input image. Then we have here outputs equals a list of output image also comma log. So the the log. Okay. We have here demo launch and then pass here SH equals true. So the log is the status and it's simply this text which is image converted. Let's launch my app. You can see here we have a gradial app now running. We have a drop image here. Let's choose the image of Elmo. Let's choose it. You can see now it's loading. Here we have Elmo. Let's click on convert to grayscale. It will return here this text image converted. in addition to with this image of Elmo converted into a grayscale image. So here we have multiple outputs being retained and this is the idea of returning different outputs taking in one input and returning different outputs. Let's dive into gradio themes to change the theme of a gradio layout using some of the available themes on the gradio list. We can go help and then pass in gradio themes to check what are the the different themes that we have. You can see now we have a massive output. If you scroll up here you can see all the available themes the names of the themes that are available for you to check out. You can see here these are the themes. We have the glass theme, monochrome theme, ocean theme, origin theme, soft theme and the color. Now let's go ahead and try and try some of these themes. We can go def echo. So this function will just echo what we pass into yet text or num. Then it returns let's make it num better than text. Then let's return num. So we pass in five it returns five. If you echo six it returns here the number six. Then let's go ahead and then I face create an interface that will be gradio.inface. interface to instantiate an interface object. It takes from me fn equals echo. The function echo inputs equals gradio number. It takes from me a number and it returns to me a number. It does nothing but returns the same exact same input that we have passed in earlier. The theme now we can see we have a new parameter here theme equals gradio do themes do themes do glass. So we have a glass theme. Let's try it. We can go ahead and run that. After we launch this interface, we can go interface.launch. Then set share equals true. Now the the layout is being loaded. You can see now we will have a brand new layout. You can see the glass theme. Here we have number five. Then submit. It will submit the same number but with a nice beautiful pretty theme. Okay. The glass theme. We have also different options. If you want to try them, we can go ahead and copy this code, the same exact code, so we don't rewrite the code, duplicate it, and then change the theme to soft. Okay, so all you need to do is just change the theme from glass to soft and then see the magic happens. You can see now we have a soft theme different than what what we have earlier. You can see here the theme this theme. Okay, we can pass in 10 then it will submit and returns the just 10 echo it. Then let's try the last theme here which is called also monochrome. Mono Chrome also it's a it's a nice theme. You can see it's an exciting theme. We can pass in here 40 submit. It submits and returns 40. Okay. And feel free to play around with different themes. Also you can use the different method which is gradu setting a blocks as demo. Then we can go and create a new row by going with gradio dot row and then append into here gradio number. Here we can pass inside the blocks theme equals gradio themes dot monochrome. So we have two different methods remember to create a layout. We have the interface class, the automatic interface class and also we have this manual way of constructing the the layout here. In this way also you can play around with themes by passing the theme parameter to the blocks class. So rather than passing theme parameter to the interface class, we can pass this theme parameter to the blocks class. You can see here like that. Then we can call this demo and then launch the app. You can see now we have a monochrome theme. Okay, just with one input. Let's dive into another topic which is gradio integration with machine learning. Integration with machine learning. So so far we have building layouts but with with no in without incorporating any machine learning into the pipeline into the process. Now let's have machine learning from transformers import auto image processor. So we have this class which is called auto image processor and this class is used to process an image to be able to pass it into the resonant model. We'll use reset model then we have a comma automodel for image classification to classify different images for image classification. Let's go ahead and use that. First we have the processor equals processor equals here our instance from the class auto image processor that we can dot from pre-trained. So from the pre-trained model which is Microsoft /resnet-18 so 18 layers here we can load the model into the processor instance. Then we have here model equals automodel automodel for image classification classification dot from pre-trained and then pass into here Microsoft Microsoft/resNet- 18. So, so this model you can search on hugging face and you can find it on hugging face under the name Microsoft. Go to models then search filter by name. You can see here we have Microsoft resent 50 and also resent 18. You can see here the model card on how to use this model transforms. You can see from transforms import pipeline or from transforms the way that we used from transforms import auto image processor comma automodel for automodel for image classification and then from pre-trained pass in Microsoft/resent 50 or 18 and we have from pre-trained pass in Microsoft/resNet 50 and you can see here we have the reset archetype you have residual connections this is the this is the residual architecture this is the the plane architeia And this is the VG19. They convert it to the VG19. And keep in mind this architecture is used to classify images. So let's go ahead and load that model in. Now the next step is to visual is to visualize the model architecture by printing the model. And you can see the architecture of the model here. If you search for ResNet model architecture, you can see a plethora of images on what is the residual net. You can see here the residual neurotic. This is the main idea behind ResNet. The main novel idea that they have proposed in this archae is the residual connection. The residual connection makes the neuronet training more stable and also it is it eases the flow of the residual. So it ease the flow of the data. It makes the flow of data more stable and easy without any degradation in the performance. And you can see the idea here is incorporating the input to the layer into the output. And if you search here ResNet paper, you can see deep residual learning for image recognition by coming here it all. This is the most cited paper in the world uh by 300 above thousand citations. You can see here view PDF and scroll down. Here we have the the image the same image basically in the hugging face platform the residual connections. Now I think our model is loaded. We can we can show its architecture and that is and that is this is our architecture. You can see we have now reset stage sequential reset basic layer identity. So they are preserving the identity of the layers. ResNet convolution layer, convolution 2D, batch normalization layer, relu. You can see they have so many layers. It's going deep. You can see they have deep layers. And the main idea is that they are using here reset shortcut. Now let's move on and use this model into our gradio interface. The first thing is create a function called classify image. This function takes from me an image. It receives an image. Then we need to process that image. So in order to use this model we need to process our image and make it compatible with with our model by going ahead and image equals processor that we have created earlier by going processor then pass in our image return tenses equals to pytorch to set the form of the return tensor should be in the form of pytorch. Let's go ahead and access the key pixel values. Then let's go ahead and do the next step which is passing the image passing our image to the model to the model and then it returns logistics. Keep in mind any classifier in the world would return logits and you have to select or choose the most highest value of these logits and this is a predicted class. Here we have 0 to 1,000 because they are trained on this model is trained on imageet consisting of 1,000 different classes. Here we have loits equals model. So let's use our magical model and then pass in our image dot logets. So get in the logits. Then we have via gra grab grab the index of the largest value or of the highest value between these logets probability. So here we have so many probabilities. We need to select the highest probability value by going ahead and predicted label equals lojets.ax and then pass in here minus one dimension minus one dot item to select that singular item then return model.configuration do ID2 label. So just index and on the this list ID to label basically if you go ahead here and then tap into model.configuration do ID to label. So map the ID into a label. It's a huge dictionary or a huge list. You can see here all the different classes and categories and groups that are existing inside imageet. We have tench, we have goldfish, great white shark, tiger shark, and so on. There are 1,000 different classes here inside the imageet. That's it. Let's go ahead and pass in our predicted label to get the predicted label. Then let's go ahead and just run this function. This function will help us to use our model and go ahead like that. Now let's interface equals gradio dot interface. Let's create and construct a new interface. Let's pass in function equals classify image. Feel free to name it whatever you want. We have inputs equals grandio image. This is the image component, comma, outputs equals gradio.label. So keep in mind this is a classification model. It receives an image object and it produces a label for for which class this image belongs to. Then we have via the description nice little description that describes what this model does by going description upload an image. Upload an image. Then let's go ahead and launch that straight away. You can see now we will have a gradio demo app that is capable of predicting or classifying the image by just passing here an image. So here we have an image an area to to pass an image. Then we can submit and then classify it. And keep in mind this there are there is a public URL that that will expire after one week. But now we have one week available to use this URL link. Let's go ahead and search for bird for example images bad images. Here we have plenty of birds. Let's select one of them. Let's copy that image or grab that image. Go to gradio. Drop it like there. Then let's submit. It will classify here as be eater. Uh bee eater. Okay. Let's go ahead and for example grab another image of shark image. This is a shark image. Let's go here. Graio submit. You can see here great white shark. Nice. And the last search here. Volcano image. You can see here we have volcano image. Let's get rid of this image. Pass in the volcano image. It will classify it as a volcano. And hooray. Here we have volcano. So you can see resident now classifies that image as a volcano image. Now let's move on to the next step. Now you can see how easy it is to build gradio layouts or to build gradio apps incorporating some state-of-the-art machine learning models. Easy how easy it is. Now let's go to gradio sentiment analysis to incorporate another model which is the sentiment analysis model. Let's go from transformers import pipeline. So we need the pipeline here. Remember this is a highle pipeline that allows us to load in a model. So let's go ahead and sentiment analysis equals analysis equals pipeline and then pass in sentiment underscore anal dash analysis. You can see here analysis. Okay, run that. Here we have the pipeline and then passed into here as sentiment analysis. And remember this is defaulted to dist the default model to classify the sentiment or to classify text. Now our model here is loading. No model is supplied because we are we want to use the default model. subbert and you can see here it's called also this subbert base and case fine-tuned SST to English now my model is loaded let's go ahead and see here model or it's called a pipe you have sentiment analysis sentiment analysis and this is my model you can see the architecture of the model or the pipeline okay text classification pipeline now let's move on to the next step which is using this model to classify the sentiment by going sentiment underscore analysis then pass in I am sad run that sentiment uners sentiment underscore analysis run that I am sad it says negative if you choose here I am happy it says positive my day was great you can see my day was great positive now let's move on to the next thing which is incorporating this sentiment analysis model into the gradio layout by going defaf and then name my function predict underscore predict underscore sentiment. So we have to predict the sentiment and then pass into here a text then it returns a result. So result equals sentiment analysis and then pass into here text some nice text then return result at index zero. then grab the label and then return also the result at index zero and then score. So here we are returning both things the label negative positive or whatever it was then returning the score the confidence rate of the model that the model how many how much the model thinks that this or believes that this text belongs to one class. Let's go predict underscore sentiment. So this function predicts a score sentiment and then pass in hello I am happy this course is great run that here we have a typo so it's called predict sentiment no worries sentiment copy this name paste it over Here you can see uh yeah I have a typo here here sentiment you can see here we have forgot an end. Now this function returns positive comma 0.999. So the model is confident that 99% this sentence hello I am happy this course is great belongs to the positive class. Let's move on to the gradio interface and see how easy it is to incorporate into to incorporate it into gradio by going gradio interface and then pass in here fn equals predict. So the function called predict sentiment and then pass into here comma inputs equals gradio text box and then pass into this function lines equals to comma placeholder. You can put a placeholder as type your text here. Type your text here. Then we have outputs equals a gr a list of gradio.ext and then pass in the label equals sentiment sentiment. Then we have here comma gradio.ext and then pass into here label equals score. So one text for the sentiment and one text box for the score. Let's go. iFace.launch and start my app by passing share equals true. And you can see now we have a cool layout or a cool gradio app that you can type here. Hello, I am terrible and then submit. You can see it will say here negative by 93%. And you can pass in hello I am amazing. It will say that it is positive. because cinema is positive score 99%. And that's it. That's how to incorporate machine learning models from hugging face into the gradio layout interface GUI graphical user interface. Now let's go ahead and then uh dive into gradio errors. So this is the last topic I want to discuss gradio errors. How to show some errors in gradio by going defaf underscore. So define add underscore even. So imagine a function that you just you want to add or sum even numbers. So let's pass in a comm, b. So for whatever reason you just want to add even numbers otherwise you want to raise an error. You want to tell the user that I don't want to sum odd numbers. So here if not validate even. So let's create a function called validate even. First validate even. This function will check whether my number is even or odd. And based on that information, I want to incorporate it and check. It takes from me num. It receives from me a num. Then it returns return return num. Then modulus 2 equals equals zero. Then let's go ahead and call that function validate even. So here if you want to check that we can call this function validate even and then pass here for example 10 it will say that true. Yes my number here is even. If you pass here 11 which is odd it will say false not even 12 it will be true. So if not validate even then pass into this function the a parameter then raise so raise a gradual error and you'll see that this error will be displayed in a nice format pass into here first value is not even I am angry at you then we have here if not validate underscore even so if the B value is not even then please raise an error so raise a grandio error also telling the user that first or second second value isn't even please update it to be able to sum those numbers then we can go ahead else if there's if there's no any error if everything is fine return a plus b so this is the main logical thing logical process that I want to use let's go ahead and I if create an interface by going graddioface then let's pass in here F function equals add even comma inputs equals a list of gradio dot number comma gradio dot number. So we are here passing two number inputs comma outputs equals gradio dot number then iace launch launch my app and let's see what happens. So now we have here a gradual layout. We have two inputs. A let's pass in here four plus 8. You can see four is even 8 is an even number. Submit it. We don't have any issues. But once we pass the a input as seven then now gradio is angry at you telling you hey error first value is not even. You have to make sure that it is even. Once we make it even you don't have any error. Then the second value B here if you pass here seven or 9 submit then B is not even it says error second value is not even update it and then go ahead. Okay. So this is how you can raise errors using gradio and in a nice format. Now let's if you want a lower degree of uh of danger for example you don't need you don't want to display this type of danger which is red if you pass here 11 you can see it's a red error it indicates that this is there is something dangerous if you want to lower that degree we can easily go ahead and just update this function here of error error into warning and here warning and then since This is a warning. You don't have to raise it. So you don't have to raise this warning. Okay. Now we have a normal warning. Let's run that again. Run this again. You can see now here we have a. Let's pass for example 8 + 20. They are all even numbers. Submit. You can see here there's nothing to worry about. Once we make a for example 11, submit it. You can see now there's a warning first value is not even. So this is a warning. Then we have here B once we make B for example 13. Okay. And and also A is 11. So none of these numbers are are are even. We can go submit. And you can see here we have two warnings. Now first value is not even. Second value is not even. And at the last you can also raise this is a warning. You can see there's some type of danger still. But if you want to raise some info telling the user everything is fine. But keep in mind keep in mind that this information is whatever you want to tell the user is pass here for example five pass here six. You can see now there's an info message first value is not even. And that's it. That's gradio. I hope this gradual tutorial is fun. So you know you should a you should be able to know you should you should know how to use gradio to host or to create layouts and also incorporate machining models into it. You can see we've done a lot of the layouts how to process images and also a lot of the stuff about gradu section. In this section we'll discuss the spaces tab inside hugging face website. Here when you go to your profile and then move to your profile it will direct you to the first section which is called spaces and currently I have four spaces. Hugging face spaces is a free public platform for hosting and sharing interactive machine learning ML applications and demos directly on your profile. It functions similarly to GitHub but is specifically designed for the ML ecosystem allowing users to build a project portfolio, showcase work and collaborate with others. Key features and functionality of spaces are as the following easy deployment, interactive demos, version control, hardware options and flexibility and many many more community and collaborations and many more. So let's dive into how to create a hugging face and deploy your own model. So here you can go to your profile and then it will show us this drop-own menu. Let's go to new space. Then it will direct you to this page create a new space. Spaces are git repositories that host application code for machine learning demos. You can build spaces with Python libraries with like gradio or using docker images. So spaces are git repositories. So they are like the GitHub repositories that host application code for machine learning nodes. They are dedicated for machine learning. First here we have the owner. You can choose your own profile or other profile that you have. Then let's name our space here in this input. New space name. Let's name it as diffusion model. So this is my space name. Then here we have an input that says put some short description that describes the purpose and the functionality of this model. Let's go for example diffusion model to generate emnest amnest numbers or emnest detest numbers. Yeah, we have some license. Feel free to choose whatever license you would like. In this case, I will choose the most common one which is MIT the MIT license. Then let's scroll down here. You can see select the space SDK. Let's choose gradio. Actually we will use gradio to build this interface and then deploy it or host it to hugging face spaces. Then let's go to here. You can see we have space hardware. You can choose CPU basic or zero GPU or custom hardware. In this case I will stick to the default CPU basic. And here also we have choose a gradual template whether you want blank chatbot text to image leaderboard or trackio. I will keep it the same or the default the default option as blank. Then here you can see we have public or private. This depends on your your own preferences. I will keep it as public to be able uh to be able to share it with other people. Let's go and click on the button create space. You can see now we have a space here. Created successfully. Successfully. Let's go to files. You can see here we have get attributes and we have here readme.md. These are the default files that hugging face creates it for you. And you can see if you go and click get attributes, it will show you all these different options. You can see we have the dot. PTH short for PyTorch. PT short for PyTorch. Also another extension for storing model weights for PyTorch. Also we have PKL pickle and also we have this NNx short for open neural network exchange and we have so many extension here extensions and if you go to here diffusion model it will be direct it will direct you to the same page and also we have rhymed.mmockdown where it contains some meta information about your project or about your haggus space title diffusion model emoji they choose this emoji for you and We have also color from red, color to blue, SDK gradio, the SDK version 6.1.0. And if you want to change this emoji here, you can go to edit. So feel free to change it. And then you can scroll down and then change this emoji to whatever you want. Then you simply just go ahead and commit the changes here. After you change it, you can commit it and go ahead. But now let's go ahead and just use our diffusion model to deploy it on Hag spaces. So the first step is we need a command line terminal. Let's go and search here for terminal. You can see here we have the terminal window opened. The first thing is we have to check our git version get and then let's go zoom in a little bit dash version. So now so now let's check what is the version what is my current version of the g of the g package. You can see here have g version as 2.52.0 windows.1. So if you don't have git this running this command will result into an error because it don't have git. And if you don't have git please go here to Google and then search install git. And here you have you have the main website the first website that shows it's called git install. Click on it and it will direct you to this web page that says install. Then you have here many options there. There are different OS systems. We have Windows, we have also Mac OS and we have also Linux. If you are on Windows, click on Windows and then download here. If you are on Mac OS, you can download from here. And if you are on Linux, you can download from here. Okay, I already have I I already have installed. So you can see here the version has been printed successfully. Success success successfully. And let's go ahead and clear our tab here. Let's go to MK directory. Then let's go and name some of my folders. So we So feel free to name it whatever you want. We can go and name it as for example my diffusion model. And now it created that folder for me. Okay. And you can check that by going ls. Here you can see we have so many folders here. One of them is called my diffusion model. So this so this is my folder my diffusion model the same that I have created over here my diffusion_model. Now let's go ahead and clear that. The next step is ls dot dot/d downloads then / diffusion. So whenever or when you want to deploy a model on hugging face spaces you need a custom or a particular structure that you have to construct and build. For example here I have in this notebook I trained and built a model diffusion model to convert from text into an image or to draw an image out from text. So you provide some text for example three four five and then it generates those emnest numbers. First we have some imports here. Import the necessary libraries. Then also here we have set up the CUDA if torch CUDA is available otherwise use CPU. And then we have the batch size embedded dimension time steps epox as 100. And I already trained that model for 100 epochs. You can see here also we have the transformations. We have to two tensa to convert the mnest images into tensa. And also we have lambda that performs a specific a specific function on the on our images. Here we have conver here we have stored the mnest data set class inside a variable called train data and the same we have passed this train data variable into the data loader class. Then we have a train loader variable that contains a data loader object that is compatible to be passed to the PyTorch model and the PyTorch model will will be able to train on it. Here we have also the unit class. You can see we have the archae of the model. We have the first encoder convolution 2D. We have some convolution to DD layers that performs the operation of convolution. Also here we have some decoder that does the transpose operation of convolution and also here we have the for method that calls these layers step by step and then it defines the forward computation of the neuron net after that here we have set the optimizer as Adam to optimize our weights and here we I've built and written a training loop that trains our model you can see we have the foreign pass to pass into the model and then we have here you can see we have for pass uh loss calculation uh optimize a zero grad doing some back propagation and then optimize the step to optimize and improve our weights and then I let the model train for 100 epoch you can see here we have epoch 100 out of 100 and the loss became 0.06 so we started the loss from here 0.09 until it decreased decreased decreased until it became 0.06 06. Then we have here the loss curve. You can see it's going down and down. So the loss curve is is getting lower and lower. After that here we have a sampling function. So this function is really important. It it is considered the prediction function. So here it takes from me you can see word a word a prompt then n= 8 steps equals 100 guidance scale equals 3 and then it performs this unconditional labels for cg for cfg and then it turns it returns out an image as you can see here if we type over here for example the number seven then it gen it generates here the number seven you can see here it's it looks looks like a seven number. If you run again, here we have a seven a an image that looks like seven. Okay, so the model here is trying the model is trying to generate and to synthesize the image of seven. You can see here we have seven and if we write here one in natural language uh way it will turn it into an image. You can see we have one here the number one and also if we provide here two it will create and it will generate the number two. If we go again here you can see we have two number. So we have a diffusion model we have trained it for 100 epochs and we use this architecture that is leveraging the unit model. You can see here we have the class unit and this class here has so many convolution layers and transpose convolution layers that is working on our images and trying to convert and trying to turn our prompt from a natural language into text into image. So converting text to image. After that we have another sample here. If you pass here for example the number six then it will generate here the number six. You can see here we have a look lookalike number six. So here you can see we have here an image that looks like the number six. And if you type over here also for example four then it will generate here some numbers that looks like four. So you can see here you can see here we have four number four. Okay. And let's go move on to the next step. And then I saved my model into some files by going import OS osmake directories. So create a directory called checkpoints and then set the parameter exist okay equals true. Then save the model dot state dictionary inside this file that has extension. PT and also save this model the model weights save it into a file with the extension PTH. So PyTorch and then I saved it. You can see here we have here the model the model saved. If you go to here, you can see I have here two files. The first has the name texttodigit function_mnest.pt so PyTorch and the second is text to digit diffusion emnest. Pth and they are they are all the same. So differing with different extensions but they represent the same set of weights because remember PyTorch library supports two different types of extensions PT and PTH and they are considered the same. Then we have here you can see model.load set load set dictionary then pass into here the function torch.load and then pass here one of these files the path that that is pointing to one of these files. it will load in the weights and create a new instance of the model with the same set of the weights as our trained model earlier. And here we have also the function of the of the loaded model. If you pass here the number for example number one then it will generate some images that is representing the number one that is representing number one. And if you pass here for example eight it will generate the number eight. You can see here we have some images that looks like number eight. Let's move on to here. And then we have some function to normalize input. So you pass in some text. Then we have here return the text and also raise some value error. Please enter a number. So if you don't provide the number, it will raise an error. Then we have also here you can see a function gradio generate that creates some try and accept block. So try word then normalize the text except exception. We have if you have some error then return none and return the string of the error and also here we are returning the image and returning a string indicating that generated digit as word and at the last we created a gradio interface that takes from me a gradio interface the input in the form of a text box. We enter some text and then the model tries to generate and convert this text into an image and then it returns that that output in the form of image and you can see the label as generated emnest digit type equals numpy and then if we provide here a number for example number two submit then it here number two you can see it tries to generate number two and if you provide here one submit it tries to join number one. So you can see here we have one submit again one and if you provide for example number six it tries to join number six. So you can see some images looks like number six. Okay you can see here we have number six. Now let's move on to the next step where here we have built also another grid interface but using the manual way of doing that. Now let's move on to the next step. So once you train a model once you have a model and build it train it you have to construct a file that is called model.python model.python this file will instantiate the backbone architecture of your model. So here you have the same code as the unit class before but we have put it inside a separate notebook file inside a separate cell and then you can and you can see here after that we have defined a function called create diffusion model. This function takes from me several parameters that sets the values the default values for the for some hyperparameters. And these hyperparameters will be defined and used inside the architecture here the unit. For example, embedding dimension number of classes, time steps and whatever hypamearameters you need to set. At the last or finally we return a a a version of the model with no in weights just a model the model architecture. And also we need a file then feel free to go ahead and file download and then download file in the form of python. So you have to have a copy or you need to have a copy with the extension with the extension python that is containing a python script that creates for you a model architecture a plain model architecture without any weights. Then we plug those weights to this model architecture. And here we have a notebook called app.py.i python notebook. This is also a notebook that contains some code for constructing the app for gradial. So here we are putting all the code together. So you can see we are from model. So from this module model from this sub package called model please go ahead and import the function create diffusion model. And that's it. This is our function create diffusion model. So we are keeping our code here neat, beautiful and easy to organize. So from model import this function also from time it import default timer as timer because we need to time our model uh our model time the time it takes to make a prediction or to gener image and also from typing importable and then we have here CUDA device to set the device as CUDA if if CUDA is available otherwise it set it as CPU and we have the same logical code as you can see but at the last we are creating the grad interface you can See here we have gradio.inface then pass function equals predict inputs as a textbox label into some digit and we have outputs in the form of an image then we have this gradual interface. So here we have a file for training and building the model and also we have a notebook for storing in a code that instantiates the model architecture and here we have a file or app. Python that contains all the code and combines it into one file to create and instantiate an app for hugging face spaces to work properly and to work in a proper way. Here you have to go file and then download then download this file in the form of Python. Then you you have to have a folder called for example diffusion or whatever name you would like. This diffusion folder will contain the app.python Python that we saw earlier. Also, it will contain model.py. So, you can see we have the file app.python. Also, we have model.python that contains a code to create an object of the model to create an instance of the model. And also, we have a file, a special file special called requirements. .txt that contains the requirements and the necessary libraries that you need to require when your Gradial app runs. So when your hugging face runs, it will require some libraries, some packages, some modules to be installed. And here you are telling hugging face, hey hugging face, I will upload to you this model. Please make sure you have these libraries installed already. Torch with this version, torch vision with this version 0.24 and gradio with this version 550.0. And also here we have a two files. Actually you don't need two files but here we are providing hugging face with two files. The first ends with the extension PTH and the second ends with the extension PT. They are all the same. Feel free to choose whatever you preferring. If you prefer PTH, use that. If you prefer PT, use that. You don't need to have two files. But here we have the weights. We plug these weights to the architecture. Then we trigger that code inside the app. And we have some requirements to tell Gradio and hugging face that we require these libraries to be installed in order for our app to work in a proper way. Let's continue with our prompts to deploy our app or our model to hugging face spaces. First you can see we are inside the directory my diffusion_model that we have that we have done earlier. Let's go ahead and ls so list everything inside the dot dot slashd downloads slashde diffusion. So the the diffusion directory and it will show us what is the content inside the diffusion directory. You can see we have app model requirements txt text dot_2 digit diffusion model_mnest.pytorch and the other extension. PTH the same files that we have inside our diffusion directory inside downloads. So remember I downloaded these files so they are now exist in the downloads directory and it should be the same. Now let's move on to the next step where we have to go to copy these files. So remember currently if you do ls it will show here nothing. Let's go ahead and copy. So we have to get get clone. Then we have to pass in the path of the repo of the hugging face. We can go here app and then we can copy this URL. Go into my command line. You can see now once I do ls here we have nothing. But once we get clone and then pass in my path of the repo and then clone the repo. You can see now it's cloning into diffusion-model. And you can see here we have also enumerating objects. And now once we go ls now we have this folder which is called diffusion-model. And if you go change directory diffusion-model it will direct us to that directory and we have we could have ls and it will show us that now we have cloned our repo and you can see here currently my repo just contains two files readme.md.get attributes and they are showed over here. You can see now we have these two files readme and get attributes. So we have cloned our ribbo successfully. Let's go ahead and clear my page and move on to the next step. Now the next step is remember that ls do/d downloads. So I need now double then we go downloads /deusion. I have here the contents app model. I need to part to copy these contents and paste them over the diffusion-model directory by going cp short for copy-r recursively and we have here dot dot slash dot dot slash downloads and then we have here / diffusion and then move everything inside the diffusion by putting star then space dot. So we move everything here into our current working directory that is representing the fusion-model directory or folder. Let's go ahead. You can see now it's copied it successfully. And if you go and show ls now hooray, we have app.python model.python readme.markdown requirements.txt and my weights files. So now we have got all the necessary parts, the necessary files that we need to run our gradio app on hugging face. Now all we have to do is just go ahead and try to uh try to commit or push these files into hugging face. So the first thing is go get space remote-v. So what is my remote origin? What is my origin? You can see here I have origin https/huggingface.co. cospaces/my username/defusion-model and we have two permissions available. We have fetch. So the permission fetch and also push you can also push to the hugging face spaces and here you can also go ahead and get lfs dash lfs and then install. So we need the get lfs. Why? Because currently my file my model file is larger than 1 mgabyte. So if you have large files at least they are above 1 megaby or above 10 megabytes you need to install the lfs package by going to Google and then get LFS installed. If you don't have it already you can install the gfs. You can see get large file storage an open-source git extension for versioning large files. And you can download that from here to be able to upload large files onto hugging face. And you can see here you can go easily get LFS large file storage install. Then we can also get uh track get LFS track and then have this file. So let's move on to our command line. Get LFS install. You can see now I have it already installed. Updated git hooks get LFS initialized. And you can track files easily by doing this get space LFS then track track every file for example my model file and we can go here to my here folder and then copy the name of the of the model file. So remember we don't need the model python but rather the weights file because the weights file could get large and large. Then we can go here and paste and paste it over here. Now we can go you can see now get LFS track. You can see here the path phth is tracking text to digit diffusion_mness. PTH. So now our model file weights is tracked in a proper way. We can move ahead and also uh continue with the prompt. So get space lfs track every single file that ends in the extension. PTH we can go ahead and you can see PTH is already supported. So now we have we have tracked our files. We can go ahead and do the next step. Get add.get attributes and feel free to read here into the documentation. You can see here we have also get add.get attributes. You can run that command and it will execute over here. You can see here we can run and it added the get attributes and also let's get add star. So add everything and then if you check the status by going get status or status you can see now all our all of our files are green that means we have tracked every single file we have inside our folder diffusion-model. So now all we need to do is just go ahead and commit that by going get commit and then here dash m. So pose a message or send a message that says initial commit. So feel free to read here to put here or write here whatever message you want to put or write but in the in the first commit let's keep it simple and write here initial commit. You can see now it will commit that to the hugging face and then let's go ahead and get push. It will push that to the hugging face spaces. You can see now it's trying to push my files and now it's uploading. So keep in mind sometimes it will ask you for a token ID or a token that you need to provide here and that is easy. All you have to do is just write the command get remote and then set URL. So you can go get and then write here remote set dash URL then pass into here origin https and then put here your username. So your user dash name you can put here whatever username you have. Then we have colon token. So here you can replace the token your token ID at huggingface.co/reopath. And keep in mind this repo path should contain your us your spaces like that spaces slash your username slash your repo name like that. Okay. Then you can run that and it will ask you to provide the the token and it will authenticate and also then you can run the next command which is which says get pull origin and it will push your files into hugging face spaces. With that being said now we have we have done we've done we are done with the command line. Let's go to here and check our you can see now our hugging face is now starting. You can see now it's starting and trying to start and launch our app on hugging face spaces. So it might take some minutes for example 2 minutes to 30 minutes to to 3 minutes and you have to wait until it finishes building and starting then you then you can be able or then you can review your app and view it and also actually start using it. Now you can see my gr my hugging face is now running successfully. We don't have any errors. We don't have any issues. Everything has run smoothly. And if you go to your username here, you can see we have now many spaces. And our space that we have done in this section or in this course is this space diffusion model. Diffusion model to generate eminent numbers. And if you click on it, you can see uh it is committed 4 minutes ago or it has run for 4 minutes now ago. And here we have running. You can see now my ripple or my hugging face is now running smoothly. And this is my dashboard or this is my grandio interface. Here we have some input text box where you can write here a human readable number name for example three or for example one. Then you can go ahead and submit it and it will generate here some numbers. As you can see submit again if you pass here three submit it tries to write here the uh it's it tries to draw the number three you can see here it's trying to draw number three and if you pass here number four for example submit you can see now it is trying to draw number four and if you pass here two for example it tries to draw or to write number two. So this is my diffusion model. You can see here it wrote or it draw here number two. And feel free to upscale this model to train it further or to upscale the architecture or even use transfer learning techniques to better make this model work properly. Okay. And here you can see we have the the generation time in seconds. So you can you can see here every time we generate here we have a differing amount of time that the model has taken to produce or to draw this image. Here we have the generation time as 0.34. And if you pass here for example number six it also will generate and submit number six. You can see a draw number six an image that looks like number six. Okay. Now let's move on to you can see here my gradual interface. now is working properly and that's it. That's how you can upload and also here we have the share via link. You can you have the ability to share this app or to share this gradio interface via a link. You can go here, open this link and it will direct you to the same gradio web interface hosted on the on hugging face spaces and you can see it belongs to my username my account and it's named diffusion-model and currently I have here zero likes hopefully give me a like here and then we have this text box and it draws some our output image here and then also I have some other spaces here that I would like you to see if you Go to hugging face and then my account. You can see here I have so many spaces. I have the generation space GANs model food vision big and also I have food vision mini. Let's go to food vision big. Now you can see my my app here or my grado interface is working smoothly. You can see it's running and here we have this area where you can drop in here an image and it will classify this image for you into 101 different classes of food categories. If we submit it here we have pizza and also if we grab another image for example you can see here I have examples. If you choose it it will use that example to demonstrate how the the workflow works. And if you go to Google and search over here trau for example images it will show you some tiramisu images. Let's copy let's drag some of these images and drop it over there. We can go like that. Drag it. Drop over here. Drop the image here. You can see now we have a term image. We can go and submit it. Then it classified that as termisu. That's it. I hope you find this tutorial helpful and thanks for watching.

Generated algorithmically for Search Engine Indexing.

Summarize Another Video