Do you want to build your own AI Text-to-Image Generator in less than 15 minutes? Join me as I'll walk you through the process of building one using Stable Diffusion within Visual Studio Code!
Prerequisites
Before you start, ensure you have the following:
Step 1: Set Up the Development Environment
In your project directory, create a file named requirements.txt and add the following dependencies to the file:
certifi==2022.9.14 \ncharset-normalizer==2.1.1 \ncolorama==0.4.5 \ncustomtkinter==4.6.1 \ndarkdetect==0.7.1 \ndiffusers==0.3.0 \nfilelock==3.8.0 \nhuggingface-hub==0.9.1 \nidna==3.4 \nimportlib-metadata==4.12.0 \nnumpy==1.23.3 \npackaging==21.3 \nPillow==9.2.0 \npyparsing==3.0.9 \nPyYAML==6.0 \nregex==2022.9.13 \nrequests==2.28.1 \ntk==0.1.0 \ntokenizers==0.12.1 \ntorch==1.12.1+cu113 \ntorchaudio==0.12.1+cu113 \ntorchvision==0.13.1+cu113 \ntqdm==4.64.1 \ntransformers==4.22.1 \ntyping_extensions==4.3.0 \nurllib3==1.26.12 \nzipp==3.8.1
To install the listed dependencies in the requirements.txt file, run the following command in your terminal:
pip install -r requirements.txt
Step 2: Configure Authentication
In your project directory, create a file named authtoken.py and add the following code to the file:
auth_token = \"ACCESS TOKEN FROM HUGGING FACE\"
To obtain access token from Hugging Face, follow these steps:
Step 3: Develop the Application
In your project directory, create a file named application.py and add the following code to the file:
# Import the Tkinter library for GUI\nimport tkinter as tk\n\n# Import the custom Tkinter library for enhanced widgets\nimport customtkinter as ctk \n\n# Import PyTorch for handling tensors and model\nimport torch \n\n# Import the Stable Diffusion Pipeline from diffusers library\nfrom diffusers import StableDiffusionPipeline \n\n# Import PIL for image handling\nfrom PIL import Image, ImageTk \n\n# Import the authentication token from a file\nfrom authtoken import auth_token \n\n\n# Initialize the main Tkinter application window\napp = tk.Tk()\n\n# Set the size of the window\napp.geometry(\"532x632\") \n\n# Set the title of the window\napp.title(\"Text-to-Image Generator\") \n\n# Set the appearance mode of customtkinter to dark\nctk.set_appearance_mode(\"dark\") \n\n# Create an entry widget for the prompt text input\nprompt = ctk.CTkEntry(height=40, width=512, text_font=(\"Arial\", 20), text_color=\"black\", fg_color=\"white\")\n\n# Place the entry widget at coordinates (10, 10)\nprompt.place(x=10, y=10) \n\n# Create a label widget for displaying the generated image\nlmain = ctk.CTkLabel(height=512, width=512)\n\n# Place the label widget at coordinates (10, 110)\nlmain.place(x=10, y=110) \n\n# Define the model ID for Stable Diffusion\nmodelid = \"CompVis/stable-diffusion-v1-4\" \n\n# Define the device to run the model on\ndevice = \"cpu\" \n\n# Load the Stable Diffusion model pipeline\npipe = StableDiffusionPipeline.from_pretrained(modelid, revision=\"fp16\", torch_dtype=torch.float32, use_auth_token=auth_token)\n\n# Move the pipeline to the specified device (CPU)\npipe.to(device) \n\n# Define the function to generate the image from the prompt\ndef generate():\n\n # Disable gradient calculation for efficiency\n with torch.no_grad(): \n \n # Generate the image with guidance scale\n image = pipe(prompt.get(), guidance_scale=8.5)[\"sample\"][0] \n\n # Convert the image to a PhotoImage for Tkinter\n img = ImageTk.PhotoImage(image) \n\n # Keep a reference to the image to prevent garbage collection\n lmain.image = img \n\n # Update the label widget with the new image\n lmain.configure(image=img) \n\n# Create a button widget to trigger the image generation\ntrigger = ctk.CTkButton(height=40, width=120, text_font=(\"Arial\", 20), text_color=\"white\", fg_color=\"black\", command=generate)\n\n# Set the text on the button to \"Generate\"\ntrigger.configure(text=\"Generate\") \n\n# Place the button at coordinates (206, 60)\ntrigger.place(x=206, y=60) \n\n# Start the Tkinter main loop\napp.mainloop()
To run the application, execute the following command in your terminal:
python application.py
This will launch the GUI where you can enter a text prompt and generate corresponding images by clicking the Generate button.
Congratulations! You have successfully built an AI Text-to-Image Generator using Stable Diffusion in Visual Studio Code. Feel free to explore and enhance the application further by adding new features and improving the user interface. Happy coding!
Do you want to build your own AI Text-to-Image Generator in less than 15 minutes? Join me as I'll walk you through the process of building one using Stable Diffusion within Visual Studio Code!
Prerequisites
Before you start, ensure you have the following:
Step 1: Set Up the Development Environment
In your project directory, create a file named requirements.txt and add the following dependencies to the file:
certifi==2022.9.14 \ncharset-normalizer==2.1.1 \ncolorama==0.4.5 \ncustomtkinter==4.6.1 \ndarkdetect==0.7.1 \ndiffusers==0.3.0 \nfilelock==3.8.0 \nhuggingface-hub==0.9.1 \nidna==3.4 \nimportlib-metadata==4.12.0 \nnumpy==1.23.3 \npackaging==21.3 \nPillow==9.2.0 \npyparsing==3.0.9 \nPyYAML==6.0 \nregex==2022.9.13 \nrequests==2.28.1 \ntk==0.1.0 \ntokenizers==0.12.1 \ntorch==1.12.1+cu113 \ntorchaudio==0.12.1+cu113 \ntorchvision==0.13.1+cu113 \ntqdm==4.64.1 \ntransformers==4.22.1 \ntyping_extensions==4.3.0 \nurllib3==1.26.12 \nzipp==3.8.1
To install the listed dependencies in the requirements.txt file, run the following command in your terminal:
pip install -r requirements.txt
Step 2: Configure Authentication
In your project directory, create a file named authtoken.py and add the following code to the file:
auth_token = \"ACCESS TOKEN FROM HUGGING FACE\"
To obtain access token from Hugging Face, follow these steps:
Step 3: Develop the Application
In your project directory, create a file named application.py and add the following code to the file:
# Import the Tkinter library for GUI\nimport tkinter as tk\n\n# Import the custom Tkinter library for enhanced widgets\nimport customtkinter as ctk \n\n# Import PyTorch for handling tensors and model\nimport torch \n\n# Import the Stable Diffusion Pipeline from diffusers library\nfrom diffusers import StableDiffusionPipeline \n\n# Import PIL for image handling\nfrom PIL import Image, ImageTk \n\n# Import the authentication token from a file\nfrom authtoken import auth_token \n\n\n# Initialize the main Tkinter application window\napp = tk.Tk()\n\n# Set the size of the window\napp.geometry(\"532x632\") \n\n# Set the title of the window\napp.title(\"Text-to-Image Generator\") \n\n# Set the appearance mode of customtkinter to dark\nctk.set_appearance_mode(\"dark\") \n\n# Create an entry widget for the prompt text input\nprompt = ctk.CTkEntry(height=40, width=512, text_font=(\"Arial\", 20), text_color=\"black\", fg_color=\"white\")\n\n# Place the entry widget at coordinates (10, 10)\nprompt.place(x=10, y=10) \n\n# Create a label widget for displaying the generated image\nlmain = ctk.CTkLabel(height=512, width=512)\n\n# Place the label widget at coordinates (10, 110)\nlmain.place(x=10, y=110) \n\n# Define the model ID for Stable Diffusion\nmodelid = \"CompVis/stable-diffusion-v1-4\" \n\n# Define the device to run the model on\ndevice = \"cpu\" \n\n# Load the Stable Diffusion model pipeline\npipe = StableDiffusionPipeline.from_pretrained(modelid, revision=\"fp16\", torch_dtype=torch.float32, use_auth_token=auth_token)\n\n# Move the pipeline to the specified device (CPU)\npipe.to(device) \n\n# Define the function to generate the image from the prompt\ndef generate():\n\n # Disable gradient calculation for efficiency\n with torch.no_grad(): \n \n # Generate the image with guidance scale\n image = pipe(prompt.get(), guidance_scale=8.5)[\"sample\"][0] \n\n # Convert the image to a PhotoImage for Tkinter\n img = ImageTk.PhotoImage(image) \n\n # Keep a reference to the image to prevent garbage collection\n lmain.image = img \n\n # Update the label widget with the new image\n lmain.configure(image=img) \n\n# Create a button widget to trigger the image generation\ntrigger = ctk.CTkButton(height=40, width=120, text_font=(\"Arial\", 20), text_color=\"white\", fg_color=\"black\", command=generate)\n\n# Set the text on the button to \"Generate\"\ntrigger.configure(text=\"Generate\") \n\n# Place the button at coordinates (206, 60)\ntrigger.place(x=206, y=60) \n\n# Start the Tkinter main loop\napp.mainloop()
To run the application, execute the following command in your terminal:
python application.py
This will launch the GUI where you can enter a text prompt and generate corresponding images by clicking the Generate button.
Congratulations! You have successfully built an AI Text-to-Image Generator using Stable Diffusion in Visual Studio Code. Feel free to explore and enhance the application further by adding new features and improving the user interface. Happy coding!
Awesome
","body@stripHtml({\"removeProcessingText\":false,\"removeSpoilerMarkup\":false,\"removeTocMarkup\":false,\"truncateLength\":200})@stringLength":"9","kudosSumWeight":0,"repliesCount":0,"postTime":"2025-03-30T10:37:09.696-07:00","lastPublishTime":"2025-03-30T10:37:09.696-07:00","metrics":{"__typename":"MessageMetrics","views":63},"visibilityScope":"PUBLIC","placeholder":false,"originalMessageForPlaceholder":null,"isEscalated":null,"solution":false,"entityType":"FORUM_REPLY","eventPath":"category:AI/category:solutions/category:communities/community:gxcuf89792board:Azure-AI-Services/message:4228094/message:4398850","replies":{"__typename":"MessageConnection","pageInfo":{"__typename":"PageInfo","hasNextPage":false,"endCursor":null,"hasPreviousPage":false,"startCursor":null},"edges":[]},"customFields":[],"attachments":{"__typename":"AttachmentConnection","edges":[],"pageInfo":{"__typename":"PageInfo","hasNextPage":false,"endCursor":null,"hasPreviousPage":false,"startCursor":null}}},"CachedAsset:text:en_US-components/community/Navbar-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/community/Navbar-1745505307000","value":{"community":"Community Home","inbox":"Inbox","manageContent":"Manage Content","tos":"Terms of Service","forgotPassword":"Forgot Password","themeEditor":"Theme Editor","edit":"Edit Navigation Bar","skipContent":"Skip to content","gxcuf89792":"Tech Community","external-1":"Events","s-m-b":"Nonprofit Community","windows-server":"Windows Server","education-sector":"Education Sector","driving-adoption":"Driving Adoption","Common-content_management-link":"Content Management","microsoft-learn":"Microsoft Learn","s-q-l-server":"Content Management","partner-community":"Microsoft Partner Community","microsoft365":"Microsoft 365","external-9":".NET","external-8":"Teams","external-7":"Github","products-services":"Products","external-6":"Power Platform","communities-1":"Topics","external-5":"Microsoft Security","planner":"Outlook","external-4":"Microsoft 365","external-3":"Dynamics 365","azure":"Azure","healthcare-and-life-sciences":"Healthcare and Life Sciences","external-2":"Azure","microsoft-mechanics":"Microsoft Mechanics","microsoft-learn-1":"Community","external-10":"Learning Room Directory","microsoft-learn-blog":"Blog","windows":"Windows","i-t-ops-talk":"ITOps Talk","external-link-1":"View All","microsoft-securityand-compliance":"Microsoft Security","public-sector":"Public Sector","community-info-center":"Lounge","external-link-2":"View All","microsoft-teams":"Microsoft Teams","external":"Blogs","microsoft-endpoint-manager":"Microsoft Intune","startupsat-microsoft":"Startups at Microsoft","exchange":"Exchange","a-i":"AI and Machine Learning","io-t":"Internet of Things (IoT)","Common-microsoft365-copilot-link":"Microsoft 365 Copilot","outlook":"Microsoft 365 Copilot","external-link":"Community Hubs","communities":"Products"},"localOverride":false},"CachedAsset:text:en_US-components/community/NavbarHamburgerDropdown-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/community/NavbarHamburgerDropdown-1745505307000","value":{"hamburgerLabel":"Side Menu"},"localOverride":false},"CachedAsset:text:en_US-components/community/BrandLogo-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/community/BrandLogo-1745505307000","value":{"logoAlt":"Khoros","themeLogoAlt":"Brand Logo"},"localOverride":false},"CachedAsset:text:en_US-components/community/NavbarTextLinks-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/community/NavbarTextLinks-1745505307000","value":{"more":"More"},"localOverride":false},"CachedAsset:text:en_US-components/authentication/AuthenticationLink-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/authentication/AuthenticationLink-1745505307000","value":{"title.login":"Sign In","title.registration":"Register","title.forgotPassword":"Forgot Password","title.multiAuthLogin":"Sign In"},"localOverride":false},"CachedAsset:text:en_US-components/nodes/NodeLink-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/nodes/NodeLink-1745505307000","value":{"place":"Place {name}"},"localOverride":false},"CachedAsset:text:en_US-components/messages/EscalatedMessageBanner-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/EscalatedMessageBanner-1745505307000","value":{"escalationMessage":"Escalated to Salesforce by {username} on {date}","viewDetails":"View Details","modalTitle":"Case Details","escalatedBy":"Escalated by: ","escalatedOn":"Escalated on: ","caseNumber":"Case Number: ","status":"Status: ","lastUpdateDate":"Last Update: ","automaticEscalation":"automatic escalation","anonymous":"Anonymous"},"localOverride":false},"CachedAsset:text:en_US-components/users/UserLink-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/users/UserLink-1745505307000","value":{"authorName":"View Profile: {author}","anonymous":"Anonymous"},"localOverride":false},"CachedAsset:text:en_US-shared/client/components/users/UserRank-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-shared/client/components/users/UserRank-1745505307000","value":{"rankName":"{rankName}","userRank":"Author rank {rankName}"},"localOverride":false},"CachedAsset:text:en_US-components/messages/MessageTime-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/MessageTime-1745505307000","value":{"postTime":"Published: {time}","lastPublishTime":"Last Update: {time}","conversation.lastPostingActivityTime":"Last posting activity time: {time}","conversation.lastPostTime":"Last post time: {time}","moderationData.rejectTime":"Rejected time: {time}"},"localOverride":false},"CachedAsset:text:en_US-components/messages/MessageSolvedBadge-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/MessageSolvedBadge-1745505307000","value":{"solved":"Solved"},"localOverride":false},"CachedAsset:text:en_US-components/messages/MessageSubject-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/MessageSubject-1745505307000","value":{"noSubject":"(no subject)"},"localOverride":false},"CachedAsset:text:en_US-components/messages/MessageBody-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/MessageBody-1745505307000","value":{"showMessageBody":"Show More","mentionsErrorTitle":"{mentionsType, select, board {Board} user {User} message {Message} other {}} No Longer Available","mentionsErrorMessage":"The {mentionsType} you are trying to view has been removed from the community.","videoProcessing":"Video is being processed. Please try again in a few minutes.","bannerTitle":"Video provider requires cookies to play the video. Accept to continue or {url} it directly on the provider's site.","buttonTitle":"Accept","urlText":"watch"},"localOverride":false},"CachedAsset:text:en_US-components/messages/MessageCustomFields-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/MessageCustomFields-1745505307000","value":{"CustomField.default.label":"Value of {name}"},"localOverride":false},"CachedAsset:text:en_US-shared/client/components/common/QueryHandler-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-shared/client/components/common/QueryHandler-1745505307000","value":{"title":"Query Handler"},"localOverride":false},"CachedAsset:text:en_US-components/messages/MessageReplyButton-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/MessageReplyButton-1745505307000","value":{"repliesCount":"{count}","title":"Reply","title@board:BLOG@message:root":"Comment","title@board:TKB@message:root":"Comment","title@board:IDEA@message:root":"Comment","title@board:OCCASION@message:root":"Comment"},"localOverride":false},"CachedAsset:text:en_US-components/community/NavbarDropdownToggle-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/community/NavbarDropdownToggle-1745505307000","value":{"ariaLabelClosed":"Press the down arrow to open the menu"},"localOverride":false},"CachedAsset:text:en_US-shared/client/components/users/UserAvatar-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-shared/client/components/users/UserAvatar-1745505307000","value":{"altText":"{login}'s avatar","altTextGeneric":"User's avatar"},"localOverride":false},"CachedAsset:text:en_US-shared/client/components/ranks/UserRankLabel-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-shared/client/components/ranks/UserRankLabel-1745505307000","value":{"altTitle":"Icon for {rankName} rank"},"localOverride":false},"CachedAsset:text:en_US-components/messages/MessageListMenu-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/MessageListMenu-1745505307000","value":{"postTimeAsc":"Oldest","postTimeDesc":"Newest","kudosSumWeightAsc":"Least Liked","kudosSumWeightDesc":"Most Liked","sortTitle":"Sort By","sortedBy.item":" { itemName, select, postTimeAsc {Oldest} postTimeDesc {Newest} kudosSumWeightAsc {Least Liked} kudosSumWeightDesc {Most Liked} other {}}"},"localOverride":false},"CachedAsset:text:en_US-components/messages/AcceptedSolutionButton-1745505307000":{"__typename":"CachedAsset","id":"text:en_US-components/messages/AcceptedSolutionButton-1745505307000","value":{"accept":"Mark as Solution","accepted":"Marked as Solution","errorHeader":"Error!","errorAdd":"There was an error marking as solution.","errorRemove":"There was an error unmarking as solution.","solved":"Solved","topicAlreadySolvedErrorTitle":"Solution Already Exists","topicAlreadySolvedErrorDesc":"Refresh the browser to view the existing solution"},"localOverride":false}}}},"page":"/forums/ForumMessagePage/ForumMessagePage","query":{"boardId":"azure-ai-services","messageSubject":"how-to-build-your-own-ai-text-to-image-generator","messageId":"4228094"},"buildId":"-gVUpXaWnPcjlrLJZ92B7","runtimeConfig":{"buildInformationVisible":false,"logLevelApp":"info","logLevelMetrics":"info","openTelemetryClientEnabled":false,"openTelemetryConfigName":"o365","openTelemetryServiceVersion":"25.3.0","openTelemetryUniverse":"prod","openTelemetryCollector":"http://localhost:4318","openTelemetryRouteChangeAllowedTime":"5000","apolloDevToolsEnabled":false,"inboxMuteWipFeatureEnabled":false},"isFallback":false,"isExperimentalCompile":false,"dynamicIds":["./components/seo/QAPageSchema/QAPageSchema.tsx","./components/community/Navbar/NavbarWidget.tsx","./components/community/Breadcrumb/BreadcrumbWidget.tsx","./components/customComponent/CustomComponent/CustomComponent.tsx","./components/messages/TopicWithThreadedReplyListWidget/TopicWithThreadedReplyListWidget.tsx","./components/messages/MessageView/MessageViewStandard/MessageViewStandard.tsx","./components/messages/ThreadedReplyList/ThreadedReplyList.tsx","./components/external/components/ExternalComponent.tsx","./components/customComponent/CustomComponentContent/TemplateContent.tsx","../shared/client/components/common/List/UnstyledList/UnstyledList.tsx","./components/messages/MessageView/MessageView.tsx"],"appGip":true,"scriptLoader":[{"id":"analytics","src":"https://techcommunity.microsoft.com/t5/s/gxcuf89792/pagescripts/1730819800000/analytics.js?page.id=ForumMessagePage&entity.id=board%3Aazure-ai-services&entity.id=message%3A4228094","strategy":"afterInteractive"}]}/discussions/microsoft-intune/how-to-deploy-applications-on-demand-to-only-a-few-users-or-devices/3885483