Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

How-To Tutorials - ChatGPT

113 Articles
article-image-implementing-azure-ad-protection-with-chatgpt
Steve Miles
15 Jun 2023
8 min read
Save for later

Implementing Azure AD Protection with ChatGPT

Steve Miles
15 Jun 2023
8 min read
IntroductionCybersecurity professionals face numerous challenges daily, from threat detection to incident response. The advent of AI-powered language models, also called Generative AI such as ChatGPT or Google's Bard, has revolutionized how experts approach their tasks. In this tutorial, we will explore how ChatGPT can assist cybersecurity professionals in performing various tasks efficiently and effectively. From analyzing logs and conducting risk assessments to developing incident response strategies, ChatGPT's capabilities can be harnessed to streamline workflows and enhance productivity. In this blog, let's dive into the practical applications and benefits of integrating Generative AI into (cyber)security operations.In this article, we will cover a tutorial on implementing Azure AD Protection with ChatGPT and also cover certain other areas of cybersecurity where GPT can be beneficial.Implementing Azure AD Identity Protection with ChatGPTAzure AD Identity Protection helps organizations safeguard their Azure Active Directory (Azure AD) identities by detecting and mitigating identity-related risks. In this section, we will explore how ChatGPT can assist in implementing Azure AD Identity Protection through code examples using Python and the Microsoft Graph API.1. Set up the EnvironmentBefore we begin, ensure that you have the following prerequisites in place:Python is installed on your machine.The requests library is installed. You can install it using the following command: pip install requests Azure AD application registered with the appropriate permissions to access Azure AD Identity Protection.2. Acquire Access TokenTo interact with the Microsoft Graph API, we must acquire an access token. Use the following Python code to obtain the access token:```python import requests # Azure AD application details tenant_id = 'YOUR_TENANT_ID' client_id = 'YOUR_CLIENT_ID' client_secret = 'YOUR_CLIENT_SECRET' # Microsoft Graph token endpoint token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token' # Request access token payload = {    'grant_type': 'client_credentials',    'client_id': client_id,    'client_secret': client_secret,    'scope': 'https://graph.microsoft.com/.default' } response = requests.post(token_url, data=payload) if response.status_code == 200:    access_token = response.json()['access_token'] else:    print('Error: Failed to obtain access token') ```Make sure to replace the placeholders with your Azure AD application details.3. Query Azure AD Identity Protection Data with ChatGPTNow that we have the access token, we can leverage ChatGPT to query Azure AD Identity Protection data. Use the following code example to interact with the model and retrieve identity protection insights:```python import openai openai.api_key = 'YOUR_OPENAI_API_KEY' def query_model(question):    response = openai.Completion.create(        engine='text-davinci-003',        prompt=question,        max_tokens=100,        temperature=0.5,        n=1,        stop=None,        temperature=0.5,    )    if response.choices:        return response.choices[0].text.strip()    else:        return None # Example question for querying Azure AD Identity Protection data question = "What are the recent risky sign-ins detected by Azure AD Identity Protection?" # Microsoft Graph API endpoint for risky sign-ins graph_api_url = 'https://graph.microsoft.com/v1.0/identityProtection/riskyUsers' # Send API request with the access token headers = {    'Authorization': f'Bearer {access_token}',    'Content-Type': 'application/json' } response = requests.get(graph_api_url, headers=headers) if response.status_code == 200:    risky_sign_ins = response.json()    # Process the response as needed    # ...    # Query the AI model for insights or recommendations    insights = query_model(question)    if insights:        print("Identity Protection Insights:")        print(insights)    else:        print("Error: Failed to obtain insights from the AI model") else:    print("Error: Failed to retrieve risky sign-ins data from Azure AD Identity Protection") ```Ensure you have appropriate permissions and update the `graph_api_url` with the relevant endpoint for the Azure AD Identity Protection data you want to retrieve.4. Interpret and Utilize InsightsOnce you obtain insights from the AI model, interpret, and utilize them to improve your identity protection practices. This could involve taking proactive measures to mitigate risks, investigating suspicious activities, or implementing additional security measures based on the recommendations provided.Remember to adapt the code examples based on your specific requirements and refer to the Microsoft Graph API documentation for available endpoints and data structures. https://learn.microsoft.com/en-us/graph/Other application areas1. Analyzing Log FilesOne of the most important aspects of cybersecurity is analyzing log files for suspicious activity and potential security breaches. Chat can help businesses automate this process. By importing log files into the model, ChatGPT can quickly identify patterns, anomalies, and potentially malicious activities. This analysis allows cybersecurity professionals to focus on the most important issues, saving valuable time and effort. In addition, ChatGPT's ability to create human-readable summaries of log data simplifies the interpretation and communication of findings for stakeholders.2. Conducting Risk AssessmentsConducting a comprehensive risk assessment is essential to understanding an organization's security posture. ChatGPT can help in this process by using its powerful capabilities to provide context and insights. By interacting with the model, organizations can ask specific questions about potential vulnerabilities, attacks, or best practices related to their risk assessments. ChatGPT's feedback provides knowledge of the organization's security environment and offers real value actionable insights that help businesses identify and prioritize risks and remediation tasks.3. Developing Incident Response StrategiesTime is of the essence in a cybersecurity incident. Generative AI can be an invaluable tool for developing effective incident response mechanisms. By leveraging its natural language processing capabilities, businesses can use ChatGPT to brainstorm and optimize response processes. The model can provide recommendations based on historical data, industry standards, and best practices, helping to create robust and efficient incident response systems. Generative AI can understand and generate human-like responses, making it an ideal virtual security analyst for cybersecurity professionals in high-pressure and time-sensitive situations.4. Automating Routine TasksCybersecurity professionals are often faced with increasing volume and velocity of repetitive and time-consuming tasks, such as vulnerability assessments, log analysis, and updating firewall rules. Generative AI can help automate these routine tasks, freeing experts to focus on complex real-value organizational security challenges. By integrating ChatGPT with existing automation frameworks, organizations can create chatbot-like interfaces that interact with the model to perform pre-defined actions. This approach increases productivity and reduces the risk of human error associated with manual processing.5. Enhancing Threat Intelligence AnalysisEffective threat reporting is essential for proactive cybersecurity defenses. Generative AI can enhance threat intelligence data analysis by extracting insights from a vast repository of security information. By asking about emerging threats, known vulnerabilities, or attack techniques, administrators can gain a deeper understanding of the ongoing threat landscape. ChatGPT's ability to understand complex security issues enhances the accuracy and relevance of threat intelligence reports, contributing to timely decision-making.ConclusionIn conclusion, it is easier and more efficient to implement Azure AD in conjunction with ChatGPT. As the cybersecurity landscape continues to evolve, businesses must embrace AI-powered solutions to stay ahead of malicious actors. Generative AI provides valuable support for various cybersecurity tasks, including log analysis, risk assessment, incident response planning, workflow automation, and threat intelligence analysis capabilities, enabling cybersecurity professionals to streamline their workflow, increase productivity, and make more informed decisions. While it is important to exercise proper judgment and credentials when implementing AI models, integrating Generative AI  such as ChatGPT into the cybersecurity industry offers significant opportunities for businesses to manage their tasks faster, more accurately, and more efficiently.Author BioSteve Miles (SMiles) is the CTO responsible for the tools and technologies selection for the cloud practice of a multi-billion turnover IT distributor based in the UK and Ireland. He is also a multi-cloud and hybrid technology strategist with 20+ years of telco, co-location, hosted data center, hybrid, and multi-cloud infrastructure experience. Steve is an Alibaba Cloud MVP (Most Valuable Professional), as well as being a Microsoft Azure MVP (Most Valuable Professional), and MCT (Microsoft Certified Trainer). Published freelance author for Microsoft technologies and certification guides, as well as an editorial and technical reviewer. Amongst many hybrid/cloud-based certifications, he is Alibaba Cloud Certified, with 20+ Cloud/Hybrid based Microsoft certifications with 14 of those being in Azure.His roles have included network security architect, global solutions architect, public cloud security solutions architect, and Azure practice technical lead. He currently works for a leading multi-cloud distributor based in the UK and Dublin in a cloud and hybrid technology leadership role.His first Microsoft certification was on Windows NT. He is an MCP, MCITP, MCSA, and MCSE for Windows Server and many other Microsoft products. He also holds multiple Microsoft Fundamentals, Associate, Expert, and Specialty certifications in Azure Security, Identity, Network, M365, and D365. He also holds multiple security and networking vendor certifications, as well as PRINCE2 and ITIL, and is associated with industry bodies such as the CIF, ISCA, and IISP.Author of the book: Azure Security Cookbook 
Read more
  • 0
  • 0
  • 176

article-image-adding-a-chatbot-to-your-portfolio-website-with-chatgpt
Maaike van Putten
13 Jun 2023
10 min read
Save for later

Adding a Chatbot to your Portfolio Website with ChatGPT

Maaike van Putten
13 Jun 2023
10 min read
This article is the second part of a series of articles, please refer to Part 1 for learning how to create a simple portfolio website using ChatGPT in a few stepsIn my last blog, we created a basic personal portfolio app for Olivia with ChatGPT. We’ll use this as the starting point for our next adventure. We’re going to be adding a simple chatbot to our website and configuring it to deal with certain questions. Of course, we could do this ourselves, but let’s see how we can utilize ChatGPT to accomplish this task faster. We’re going to do so with just four prompts! Let’s start with the end result, so you know what we’re working towards:Image 1: End result of the project In the right bottom corner, you see a pop-up that says Ask me anything. Well, you can’t ask it anything, but it can answer the following common questions:Where can I contact you?Can I contact you through Twitter?Can I contact you through LinkedIn?Where can I see your projects? Of course, we can elaborate and do even more with it. We actually wanted to use a free API for this, and we were stuck with CDN options due to the nature of our project. Luckily, we have a digital friend who has some options for us. Let’s see how this started.Deciding which service to use (with ChatGPT)It’s best to be quite descriptive when prompting. This is the first prompt that was used to start implementing the chatbot:I have an existing portfolio site, using HTML/CSS/JS. I'm not using any package managers, so any requirements will have to use a CDN. I want to add a chatbot to my site using a Natural Language AI. If it is possible I'd want the API I'll use to be free. Can you give me some options as to how I can achieve this? ChatGPT had some ideas: Certainly! There are several options available for adding a chatbot with Natural Language AI to your existing portfolio site using HTML/CSS/JS and integrating it through a CDN. Here are a few options that offer free plans: 1. IBM Watson Assistant: IBM Watson Assistant is a powerful NLP service that allows you to build chat bots. You can integrate it into your website using the Watson Assistant API. IBM offers a free tier that provides a limited number of API requests per month. You can find more information and documentation on the IBM Watson Assistant website. 2. Dialogflow (formerly API.AI): Dialogflow, now part of Google Cloud, offers a free tier that allows you to create conversational agents and integrate them into your website. Dialogflow provides a JavaScript library that you can use to communicate with the API. You can find documentation and examples on the Dialogflow website. 3. Wit.ai: Wit.ai, which is also owned by Facebook, provides a free NLP service for building chatbots. You can integrate it into your website using the Wit.ai API. Wit.ai offers a JavaScript SDK that you can use to interact with the API. You can find more information on the Wit.ai website. 4. Microsoft Azure Bot Service: Microsoft Azure Bot Service offers a free tier that allows you to create and deploy chatbots. You can use the Bot Service REST API to communicate with your bot from your website. Microsoft provides documentation and examples on its Azure Bot Service website. Remember to review the terms and limitations of the free plans for each service to ensure they meet your requirements. Additionally, be aware that some services may have usage limitations or require you to upgrade to a paid plan for higher usage levels or advanced features. Choose the option that best suits your needs, and refer to the respective documentation for implementation details specific to each service. After this, it was research time. This actually took a little while. IBM wasn’t properly explored, because the sign-up failed due to the Dutch valid phone number not passing validation. Azure seemed great, but a bit too advanced for what we needed right now. The chatbot service chosen was Wit.ai. On there we can sign up, get an access token and specify how to deal with certain inputs. After figuring that out and making a little code start ourselves. It was time to start adjusting the code with ChatGPT. Prompting for codeEnter the following prompt, to begin with: Alright, I set up a wit.ai project, and it seems to work. Now I have the following snippet:   <section id="chat-bot">    <h2>Ask me anything!</h2>    <input id="chat-prompt" type="text">  </section> I'd like to create a chatbot with this. I can write the responses myself, but can you for now create some JavaScript code that sends an HTTP request to the wit.ai server and parses the result? For now, just print it to the console. It gave us a great place to start and some additional implementation guidelines. We’ve only included the code snippet here:// Function to send the user's message to Wit.ai and parse the response async function sendMessage(message) { // Replace 'YOUR_WITAI_ACCESS_TOKEN' with your actual Wit.ai access token const accessToken = 'YOUR_WITAI_ACCESS_TOKEN'; const apiUrl = `https://api.wit.ai/message?v=20210525&q=${encodeURIComponent(message)}`; try {    const response = await fetch(apiUrl, {      headers: {        Authorization: `Bearer ${accessToken}`      }    });    if (response.ok) {      const data = await response.json();      console.log('Wit.ai Response:', data);      // Process the data and handle the response as needed      // For example, extract intents, entities, or generate appropriate responses    } else {      console.log('Request to Wit.ai failed with status:', response.status);    } } catch (error) {    console.log('An error occurred while communicating with Wit.ai:', error); } } // Event listener for handling user input const inputElement = document.getElementById('chat-prompt'); inputElement.addEventListener('keydown', async (event) => { if (event.key === 'Enter') {    const message = event.target.value.trim();    if (message) {      console.log('User Input:', message);      await sendMessage(message);      event.target.value = ''; // Clear the input field    } } }); It also instructed us to take the following steps:Replace YOUR_WITAI_ACCESS_TOKEN with our actual access tokenPress enter after typing your question and it then logs the response to the console Make sure to put the JavaScript code in the <script> tag This is what it looked like:Image 2: practical output after the first few prompts This was already quite good, but of course, we don’t want the response in the console, but displayed in the chat window. And the same goes for our previous questions, it should become a chat. Let’s see if we can move toward that.Making it into an actual conversationIt’s always a good idea to be specific in your prompt. You can see the following prompt does quite a bit of the heavy lifting and explains clearly what type of work is needed from ChatGPT. This helps to achieve the result: I've modified the HTML a little bit:   <section id="chat-bot">    <ol id="chat-history"></ol>    <h2>Ask me anything!</h2>    <input id="chat-prompt" type="text">  </section> Can you write some logic which can populate the `chat-history` element? I need 3 things: - A history as a JavaScript object- A function which can generate the content from the history- A function which can add the question, and the response, to the history in JavaScript For now just print the top intent and all the entities. This did quite a bit of the work already. You can see the result below, the history and the answers of the two questions asked appear on top of the input box.Image 3: Answers and history appearing on top of the Input box                        It’s no secret that I’m not a UX or design expert, but even I can see that this is not ideal. So let’s see if we can improve the design.Asking ChatGPT to Style the ChatbotLet’s see if we can improve the design. Normally chatbots are not on the top left, but the bottom right. Also, it would be nice if the history could go inside the box. Of course, we want to use the same orange as for the rest of our portfolio. Here’s the prompt: Can you generate some CSS to style the element? I'd like the following: - The chat should be at the bottom right of the page.- The chat should not impact the rest of the page.- Each question and response should have a chat bubble.- The theme color is #f37041.This gave us the CSS and some context as output. Here’s the CSS:#chat-bot { position: fixed; bottom: 20px; right: 20px; z-index: 9999; background-color: #f37041; color: #fff; font-family: Arial, sans-serif; border-radius: 5px; padding: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3); } #chat-history { list-style: none; margin: 0; padding: 0; max-height: 200px; overflow-y: auto; } .question, .response { display: inline-block; max-width: 80%; padding: 8px; border-radius: 10px; margin-bottom: 5px; } .question { background-color: #fff; color: #333; text-align: right; } .response { background-color: #f37041; color: #fff; text-align: left; } #chat-prompt { width: 100%; padding: 8px; margin-top: 10px; border: none; border-radius: 5px; } #chat-prompt:focus { outline: none; } #chat-prompt::placeholder { color: #ccc; } And this did quite the trick. Here’s what it looks like now: Image4: The final output If you’d like to see all the responses and the versions of the personal portfolio after each step, you can check out this GitHub repo: https://github.com/BrightBoost/portfolio-with-ai-prompt-chatgptSummaryIn conclusion, integrating a basic chatbot into your personal portfolio website can significantly enhance user engagement and provide a unique interactive experience. By leveraging GPT prompts, you can effortlessly develop a conversational AI agent that understands and responds to user queries. Adding this functionality not only showcases your technical skills but also demonstrates your ability to create dynamic and user-centric web experiences. So go ahead, implement a chatbot and elevate your portfolio website to the next level. Happy prompting!Author Bio Maaike van Putten is an experienced software developer and Pluralsight, LinkedIn Learning, Udemy, and Bright Boost instructor. She has a passion for software development and helping others get to the next level in their career.LinkedInTraining courses   
Read more
  • 0
  • 0
  • 1483

article-image-demystifying-and-getting-started-with-github-copilot
Rod Anami
13 Jun 2023
6 min read
Save for later

Demystifying and Getting Started with GitHub Copilot

Rod Anami
13 Jun 2023
6 min read
Suddenly, in a blink of an eye, we all started to talk about AI, with particular attention to Generative AI, which produces assets, including code. Not long ago, OpenAI released ChatGPT, which received the spotlight from the media and even interest from people outside IT because of its capacity to sustain a dialog with a human and bring very specialized knowledge to answer questions. Before we continue, as a disclaimer, AI did not generate this very article. In my previous post, I discussed that site reliability engineers (SREs) and other professionals used AI capabilities long before ChatGPT. Today I want to talk about an exciting application of AI to aid software engineers, developers, and SREs in coding with AI-powered pair programming. GitHub Copilot is one notorious example and is sold as an "AI pair programmer." It generates code based on the comments around the code's intention, and it's been gaining traction among the developer's ranks. By the end of this post, you will understand what's Copilot and how to start using it.Does it mean I don't need any development skills anymore?The short answer is not really. Unless the problem you're trying to resolve with code is simple enough to require a few functionalities, you must have solid software development abilities to complete the work, even with Copilot in the game. Copilot is an emerging coding productivity tool, not a no-code or low-code solution. Also, would you sell software that you wouldn't be able to explain how it works? Worse, would you buy software that no one knows how it works?How does it work?GitHub Copilot utilizes OpenAI Codex under the hood. Like ChatGPT, Codex is a descendant of the GPT-3 (third-generation Generative Pre-trained Transformer), a neural network machine learning model trained with data from the Internet and capable of generating any natural language text. On top of that, they used billions of code lines from public repositories to teach Codex. In essence, it can read natural language and forge lines of code in many languages, including "JavaScript, Go, Perl, PHP, Ruby, Swift and TypeScript, and even Shell," but it has more proficiency in Python.Codex possesses four proven coding capacities:Generation: it generates lines of code based on a description in natural languageTranspiration: transforms code written in one language to another one that has a similar level of abstractionExplanation: explains what a block of code does in detailRefactoring: improves the efficiency of a code block without modifying its original intentWith Copilot, it's possible to generate a new block of code by inserting a programming language comment with the description of the code logic. For example, if I type this comment in a JavaScript file:// A function that takes in a string and returns a string with the first letter capitalizedIt may suggest the following code snippet:function capitalizeFirstLetter(string) {        return string.charAt(0).toUpperCase() + string.slice(1);}Another usage is through code recommendations. For instance, it may suggest lines of code to complete an unfinished function or procedure.Will it spy on me?Not at all. According to the GitHub's privacy statement, "neither your Prompts nor Suggestions will be shared or used as suggested code for other users of GitHub Copilot." Of course, publishing your code and the comments used to generate code through Copilot on a public repository may defeat this data privacy.Will it generate the perfect code?No, it will construct a reasonable with minimum accuracy solution, but it does not necessarily mean the generated code perfectly fits your project requirements. You will need to validate if the Copilot recommendations make sense in the context of your project. Also, there's no guarantee the code suggestions are flawless or follow strict security and quality policies.Now that you have a basic understanding of Copilot let's enable it on your laptop. You will need a GitHub account and an integrated development environment (IDE) tool installed on your machine.Enable Copilot for your GitHub personal accountYou can sign up for free at this link if you don't have a GitHub personal account. I'm assuming you have one ready for the rest of the below instructions.Image 1: Copilot pageThe first task is enabling the Copilot feature for your GitHub account; you can do that by selecting one of the pricing plans here. When I wrote this article, there was a free trial option. Next, you need to indicate whether or not you want the code suggestions coming from public code and if Copilot can use your snippets to improve the model (re-train it).Install the Copilot module on your preferred IDEAfter you enable it for your GitHub account, the second task is to install Copilot into your preferred IDE. I'm using Microsoft Visual Studio Code (VS Code), but they provide a package for many other IDEs; you can see the list and specific installation procedure here. Also, if you want, you can download and install VS Code from this official website.Image 2: Copilot extensionFor the VS Code tool, the installation process is straightforward: Open VS Code and click on Extensions in the left navigation panel.Look for the "copilot" term and select the GitHub Copilot extensionUse your GitHub credentials if you don't have any VS Code extension for GitHub yetInstall it and make sure it's enabled globally.Start to experiment with Copilot for realAfter you have the Copilot extension, it's time to test it. Just open a project folder or create a new one.Then create a new file; you can name it after copilot-test.js. If you don't have the JavaScript extension, it will prompt you to install it. Let's craft a comment that will trigger Copilot to generate code. Enter the following statement:// A function that reads a JSON file and returns the number of fields in the JSON objectThen, hit the CTRL+Enter to see possible solutions in a separate window. By the way, you can see all the keyboard shortcuts in this document for VS Code. It can bring up to 10 possible recommendations. Check the one that matches your style and click on the "Accept Solution" link at the end of the section.ConclusionAlthough it may not be the full-fledged AI-fueled programmer we see in the movies, GitHub Copilot helps developers with the initial algorithms and basic coding patterns. It might benefit individual developers and entire companies if seen as a software development productivity tool instead of a mythic autonomous programmer bot.I hope you enjoyed this blog post, and if you liked it, please connect to me on LinkedIn or follow me on Twitter @ranami. Also, my book Becoming a Rockstar SRE is out.
Read more
  • 0
  • 0
  • 154

article-image-chatgpt-as-an-assistant-for-plc-programmers
M.T White
13 Jun 2023
10 min read
Save for later

ChatGPT as an Assistant for PLC Programmers

M.T White
13 Jun 2023
10 min read
ChatGPT has been making the rounds recently in the world of programming.  In short, there is a lot of hoopla about whether or not it will replace programmers, how well it writes code, how well it troubleshoots issues, and more importantly how programmers can leverage it to automate code production. One area where ChatGPT can be of particular use is in the field of automation.  As all automation programmers know, the automation industry is very fast-paced.  This means that being able to quickly produce quality code is vital to the success of not only the programmer but the company as a whole.  However, it is often the case that some of the simplest code that a developer will need to produce is often the most time-consuming to write.  Two areas that come to mind are large case statements and sorting algorithms.  As such, the following article is going to explore how ChatGPT can be used to produce code that would otherwise be monotonous or time-consuming to write.  More specifically, the following is going to explore how ChatGPT can be used to generate the necessary code for a case statement that displays a motor’s health and how it can be used to select and generate the code for a sorting algorithm to sort part sizes. A CASE Statement to Detect Motor HealthA very daunting and time-consuming task that all automation programmers will perform regularly is creating large case statements.  It is not uncommon for automation programmers to have to build things like state machines that have 10s or even 100s of different cases.  As anyone who has built these before knows, building structures like these is time-consuming and monotonous at best.  For example, suppose a developer is working on a function block that will display a custom message about a motor error in an HMI.  Assume in this example the developer needs a code block that can handle the input/output exchange for the following table,Input valueString Message1Cable Error2Motor Overheated3Under CurrentDepending on the experience level of the developer a simple case statement program that can handle the requirements would take about five minutes.  However, when there are more case statements, for example, 30 or 40 inputs, the timeframe for completion could drastically increase.  Simply put, since there are more cases there will be more code to write.  In turn, this means that it will take the developer more time to type out the code and there will be a higher probability of introducing a bug or bugs in the code due to human error.  On the other hand, to quickly generate a quality code block that can meet these requirements all one would need to do is enter the following into ChatGPT:write an IEC 61131-3 code block that will set a message variable to "cable error" when the input is 1, "motor overheated" when the input is 2, and "under current" when the input is 3This statement will output the following:FUNCTION_BLOCK SetMessage VAR_INPUT    Input: INT; // Input value END_VAR VAR_OUTPUT    Message: STRING(50); // Output message END_VAR METHOD SetMessage VAR    TempMessage: STRING(50); // Temporary message variable END_VAR CASE Input OF    1:        TempMessage := 'Cable error';    2:        TempMessage := 'Motor overheated';    3:        TempMessage := 'Under current';    ELSE        TempMessage := 'Invalid input'; // Optional: default message for other input values END_CASE Message := TempMessage; // Assign the temporary message to the output message END_METHOD From the time it took to input and run the query on ChatGPT to the final code output was about one minute.  The code that was generated is quality code that looks like it was produced by an experienced programmer, it is documented, and above all else works.  The code even has an optional else statement to catch invalid inputs.  Overall, the autogenerated code is no less than what would be expected from a human developer.  With that, let’s explore how ChatGPT can be used to generate a more complex piece of software.   An Efficient Sorting Algorithm to Sort Parts by SizeIt is not uncommon for developers to be tasked with finding the smallest/largest or lightest/heaviest part produced on a production run.  For a task like this, it is common to store all the sizes, weights, or whatever it may be in an array and at one point or another sort the array to find the greatest and least size.  Depending on the size of the array, or in the case of this scenario, the number of part sizes to sort, having an efficient array is vital.  For this task, an efficient sorting algorithm will need to be picked and the code will need to be implemented. Assuming the PLC programmer is knowledgeable of sorting algorithms and Big O notations selecting an algorithm may only take a few minutes.  However, for a PLC programmer that is not versed in these topics, such as a person that is perhaps and mechanical engineer or a technician of some type, this task will probably require a Google search which ideally will take about five minutes.  Regardless, of whether the programmer is experienced or not with the algorithm it will take roughly 10 to 20 minutes for the person to type in the code.  As such, on a good day, it would take roughly 10 to 25 minutes for someone to implement a sorting algorithm. On the other hand, if a person used ChatGPT all they would have to do is type in the following query:write an IEC 61131-3 Structured Text sorting algorithm that can sort the elements in an array with 100 entries with the best possible Big O timeWhich will generate the following:FUNCTION_BLOCK QuickSort VAR_INPUT    arr: ARRAY[1..100] OF INT; END_VAR METHOD SortArray : BOOL    SortPartition(arr, 1, 100);    SortArray := TRUE; END_METHOD METHOD SortPartition(arr: ARRAY[1..100] OF INT; low: INT; high: INT) VAR    pivot: INT;    partitionIndex: INT; END_VAR    IF low < high THEN        pivot := Partition(arr, low, high, low); // Choosing pivot as the first element        SortPartition(arr, low, pivot - 1);        SortPartition(arr, pivot + 1, high);    END_IF; END_METHOD METHOD Partition(arr: ARRAY[1..100] OF INT; low: INT; high: INT; pivotIndex: INT) : INT VAR    pivotValue: INT;    i: INT;    partitionIndex: INT;    temp: INT; END_VAR    // Swap pivot element to the end    temp := arr[high];    arr[high] := arr[pivotIndex];    arr[pivotIndex] := temp;    pivotValue := arr[high];    partitionIndex := low;    FOR i := low TO high - 1 DO        IF arr[i] <= pivotValue THEN            // Swap elements            temp := arr[i];            arr[i] := arr[partitionIndex];            arr[partitionIndex] := temp;            partitionIndex := partitionIndex + 1;        END_IF;    END_FOR;    // Move pivot element to its correct position    temp := arr[partitionIndex];    arr[partitionIndex] := arr[high];    arr[high] := temp;    Partition := partitionIndex; END_METHOD END_FUNCTION_BLOCKAll of this code was generated in about one minute.  As can be seen, ChatGPT generated roughly 60 lines of code not counting the code that utilizes the example.  The only overhead that would be required by the programmer is to create the necessary files and paste the code in.  In terms of efficiency, ChatGPT rendered the Quicksort algorithm which has a Big O of n*log(n).  So, in the end, the programmer is probably looking at around five minutes' worth of work to implement an efficient algorithm that would otherwise take up to half an hour by hand.The Key to using ChatGPTAs can be seen, the key to using ChatGPT as a programming assistant is simply learning to talk to it.  Unlike programming languages that have a unique syntax, ChatGPT can interpret normal, human language.  However, to get the most out of ChatGPT the programmer needs to learn to ask detailed questions. The general rule of thumb is the more detailed a statement is the more detailed the solution will be.  As was seen, in the examples, all the code was produced with a single sentence.  Depending on the resolution needed, a simple query can produce great results, but it should be noted that if specs like specific ports, and so on need to be addressed the user should specify those.  Though novel now, it is likely that the art of talking to these systems will soon appear to generate optimal code with a query. SummaryIn all, ChatGPT can be used as a tool to help speed up the development process.  As was explored with the motor health code block and the sorting algorithm, ChatGPT can turn a simple phrase into workable code that would take a human a considerable amount of time to type out.  In short, even if a PLC programmer is knowledgeable of both programming principles, algorithms, and other computer science concepts they will always be bottlenecked by having to implement the code if they cannot simply cut and paste it from another source. When used in a way that was explored, ChatGPT is a great productivity tool.  It can be used to greatly reduce the amount of time needed to implement and if necessary find a solution.  Overall, ChatGPT needs guidance to arrive at a proper solution and the person driving the AI needs to be competent enough to implement the solution.  However, when in the right hands ChatGPT and similar AI systems can greatly improve development time.Author BioM.T. White has been programming since the age of 12. His fascination with robotics flourished when he was a child programming microcontrollers such as Arduino. M.T. currently holds an undergraduate degree in mathematics, and a master's degree in software engineering, and is currently working on an MBA in IT project management. M.T. is currently working as a software developer for a major US defense contractor and is an adjunct CIS instructor at ECPI University. His background mostly stems from the automation industry where he programmed PLCs and HMIs for many different types of applications. M.T. has programmed many different brands of PLCs over the years and has developed HMIs using many different tools.Author of the book: Mastering PLC Programming
Read more
  • 0
  • 0
  • 268

Banner background image
article-image-effective-text-generation-editing-and-translation-with-chatgpt
Valentina Alto
13 Jun 2023
7 min read
Save for later

Effective Text Generation, Editing and Translation with ChatGPT

Valentina Alto
13 Jun 2023
7 min read
This article is an excerpt from the book, Modern Generative AI with ChatGPT and OpenAI Models, by Valentina Alto. This book will help harness the power of AI with innovative, real-world applications, and unprecedented productivity boosts, powered by the latest advancements in AI technology like ChatGPT and OpenAI.In the world of natural language processing, ChatGPT stands as a powerful tool for various text-related tasks. From generating creative and coherent text to providing translations and editing assistance, ChatGPT offers a wide range of functionalities. In this article, we will explore how to harness the capabilities of ChatGPT to accomplish tasks such as generating engaging content, translating text between languages, and receiving helpful suggestions for editing. With practical examples and step-by-step instructions, we will unlock the potential of ChatGPT as a versatile text companion for developers and content creators alike.As a language model, ChatGPT is particularly suited for generating text based on users’ instructions. For example, you   could ask ChatGPT to generate emails, drafts, or templates that target a specific audience:Figure 1: Example of an email generated by ChatGPTAnother example might be asking ChatGPT to create a pitch structure for a presentation you have to prepare: Figure 2 – Slideshow agenda and structure generated by ChatGPTYou can also generate blog posts or articles about trending topics this way. Here is an example:Figure 3 – blog post with relevant tags and SEO  by ChatGPTWe can even get ChatGPT to reduce the size of the post to make it fit for a tweet. Here is how we can do this: Figure 4 – ChatGPT shrinks an article into a Twitter postFinally, ChatGPT can also generate video or theatre scripts, including the scenography and the suggested editing. The following figure shows an example of a theatre dialog between a person and ChatGPT:  Figure 5– Theatre dialog with scenography generated by ChatGPTI only provided a truncated version to keep you in suspense regarding the ending…Improving writing skills and translationSometimes, rather than generating new content, you might want to revisit an existing piece of text. It this be for style improvement purposes, audience changes, language translation, and so on.Let’s look at some examples. Imagine that I drafted an email to invite a customer of mine to a webinar. I wrote two short sentences. Here, I want ChatGPT to improve the form and style of this email since the target audience will be executive-level:Figure 6 – Example of an email revisited by ChatGPT to target an executive audienceNow, let’s ask the same thing but with a different target audience: Figure 6 – Example of the same email with a different audience, generated by ChatGPTChatGPT can also give you some feedback about your writing style and structure.Imagine, for example, that you wrote a script with scenography for your YouTube channel. You included the speech as well as images, clips, and video editing activities. You also know that your typical audience is between 15 and 25 years old. You want feedback on your script and ask for this from ChatGPT: Figure 7 – Example of ChatGPT providing feedback on a video script As you can see, not only was ChatGPT able to give me feedback about the writing style, but also it suggested how I could improve the scenography of the whole video, by including more visuals.Again, imagine you wrote an introduction for an essay titled The History of Natural Language Processing and you want some feedback about the writing style and its consistency with the title: Figure 8 – Example of ChatGPT giving feedback on an introduction for an essayLet’s also ask ChatGPT to make concrete examples of the attention-grabbing anecdote it talked about in its response: Figure 9 – Example of ChatGPT elaborating on something it mentioned I’m also interested in knowing whether my introduction was consistent with the title or whether I’m taking the wrong direction:Figure 10 – ChatGPT provides feedback about the consistency of the introduction with the titleI was impressed by this last one. ChatGPT was smart enough to see that there was no specific mention of the history of NLP in my introduction. Nevertheless, it sets up the expectation about that topic to be treated later on. This means that ChatGPT also has expertise in terms of how an essay should be structured and it was very precise in applying its judgment, knowing that it was just an introduction.It is also impressive to note how the model can give different feedback, depending on the context. With the video script, ChatGPT’s feedback took into account that the final consumption of that content would have been on screen. On the other hand, the essay’s introduction lives in a more formal and academic context, with a specific structure, that ChatGPT was able to capture once more.Last but not least, ChatGPT is also an excellent tool for translation. It knows at least 95 languages (if you have doubts about whether your language is supported, you can always ask ChatGPT directly). Here, however, there is a consideration that might arise: what is the added value of ChatGPT for translation when we already have cutting-edge tools such as Google Translate?To answer this question, we have to consider some key differentiators and how we can leverage ChatGPT’s embedded translations capabilities:ChatGPT can capture the intent. This means that you could also bypass the translation phase since it is something that ChatGPT can do in the backend. For example, if you write a prompt to produce a social media post in French, you could write that prompt in any language you want – ChatGPT will automatically detect it (without the need to specify it in advance) and understand your intent:Figure 11 – Example of ChatGPT generating an output in a language that is different from the inputChatGPT can capture the more refined meaning of particular slang or idioms. This allows for a translation that is not literal so that it can preserve the underlying meaning. Namely, let’s consider the British expression It’s not my cup of tea, to indicate something that is not the type of thing you like. Let’s ask both ChatGPT and Google Translate to translate it into Italian: Figure 12 – Comparison between ChatGPT and Google Translate while translating from English into ItalianAs you can see, ChatGPT can provide several Italian idioms that are equivalent to the original one, also in their slang format. On the other hand, Google Translate performed a literal translation, leaving behind the real meaning of the idiom. As with any other task, you can always provide context to ChatGPT. So, if you want your translation to have a specific slang or style, you can always specify it in the prompt. Or, even funnier, you can ask ChatGPT to translate your prompt with a sarcastic touch:  Figure 5.20 – Example of ChatGPT translating a prompt with a sarcastic touch.The original content from: OpenAI’s Wikipedia page: https://it.wikipedia.org/wiki/OpenAISummaryIn conclusion, ChatGPT is able not only to generate new text but also to manipulate existing material to tailor it to your needs. It has also proven to be very precise at translating between languages, also keeping the jargon and language-specific expressions intact.Author BioValentina Alto graduated in 2021 in Data Science. Since 2020 she has been working in Microsoft as Azure Solution Specialist and, since 2022, she focused on Data&AI workloads within the Manufacturing and Pharmaceutical industry. She has been working on customers’ projects closely with system integrators to deploy cloud architecture with a focus on datalake house and DWH, data integration and engineering, IoT and real-time analytics, Azure Machine Learning, Azure cognitive services (including Azure OpenAI Service), and PowerBI for dashboarding. She holds a BSc in Finance and an MSc degree in Data Science from Bocconi University, Milan, Italy. Since her academic journey she has been writing Tech articles about Statistics, Machine Learning, Deep Learning and AI on various publications. She has also written a book about the fundamentals of Machine Learning with Python. LinkedIn  Medium 
Read more
  • 0
  • 0
  • 153

article-image-practical-vulnerability-scanning-made-easy-with-chatgpt
Clint Bodungen
13 Jun 2023
8 min read
Save for later

Practical Vulnerability Scanning Made Easy with ChatGPT

Clint Bodungen
13 Jun 2023
8 min read
This article is an excerpt from the book, ChatGPT for Cybersecurity Cookbook, by Clint Bodungen. This book will help you master ChatGPT and the OpenAI API, and harness the power of cutting-edge generative AI and large language models to revolutionize the way you perform penetration testing, threat detection, and risk assessment.Vulnerability scanning is crucial for identifying weaknesses before exploitation. Navigating tools like NMAP, OpenVAS, or Nessus can be complex, especially for newcomers. Our article uses ChatGPT to generate command strings based on user input, simplifying the process. By following this recipe, you can generate precise command strings for NMAP, OpenVAS, or Nessus, confidently navigating their functionalities. Whether you're a cybersecurity beginner or an expert, this recipe is a valuable tool for vulnerability assessments.Getting ready Before we begin this recipe, it's essential to ensure that you have properly set up your OpenAI account and obtained your API key. Additionally, you will require the following: Vulnerability Scanning Tools: It's crucial to have NMAP, OpenVAS, or Nessus installed on your system as the recipe generates command strings for these specific tools. Please refer to their official documentation for installation and setup guidelines.  Basic Understanding of the Tools: The more familiar you are with NMAP, OpenVAS, or Nessus, the better you will be able to utilize this recipe. If you're new to these tools, consider spending some time understanding their basic functionalities and command-line options. Command Line Environment: As the recipe generates command strings intended for command line interfaces, you should have access to a suitable command line environment where you can run these commands. Sample Network Configuration Data: Prepare some sample network data that the vulnerability scanning tools can use. This could include IP addresses, hostnames, or other relevant information about the systems you'd like to scan. How to do it… In this recipe, we'll show you how to use ChatGPT to create command strings for vulnerability scanning tools like NMAP, OpenVAS, and Nessus. We'll be providing ChatGPT with the necessary details and using a specific system role and prompt. This will allow you to generate the simplest form of the command necessary to complete your request. Start by logging in to your OpenAI account and go to the ChatGPT web UI. Begin a new conversation with ChatGPT by clicking on the "New Chat" button. Next, establish the system's role by entering the following: You are a professional cybersecurity red team specialist and an expert in penetration testing as well as vulnerability scanning tools such as NMap, OpenVAS, Nessus, Burpsuite, Metasploit, and more.  Now, prepare your request. This is the information that will replace the {user_input} in the next step. It should be a natural language request such as: Use the command line version of OpenVAS to scan my 192.168.20.0 class C network starting by identifying hosts that are up, then look for running web servers, and then perform a vulnerability scan of those web servers.  Once your request is ready, enter the following message text, replacing the {user_input} placeholder with your specific request from the previous step: Provide me with the Linux command necessary to complete the following request:  {user_input}  Assume I have all necessary apps, tools, and commands necessary to complete the request. Provide me with the command only and do not generate anything further. Do not provide any explanation. Provide the simplest form of the command possible unless I ask for special options, considerations, output, etc. If the request does require a compound command provide all necessary operators, pipes, etc. as a single one-line command. Do not provide me more than one variation or more than one line. ChatGPT will then generate the command string based on your request. Review the output. If it meets your requirements, you can proceed to copy the command and use it as needed. If it doesn't, you may need to refine your request and try again.  Once you've obtained a satisfactory command, you can copy it and paste it directly into your command line to perform the vulnerability scan as described in your request. Note Remember, it's important to review and understand any command before running it in your environment. While ChatGPT aims to provide accurate commands, you are ultimately responsible for ensuring the command's safety and appropriateness for your specific context. Figure 1 shows an example ChatGPT command generated from the prompt used in this recipe.  Figure 1 – Example ChatGPT Command Generation  How it works… The GPT-assisted vulnerability scanning recipe taps into the power of natural language processing (NLP) and the vast knowledge of machine learning algorithms to generate accurate and appropriate command strings for vulnerability scanning tools like NMAP, OpenVAS, and Nessus. When you provide a specific system role and a prompt that represents a user request, ChatGPT uses these inputs to understand the context and generate a response that aligns with the given role. System Role Definition: By defining ChatGPT's role as a professional cybersecurity red team specialist and an expert in penetration testing and vulnerability scanning tools, you're instructing the model to answer from a perspective of deep technical understanding and expertise in this field. This context helps in generating accurate and relevant command strings. Natural Language Prompt: The natural language prompt that simulates a user request allows ChatGPT to understand the task at hand in a human-like manner. Instead of needing structured data or specific keywords, ChatGPT can interpret the request as a human would and provide a suitable response. Command Generation: With the role and the prompt, ChatGPT generates the Linux command necessary to complete the request. The command is based on the specific details of the user input and the expertise of the assigned role. This is where the AI leverages its knowledge of cybersecurity and language understanding to construct the necessary command string. One-Line Command: The specification of providing a one-line command, including all necessary operators and pipes, compels ChatGPT to generate a command that's ready to be pasted into a command line for immediate execution. This removes the need for the user to manually combine or modify the command, saving time and potential errors. Simplicity and Clarity: By asking for the simplest form of the command and without any further explanation, the output is kept clear and concise, which is particularly helpful for those learning or in need of a quick reference. In summary, the GPT-assisted vulnerability scanning recipe harnesses the power of NLP and machine learning algorithms to generate precise, ready-to-run commands for vulnerability scanning. By using the defined system role and prompt, users can streamline the process of crafting commands for vulnerability assessments, save time, and improve accuracy. There’s more… The flexibility and capabilities of this GPT-assisted process extend beyond the example given. First is the versatility of the prompt. It's actually designed to accommodate virtually any request for any Linux command across any domain or task. This is a significant advantage as it enables you to leverage ChatGPT's capabilities across a wide range of scenarios. By assigning the role appropriately, such as "You are a Linux system administrator", and substituting your specific request in place of {user_input}, you can guide the AI to generate accurate and context-specific command strings for a plethora of Linux operations. Beyond simply generating command strings, the potential of this recipe is amplified when combined with the OpenAI API and Python. With the proper setup, you can not only generate the necessary Linux commands but also automate the execution of these commands. Essentially, this could turn ChatGPT into an active participant in your command-line operations, potentially saving you significant time and effort. This level of automation represents a substantial step forward in interacting with AI models, turning them into active assistants rather than passive information generators. In upcoming recipes in this book, we'll delve deeper into command automation. This is just the beginning of the possibilities opened up by the integration of AI with your operating system tasks.  Summary:This article highlights vulnerability assessment and the role of ChatGPT in simplifying the process. ChatGPT offers the ability to simulate attack scenarios, identify weaknesses, and generate reports. However, it is crucial to remember that vulnerability assessment requires human expertise and judgment. ChatGPT should be used as a supplementary tool alongside human analysis to enhance cybersecurity measures and mitigate emerging threatsAuthor BioClint Bodungen is a cybersecurity professional with 25+ years of experience and the author of Hacking Exposed: Industrial Control Systems. He began his career in the United States Air Force and has since many of the world's largest energy companies and organizations, working for notable cybersecurity companies such as Symantec, Kaspersky Lab, and Booz Allen Hamilton. He has published multiple articles, technical papers, and training courses on cybersecurity and aims to revolutionize cybersecurity education using computer gaming (“gamification”) and AI technology. His flagship product, ThreatGEN® Red vs. Blue, is the world’s first online multiplayer cybersecurity simulation game, designed to teach real-world cybersecurity.    Links - Twitter  LinkedIn  YouTubeClint has some exciting courses around ChatGPT for Cybersecurity 
Read more
  • 0
  • 0
  • 170
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-building-etl-pipelines-in-no-time-using-chatgpt
Sagar Lad
11 Jun 2023
5 min read
Save for later

Building ETL Pipelines in no time using ChatGPT

Sagar Lad
11 Jun 2023
5 min read
Given the volume, velocity, and diversity of data expanding at an exponential rate in the modern era, it is crucial to utilize this data for data analytics and machine learning projects to generate business insights. Let's discuss in this post how to utilize ChatGPT to develop ETL pipelines considering the growing popularity of ChatGPT in recent years.What is an ETL (Extract, Transform, and Load) Pipeline Data must first be fetched from one or more sources, processed, or transformed in accordance with the requirements, and then loaded into a storage system that can be used directly by end users without the need for data validation or poor data quality. ETL Pipeline also known as a ‘Data Pipeline’ sometimes known as three phases. Image 1: ETL Process Flow (Extract, Transformation, and Load) During the ETL process, first, we fetch the data, and we perform data quality and validation checks on the extracted data. Once data is extracted then data pre and post-processing should be done to transform the data into a usable format. Once data processing is done, the last step is to store the data from where the end user can access this data. Let’s ask ChatGPT to build an ETL pipeline for data engineering.Problem StatementUsing Databricks and Pyspark build an ETL pipeline using 3 layered approaches: Raw, Bronze, and Gold Layers.  Data should be ingested incrementally automatically, and data should be stored in Azure SQL Database. Business Analysts can use this data to derive business insights.1. Input to ChatGPT with the programming language, and file information (location, format, delimiter, headers, output) Image 2 : Input to chatGPT to create ETL Pipeline Here, the input has been given to the ChatGPT to build an ETL pipeline with all the required input. 2. Prerequisites suggested by ChatGPT before using the code are as follows:  Image 3 : Prerequisite to setup ETL Flow Here, ChatGPT first lists down the prerequisites to set up the blob storage, azure data lake storage gen2, and Databricks workspace.3. Importing the necessary libraries and configuring the ADLS Gen2 storage credentials as shown in the preceding figure:Image 4 : ADLS Gen2 configuration for Pyspark NotebookThis code configures ADLS gen2 using the pyspark notebook to connect and use the data using the storage account key. Here, you should replace the storage account name and key with your storage account name and key details. 4. In this step, pyspark notebook creates the schema for the pyspark data frame based on the file information and we must replace adls container name with the actual container name of ADLS Gen2. Image 5 : Create Structured Schema for pyspark dataframe5. This piece of code renames the columns and once the data frame is ready, it will write the content of the dataframe to the delta format. Image 6 : Pyspark Notebook - Data Transformation Logic 6.  Finally, ChatGPT provides guidance on where to run this code and how to set up an automated pipeline using Databricks. Image 7 : Final ChatGPT Output  7. At a first glance, it looks like it worked like a charm. Generated code can be directly used in the Databricks workspace to build an ETL pipeline. But the limitation of this solution is that it is hard coding the file path so it is not a generic code.Image 8 : Pyspark Code Optimization - ChatGPT input  8.     ChatGPT creates a generic code that can be used to trigger the ETL pipeline whenever there is a new source file in the ADLS Gen2 container. Image 9 : ADLS Gen2 configuration for Pyspark Notebook9.     Next step is to configure the ADLS Gen2 to connect to Databricks using the storage account key.Image 10 : Schema Definition for CSV File 10.  Next step is to create a structured schema to use it while creating the pyspark dataframe in the next step: Image 11: Setting up a loop to check new files 11.  As a final step, we will work towards optimizing the PySpark code: Image 12: Optimised Pyspark Code for incremental data loadTo process any file using the ETL pipeline code, the suggestion is to loop the code to continuously poll the storage container location to check if there is any new file and execute the code to process the new file if any.So, we can use this code and set up Databricks notebooks in a couple of minutes to set up an automated data pipeline for the incremental data load.ConclusionIt is getting much easier and more efficient to build ETL data pipelines using the ChatGPT. ChatGPT can also assist to create a generic and optimized code as per our requirements promptly without spending development efforts. Author BioSagar Lad is a Cloud Data Solution Architect with a leading organization and has deep expertise in designing and building Enterprise-grade Intelligent Azure Data and Analytics Solutions. He is a published author, content writer, Microsoft Certified Trainer, and C# Corner MVP. Link - Medium , Amazon , LinkedIn 
Read more
  • 0
  • 0
  • 269

article-image-using-gpt-4-for-offensive-security
Indrajeet Bhuyan
11 Jun 2023
7 min read
Save for later

Using GPT-4 for Offensive Security

Indrajeet Bhuyan
11 Jun 2023
7 min read
In this article, we will explore the cutting-edge capabilities of GPT-4, the latest advancement in language models, and discover how it can revolutionize offensive security strategies. This article delves into practical examples, demonstrating how GPT-4 can be leveraged for tasks such as vulnerability assessment, penetration testing, and threat intelligence gathering. Gain insights into its enhanced natural language understanding, automated exploit generation, and intelligent attack simulations, opening new avenues for proactive cybersecurity defenses. Harness the potential of GPT-4 to fortify your offensive security arsenal.Reminder: Generative AI is known for hallucinations where they give replies which are lies, and not true so always verify your information.Here are a few use cases where you can use GPT for Offensive Security tasks:Writing phishing mailsEarlier one of the ways to detect phishing emails was bad English. Often phishing emails have a history of having incorrect English as often attackers are from non-English speaking places. But now the availability of generative AI tools enables a broader range of users to create convincing phishing and spam messages, even if they lack the skills to do so manually.For instance, these tools can be used to generate social engineering drafts that impersonate an employee or a company, making it easier for individuals with little experience in crafting these messages to carry out these types of attacks.Example:Image 1: Example of Phishing EmailExploit developmentChatGPT can assist in identifying vulnerabilities, as demonstrated by Cybernews researchers who used the chatbot to exploit a vulnerability that was discovered. However, ChatGPT is programmed to not offer illicit services, like hacking. Therefore, carefully phrased queries are necessary. Merely asking the chatbot to create an exploit for a particular vulnerability will not suffice.The researchers informed the chatbot that they were conducting a 'Hack the Box' pen test challenge and required assistance in locating a vulnerability. Once discovered, they were given step-by-step instructions, exploit code examples, and samples to use. As a result, the security researchers were able to identify and write an exploit for a well-known application within 45 minutes. This once again showcases how ChatGPT has made a previously complicated and lengthy process accessible to everyone.Write scriptsGPT-4 can be used to write automation scripts that can make the work of a security professional easExample : Here I’m asking ChatGPT to write a Python script that will use httpx to see all the live web hosts from a list of text files containing URLs and then use nuclei on all the domains:Image 2: Python script outputSource Code reviewChatGPT now with GPT-4 can be used to do source code reviews. It can help security professionals iXn do source code reviews faster. Though sometimes it gives wrong answers it can be used to get a good suggestion which later the security professional can use to verify if the response is correct or not.Example: I asked GPT-4 to find a security vulnerability in this code <?php if( isset( $_POST[ 'Submit' ]  ) ) {            // Get input            $target = $_REQUEST[ 'ip' ];            // Determine OS and execute the ping command.            if( stristr( php_uname( 's' ), 'Windows NT' ) ) {                        // Windows                        $cmd = shell_exec( 'ping  ' . $target );            }            else {                        // *nix                        $cmd = shell_exec( 'ping  -c 4 ' . $target );            }            // Feedback for the end user            $html .= "<pre>{$cmd}</pre>"; } ?> Here is the response:Image 3: Code reviewHere the code was simple and it could find a flaw in the code correctly but with complex code, it often gives incorrect responses. But these responses can help security professionals in doing their tasks fast as they can get feedback from ChatGPT and can filter out incorrect information:Create your own Nuclei templateChatgpt can be used to create a Nuclei template which can later help in automating the task of finding flaws.Example: Image 4: Nuclei templateWrite reportsThis one is my favorite. As a penetration tester or security professional one needs to write a lot of reports. Reports for clients, reports for other team members, etc. Chatgpt can be extensively used for writing security reports. Though I don’t recommend using chatGPT to make the entire report it can be used for making the task of writing reports easyExample 1: Here I’m asking ChatGPT to help me write a bug bounty report for an SSRF flaw that I found in example.com along with how to fix the issue: Image 5: Bug Bounty ReportExample 2: Here I’m asking Chatgpt to write a report on OWASP's top 10 flaws along with how to fix those flaws which I need to send to the client:Image 6: OWASP top 10 flawsPrepare for interviews.Chatgpt can be used for preparing for technical interviews as it can show you common questions that are asked for your role and position.Example: Here I’m asking ChatGPT to suggest me 10 questions along with an answer for a penetration tester job with 3 years of experience:Image 10: Interview QuestionsWrite technical blogs and articlesChatgpt is now more powerful with GPt-4 and it can help you write technical articles by giving you valuable inputs and suggestions.Fun fact: GPT-4 is used intensively while writing this article that you are reading.ConclusionIn conclusion, GPT-4, together with Chatgpt, has the potential to simplify numerous tasks in offensive security, thereby offering valuable assistance to security professionals. Though there are concerns about the possibility of individuals misusing this technology, its positive use cases cannot be disregarded. However, it is unlikely that GPT-4 can replace security professionals soon. Nonetheless, security experts who incorporate AI in their work can certainly outperform those who do not leverage this technology. Ultimately, it is up to us to determine how we use this powerful tool and ensure that it is utilized for the greater good.Author BioIndrajeet Bhuyan is a security researcher from Assam, India. He holds a Bachelor of Technology (B.Tech.) focused on Computer Science from Assam Don Bosco University. He has contributed security to various companies and organizations like Whatsapp, HTC, Samsung, Photobucket, Reverbnation, TVF, ESET, etc. He got featured in multiple national and international news portals like International Business Times, Russia Today, Times of India, Digit, Kaspersky, The Independent, India Today, etc. for his work on cybersecurity. He created ‘WannaSmile’ a tool that was used to protect users from the world’s biggest ransomware attack ‘ WannaCry’ which was featured by various national and international media.LinkedIn 
Read more
  • 0
  • 0
  • 598

article-image-infusing-old-school-powerpoint-presentations-with-gpt-powers
Andrei Gheorghiu
08 Jun 2023
9 min read
Save for later

Infusing Old-school PowerPoint Presentations with GPT Powers

Andrei Gheorghiu
08 Jun 2023
9 min read
IntroductionRumor has it that around 30 million PowerPoint presentations are being created each day. Oh, PowerPoint, the sturdy old friend in the world of presentations. You might ask, why, in this fast-paced, ever-evolving digital world, do people still reach out for PowerPoint? Well, let me break it down for you, because honestly, PowerPoint has still got game! It’s simple, universal (in the realm of presentations), easy to learn and pretty well integrated with the other two Microsoft musketeers (Word & Excel).So, sure, there are fancier new alternatives out there (like Prezi or Canva), each with their unique features and slick interfaces. But when it comes to a tried-and-true solution for your presentation needs, you might find that, like a well-loved pair of sneakers, PowerPoint fits just right.And here’s the news: the little AI based automation I am going to show you in this article might actually change your mind about the capabilities of PowerPoint and make you reconsider using much more modern alternatives for your presentations.Working as a trainer for the last 15 years, I’ve probably seen more PowerPoint than other people do. I used it daily both for studying and teaching, whether for 15-minute presentations or 5-day long courses. I’ve always thought the greatest power of PowerPoint was not in its UI, design features or the number of export formats but rather in the VBA (Visual Basic for Applications) core functionality it shares with the other tools in the Microsoft ecosystem. And yet, so much potential lays unused in this regard.Oh, did you think that VBA is dead? I’m going to prove you wrong.A key characteristic for any slide-based presentation is that the viewer only gets a glimpse of the actual knowledge in the slide. It’s more visually appealing that way, but you need a presenter to understand the story and connect the dots. And usually, the presenter needs to use some slide notes for a more cursive and natural presentation. Slide notes are like a secret teleprompter. They give you reminders, help you with the flow of your presentation, and keep you on point. They're your discreet cheat-sheet, making sure you never miss a beat during your presentation.In this article, I am going to show you how, with just a few lines of code, you can infuse your existing PowerPoint presentations with the ability to automatically generate slide notes based on your slide contents.How it worksMy approach might seem a bit crude but it is effective. Especially if your presentation contains general concepts that might fall within the knowledge span of GPT3.5 Turbo from OpenAI (or even GPT-4 if you have an API key). More niche topics, or a slide having just a single bullet of words without too much context, may not produce the best results. Afterall, it’s all automated and no matter how smart the AI model may be, it still needs context to understand the task.For those who might be unfamiliar with the GPT3.5 Turbo API: this API provides programmatic access to the same advanced language model used by ChatGPT. Its purpose in the script is to explain the concepts in a PowerPoint slide.So, the basic approach is to create a VBA macro in the presentation that performs the following:Extracts all text from the current slide.Formats the entire text and builds a specially designed prompt with it.Submits the prompt to OpenAI’s API for processing.Appends the AI answer received from the API to the current slide’s notes.Because it’s a macro, once you’ve created it you can assign a shortcut and repeat the process for each slide.Alternatively, with a bit of tweaking you could adjust the code to iterate through all the slides and create all slide notes in one go. But keep in mind there is a cost for every API call you make and for a large presentation, the cost might easily spin out of control. BeforeAfterImagine the amount of time you can save by starting with some quick AI-generated draft notes and then reviewing and adding more context instead of having to type everything in from scratch. This productivity hack can save you hours of your time or even help you make sense of presentations created by someone else that lack any explanations or trainer notes. Before you beginSome things you need to take care of before you start writing the code:Make sure you store your OpenAI API key in a local environment variable for secure and efficient access. The code works on the assumption that the API key is stored in your local environment (OPENAI_API_KEY).Enable the Developer tab on your PowerPoint. By default, this tab is not visible. To enable it and be able to create VBA code you need to go to File > Options > Customize Ribbon and select Main Tabs > Developer > Add. I know. That’s enough reason to hate PowerPoint. But at least, the good news is you only have to do it once. Once you’ve got that solved you may proceed with the next steps:Go to the Developer Tab and select Visual Basic.From the Insert menu choose Module.Add the code from the next section in the newly created module and save the file. You’ll probably be notified that the .PPTX extension does not support macros. No worries. Just click No, select .PPTM (Macro enabled presentation) as your file type and save. Make sure you customize the code first to provide the prompt with more context on your specific presentation (see the comments in the code).And that’s it. You’re good to go.Now, select Developer > Macros and you should see a new macro called QueryGpt.Just go to your desired slide and run the macro. Wait for a few seconds and you should have your notes populated with AI’s interpretation of your slide. Be mindful though, the code is simple. There’s no error checking and I haven’t tested it on hundreds of PPTs.You can download the .BAS source file for this article from here. Pro Tip: If you want to create an easy shortcut to your macro you can click on the last icon in the very top ribbon menu and select More commands and then from Choose commands from select Macros, choose the QueryGpt macro and Add. A new button for the macro will be permanently added on your ribbon.The codeNo more talking. Here’s the macro:Sub QueryGpt() Dim sld As Slide Dim shp As Shape Dim text As String Dim explanation As String Dim prompt As String Dim subject As String ' Extract and format the text from the current slide Set sld = ActiveWindow.View.Slide For Each shp In sld.Shapes If shp.HasTextFrame Then If shp.TextFrame.HasText Then text = text & " [" & Replace(shp.TextFrame.TextRange.text, vbCrLf, "/") & "] " End If End If Next shp text = Replace(Replace(Replace(text, vbCrLf, "\n"), vbCr, "\r"), vbLf, "\n") ' Prepare the prompt and call the function that queries the AI model subject = "The concept of Public Domain" prompt = "You are a useful assistant that explains the concepts from a presentation about " prompt = prompt & subject & ". Explain the following concepts: " explanation = CallOpenAI(prompt & text) ' Append the AI explanation to the slide notes sld.NotesPage.Shapes.Placeholders(2).TextFrame.TextRange.InsertAfter vbCrLf & explanation End Sub Take note of the variable called subject.That is the main topic of your presentation, and you should change that to the subject of your slides.That way the AI model gets more context about your slides and can provide better descriptions in the notes.You should be able to achieve better results by adding more details in that variable but consider the maximum context of the model (for GPT 3.5 Turbo that is around 3000 English words). The more you add to your initial input, the more you limit your result’s maximum length because the whole context cannot exceed ~3000 words.Next, here is the function responsible for making the API call and formatting the resulting answer:Function CallOpenAI(text As String) As String Dim httpRequest As Object Dim responseText As String Dim contentStartPos As Long Dim contentEndPos As Long ' Prepare the connection and send the request to the OpenAI API Set httpRequest = CreateObject("WinHttp.WinHttpRequest.5.1") httpRequest.Open "POST", "https://api.openai.com/v1/chat/completions", False httpRequest.setTimeouts 0, 60000, 30000, 120000 httpRequest.setRequestHeader "Content-Type", "application/json" httpRequest.setRequestHeader "Authorization", "Bearer " & Environ("OPENAI_API_KEY") httpRequest.Send "{""model"": ""gpt-3.5-turbo"", " _ & """messages"": [{""role"": ""user"", " _ & """content"": """ & text & """}]}" httpRequest.WaitForResponse responseText = httpRequest.responseText ' Extract the AI answer from the response string contentStartPos = InStr(1, responseText, """content"":""") + 11 responseText = Mid(responseText, contentStartPos) contentEndPos = InStr(1, responseText, """") - 1 responseText = Replace(Mid(responseText, 1, contentEndPos), "\n", vbCrLf) CallOpenAI = responseText End Function All you have to do to add this code to the presentation is to follow steps 3 to 5 above.Once you’ve created the module and saved the presentation, you’ll have the new macro called QueryGpt.If you’ve created the shortcut by following the pro tip, you’ll also have a neat way of calling the macro whenever you need to append some slide notes to the current slide.And there you go: Old-school PowerPoint presentations infused with AI super-powers.Feels like converting an old Diesel to an EV, doesn’t it? DisclaimerAs with any AI generated content do not forget to check the outputs for accuracy and potential hallucinations. (https://www.packtpub.com/page/4-ways-to-treat-a-hallucinating-AI-with-Prompt-Engineering_). Do not forget that any bias or inaccurate data in the slide content may get amplified in the outputs. Author BioAndrei Gheorghiu is an experienced trainer with a passion for helping learners achieve their maximum potential. He always strives to bring a high level of expertise and empathy to his teaching.With a background in IT audit, information security, and IT service management, Andrei has delivered training to over 10,000 students across different industries and countries. He is also a Certified Information Systems Security Professional and Certified Information Systems Auditor, with a keen interest in digital domains like Security Management and Artificial Intelligence.In his free time, Andrei enjoys trail running, photography, video editing and exploring the latest developments in technology.You can connect with Andrei on:LinkedIn: https://www.linkedin.com/in/gheorghiu/Twitter: https://twitter.com/aqg8017  
Read more
  • 0
  • 0
  • 180

article-image-writing-unit-tests-in-c-with-ease-using-chatgpt
Jesse Liberty
08 Jun 2023
9 min read
Save for later

Writing Unit Tests in C# with ease using ChatGPT

Jesse Liberty
08 Jun 2023
9 min read
The world is abuzz with talk of large language model AI, especially its iconic ChatGPT. No one is more excited and perhaps threatened than programmers. Will ChatGPT soon write code well enough to change or even eliminate our jobs? In this article, I set such concerns aside and focus on how ChatGPT can enhance our programming today. One of the places I find ChatGPT most useful is in the writing of unit tests. To illustrate this, I'm going to dip into the source code used in my latest book: .NET MAUI For C# Developers. If you haven't read my book (actually, why not stop here and run out and buy it? I can wait here) it illustrates the creation of a helpful app that, among other things, requires you to create an account. Here is the code for doing so:  [RelayCommand] async Task SignUp() {    if (EnableButton)    {      AccountCreateRequest accountCreateRequest = new()      {        Email = this.Email,        FullName = Name,        PlainPassword = Password      };      try      {        CreateAccountIsRunning = true;        await accountService.CreateAccount(accountCreateRequest);        CreateAccountIsRunning = false;        await Application.Current.MainPage.DisplayAlert(         "Sign up completed",        "Your user has been created successfully", "Ok");        await Shell.Current.GoToAsync("..");      }      catch (Exception e)      {          CreateAccountIsRunning = false;        await Application.Current.MainPage.DisplayAlert(         "Sign up failed",        "We were not able to create an account with that user name",         "Ok");      }    } } The logic here is simple, I've selected it specifically so that you can easily imagine how you would write unit tests. Let's see how ChatGPT does when presented with this code. I opened ChatGPT and entered the following message:  Write two unit tests with xUnit and nSubstitute in C# for the following .NET MAUI code (I pasted in the code. It responded so quickly it took my breath away)Sure! Here are two unit tests using xUnit and NSubstitute for the SignUp() method: I particularly like the self-assured and friendly "Sure!" at the beginning, and the restatement of what it has been asked to do. Its results come flying out in a box that has a handy Copy Code button on the top right, and a reminder on the top left that the code is in C# as shown in the figure:   Figure 1 – top of ChatGPT response  Notice that it marks the first section. // Arrange As you'll see it uses and annotates the AAA approach to unit tests (Arrange, Act, Assert). Here are the two-unit tests it produced: public class YourViewModelTests {    [Fact]    public async Task SignUp_WhenEnableButtonIsFalse_DoesNotCallAccountServiceAndDisplaysNoAlert()    {        // Arrange        var accountService = Substitute.For<IAccountService>();        var applicationMock = Substitute.For<Application>();        var mainPageMock = Substitute.For<Page>();        var shellMock = Substitute.For<Shell>();        applicationMock.MainPage = mainPageMock;        Shell.Current = shellMock;        var viewModel = new YourViewModel(accountService)        {            Email = "test@example.com",            Name = "John Doe",            Password = "password",            EnableButton = false        };        // Act        await viewModel.SignUp();        // Assert        await accountService.DidNotReceive().CreateAccount(Arg.Any<AccountCreateRequest>());        await applicationMock.MainPage.DidNotReceive().DisplayAlert(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());        await shellMock.DidNotReceive().GoToAsync(Arg.Any<string>());    }    [Fact]    public async Task SignUp_WhenEnableButtonIsTrue_CallsAccountServiceAndDisplaysAlertOnError()    {        // Arrange        var accountService = Substitute.For<IAccountService>();        accountService            .When(x => x.CreateAccount(Arg.Any<AccountCreateRequest>()))            .Throw(new Exception("Failed to create account"));        var applicationMock = Substitute.For<Application>();        var mainPageMock = Substitute.For<Page>();        var shellMock = Substitute.For<Shell>();        applicationMock.MainPage = mainPageMock;        Shell.Current = shellMock;        var viewModel = new YourViewModel(accountService)        {            Email = "test@example.com",            Name = "John Doe",            Password = "password",            EnableButton = true        };        // Act        await viewModel.SignUp();        // Assert        await accountService.Received(1).CreateAccount(Arg.Is<AccountCreateRequest>(request =>            request.Email == viewModel.Email &&            request.FullName == viewModel.Name &&            request.PlainPassword == viewModel.Password));        await applicationMock.MainPage.Received(1).DisplayAlert("Sign up failed",            "We were not able to create an account with that user name", "Ok");        await shellMock.DidNotReceive().GoToAsync(Arg.Any<string>());    } }  After the code comes to these handy instructions and reminders: In the first test case, SignUp_WhenEnableButtonIsFalse_DoesNotCallAccountServiceAndDisplaysNoAlert(), we set EnableButton to false and verify that the SignUp() method does not call CreateAccount() on the accountService, and no alerts are displayed. In the second test case, SignUp_WhenEnableButtonIsTrue_CallsAccountServiceAndDisplaysAlertOnError(), we set EnableButton to true and configure the accountService to throw an exception when CreateAccount() is called. We verify that the method calls CreateAccount(), displays the appropriate alert for failure, and does not navigate to another page using GoToAsync(). By following those instructions, I had two working, useful unit tests, literally in seconds (well, a lot of seconds, but only because it took me a minute to read and understand (and verify) what it had done.) The first time I made the request, I forgot to say it in xUnit and it spits out the tests in nUnit. I then entered, Do it again using xUnit And it didn't hesitate, out came the code in xUnit along with modified instructions. Summary In sum, my pair-programming buddy, ChatGPT, saved me a lot of tedious work creating unit tests. I can attest that it works equally well on more complex logic. It doesn't always get it right the first time, but you can "tune" it with follow-up questions, and it remembers what it just did, so rather than repeating the entire command you can just say, as I do above, Do it again, but this time… We used to say, Coding by Google is not a problem as long as you know what you are doing. The problem only arose with very junior programmers who took what they found online as-is without checking that it made sense. The same can be true here: ChatGPT can get you going, and you can often use its code as-is, but you need to keep a cautious eye on it as it certainly can get things wrong.  Writing unit tests is a critical, though often overlooked part of writing code well. ChatGPT not only makes it relatively easy, but it also encourages creating tests because you can do so quickly. It is so good that I happily pay $20/month for a subscription entitling me to unrestricted use and access to the latest iteration.  Author Bio  Jesse Liberty is a full-time hands-on programmer, specializing in C#, git, and .NET MAUI. He hosts the popular Yet Another Podcast and is the author of more than a dozen best-selling programming books. Liberty is a Certified Xamarin Developer, a Xamarin MVP, and a Microsoft MVP. He was a Technical Evangelist for Microsoft, a Distinguished Software Engineer at AT&T; a Software Architect for PBS, and a Vice President of Information Technology at Citibank, and he was on the teaching staff at Brandeis University. Jesse is a recognized expert and has spoken at conferences worldwide.  Links - LinkedIn  .NET MAUI for C# Developers  
Read more
  • 0
  • 0
  • 608
article-image-ab-testing-for-marketing-comparison-using-openai-chatgpt
Valentina Alto
08 Jun 2023
5 min read
Save for later

A/B testing for marketing comparison using OpenAI ChatGPT

Valentina Alto
08 Jun 2023
5 min read
This article is an excerpt from the book, Modern Generative AI with ChatGPT and OpenAI Models, by Valentina Alto. This book will help harness the power of AI with innovative, real-world applications, and unprecedented productivity boosts, powered by the latest advancements in AI technology like ChatGPT and OpenAI.A/B testing in marketing is a method of comparing two different versions of a marketing campaign, advertisement, or website to determine which one performs better. In A/B testing, two variations of the same campaign or element are created, with only one variable changed between the two versions. The goal is to see which version generates more clicks, conversions, or other desired outcomes.An example of A/B testing might be testing two versions of an email campaign, using different subject lines, or testing two versions of a website landing page, with different call-to-action buttons. By measuring the response rate of each version, marketers can determine which version performs better and make data-driven decisions about which version to use going forward. A/B testing allows marketers to optimize their campaigns and elements for maximum effectiveness, leading to better results and a higher return on investment.Since this method involves the process of generating many variations of the same content, the generative power of ChatGPT can definitely assist in that.Let’s consider the following example. I’m promoting a new product I developed: a new, light and thin climbing harness for speed climbers. I’ve already done some market research and I know my niche audience. I also know that one great channel of communication for that audience is publishing on an online climbing blog, of which most climbing gyms’ members are fellow readers.My goal is to create an outstanding blog post to share the launch of this new harness, and I want to test two different versions of it in two groups. The blog post I’m about to publish and that I want to be the object of my A/B testing is the following:  Figure 1– An example of a blog post to launch climbing gearHere, ChatGPT can help us on two levels:The first level is that of rewording the article, using different keywords or different attention-grabbing slogans. To do so, once this post is provided as context, we can ask ChatGPT to work on the article and slightly change some elements:Figure 2 – New version of the blog post generated by ChatGPT As per my request, ChatGPT was able to regenerate only those elements I asked for (title, subtitle, and closing sentence) so that I can monitor the effectiveness of those elements by monitoring the reaction of the two audience groups.The second level is working on the design of the web page, namely, changing the collocation of the image rather than the position of the buttons. For this purpose, I created a simple web page for the blog post published in the climbing blog (you can find the code in the book’s GitHub repository at https://github.com/PacktPublishing/The-Ultimate-Guide- to-ChatGPT-and-OpenAI/tree/main/Chapter%207%20-%20ChatGPT%20 for%20Marketers/Code):Figure 3 – Sample blog post published on the climbing blogWe can directly feed ChatGPT with the HTML code and ask it to change some layout elements, such as the position of the buttons or their wording. For example, rather than Buy Now, a reader might be more gripped by an I want one! button.So, let's feed ChatGPT with the HTML source code:Figure 4 – ChatGPT changing HTML code Let’s see what the output looks like:Figure 5 – New version of the websiteAs you can see, ChatGPT only intervened at the button level, slightly changing their layout, position, color, and wording.Indeed, inspecting the source code of the two versions of the web pages, we can see how it differs in the button sections:Figure 6 – Comparison between the source code of the two versions of the website ConclusionIn conclusion, ChatGPT is a valuable tool for A/B testing in marketing. Its ability to quickly generate different versions of the same content can reduce the time to market of new campaigns. By utilizing ChatGPT for A/B testing, you can optimize your marketing strategies and ultimately drive better results for your business.Author BioAfter completing her Bachelor's degree in Finance, Valentina Alto pursued a Master's degree in Data Science in 2021. She began her professional career at Microsoft as an Azure Solution Specialist, and since 2022, she has been primarily focused on working with Data & AI solutions in the Manufacturing and Pharmaceutical industries. Valentina collaborates closely with system integrators on customer projects, with a particular emphasis on deploying cloud architectures that incorporate modern data platforms, data mesh frameworks, and applications of Machine Learning and Artificial Intelligence. Alongside her academic journey, she has been actively writing technical articles on Statistics, Machine Learning, Deep Learning, and AI for various publications, driven by her passion for AI and Python programming.Link - Medium Modern Generative AI with ChatGPT and OpenAI Models
Read more
  • 0
  • 0
  • 127

article-image-integrating-chatgpt-api-with-microsoft-office
Martin Yanev
07 Jun 2023
6 min read
Save for later

Integrating ChatGPT API with Microsoft Office

Martin Yanev
07 Jun 2023
6 min read
In this article, we will explore how to set up a PyCharm project and install the docx Python library to extract text from Word documents. The docx library is a Python package that allows us to read and write Microsoft Word ( .docx) files and provides a convenient interface to access information stored in these files. The first step is to initiate your work by creating a new PyCharm project. This will enable you to have a dedicated area to craft and systematize your Translation app code.  Open PyCharm IDE on your systemClick on Create New Project from the welcome screen or go to File | New Project if you're already in the IDE Keep the default settingGive your project the name Translation AppClick on Create to create the project To run the language translation desktop app, you will need to install the following libraries:  openai: The  openai library allows you to interact with the OpenAI API and perform various natural language processing tasks.  docx: The  docx library allows you to read and write Microsoft Word files  .docx using Python.  tkinter: The  tkinter library is a built-in Python library that allows you to create graphical user interfaces (GUIs) for your desktop app.   As  tkinter is a built-in library, there is no need for installation since it already exists within your Python environment. To install the  openai and  docx libraries, access the PyCharm terminal by clicking on View | Tool Windows | Terminal, and then execute the following commands:  pip install openai pip install python-docx   To access and read the contents of a Word document, you will need to create a sample Word file inside your PyCharm project. Here are the steps to create a new Word file in PyCharm:  In PyCharm project create a new directory called files Right-click on the files folder and select New | File In the dialog box that appears, enter a file name with the extension .docx. For example, info.doc.  Select the Enter key to create the file Once the file is created, double-click on it to open it You can now add some text or content to this file, which we will later access and read using the docx library in Python. For this example, we have created an article about on New York City. However, you can choose any Word document containing text that you want to analyze.  The United States' most populous city, often referred to as New York City or NYC, is New York. In 2020, its population reached 8,804,190 people across 300.46 square miles, making it the most densely populated major city in the country and over two times more populous than the nation's second-largest city, Los Angeles. The city's population also exceeds that of 38 individual U.S. states. Situated at the southern end of New York State, New York City serves as the Northeast megalopolis and New York metropolitan area's geographic and demographic center - the largest metropolitan area in the country by both urban area and population. Over 58 million people also live within 250 miles of the city. A significant influencer on commerce, health care and life sciences, research, technology, education, politics, tourism, dining, art, fashion, and sports, New York City is a global cultural, financial, entertainment, and media hub. It houses the headquarters of the United Nations, making it a significant center for international diplomacy, and is often referred to as the world's capital.  Now that you have created the Word file inside your PyCharm project, you can move on to the next step, which is to create a new Python file called app.py inside the Translation App root directory. This file will contain the code to read and manipulate the contents of the Word file using the docx library. With the Word file and the Python file in place, you are ready to start writing the code to extract data from the document and use it in your application. To test if we can read word files with the docx Python library, we can implement the subsequent code in our app.py file:  Import docx  doc = docx.Document(“<full_path_to_docx_file>”)  text = “”  for para in doc.paragraphs:  text += para.text  print(text)  Make sure to replace the <full_path_to_docx_file> with the actual path to your Word document file. Obtaining the file path is a simple task, achieved by Right Click on your docx file in PyCharm and selecting the option Copy Path/Reference… from the drop-down menu.  Once you have done that, run the app.py file and verify the output. This code will read the contents of your Word document and print them to the Run Window console. If the text extraction works correctly, you should see the text of your document printed in the console (see figure below). The text variable now holds the data from the info.docx as a Python string.   Figure: Word text extraction console output SummaryThis section provided a step-by-step guide on how to set up a PyCharm project and install the docx Python library to extract text from Word documents. The section also included instructions on how to create a new Word file in PyCharm and use the docx library to read and manipulate its contents using Python.  Author BioMartin Yanev is an experienced Software Engineer who has worked in the aerospace and medical industries for over 8 years. He specializes in developing and integrating software solutions for air traffic control and chromatography systems. Martin is a well-respected instructor with over 280,000 students worldwide, and he is skilled in using frameworks like Flask, Django, Pytest, and TensorFlow. He is an expert in building, training, and fine-tuning AI systems with the full range of OpenAI APIs. Martin has dual master's degrees in Aerospace Systems and Software Engineering, which demonstrates his commitment to both practical and theoretical aspects of the industry. https://www.linkedin.com/in/martinyanev/https://www.udemy.com/user/martin-yanev-3/ 
Read more
  • 0
  • 0
  • 223

article-image-audio-summarize-any-youtube-video-with-python-chatgpt-and-aws
Andrei Gheorghiu
07 Jun 2023
8 min read
Save for later

Audio Summarize Any YouTube Video with Python, ChatGPT, and AWS

Andrei Gheorghiu
07 Jun 2023
8 min read
IntroductionHave you ever wished you could just listen to the summary of a long YouTube video instead of watching the whole thing? Well, you're in luck! In this article, I’ll be showcasing a fun little Python project that I’ve been working on, which allows you to do just that.Don’t get me wrong: YouTube is a great resource for learning about new technologies and keeping you up to date with the latest news. And best of all: it’s free. But sometimes, I tend to lose track of time in the myriad of videos out there, fast forwarding through long talks only to find out in the end that the information I’m looking for is not in the video ☹Well, if you often find yourself in a similar situation, here’s a potential tool you might like. This little script downloads the audio from a YouTube video, transcribes it, summarizes it using AI and finally generates a new audio file with the summary. And all this magic is done using the OpenAI GPT-3.5-turbo API and some cool AWS services (S3, Transcribe, and Polly). In less than 80 lines of code.For those who might be unfamiliar with these APIs, here is their purpose in the script:OpenAI's GPT-3.5-turbo provides programmatic access to the same advanced language model used by ChatGPT. Its purpose in the script is summarizing the transcribed video content.AWS S3 is a storage service where we temporarily store the audio file from the YouTube video and the transcript. We have to use an S3 bucket because it is required by AWS Transcribe and AWS Polly.AWS Transcribe is used to convert the audio file into text.AWS Polly is a service that turns text into lifelike speech. We use it to generate an audio file of the summary.Logic Diagram DisclaimerBefore you start using these services, be aware that both AWS and OpenAI have usage quotas and costs associated with them. Make sure to familiarize yourself with these to avoid any unexpected charges. You’ll probably fall well within the limits of your Amazon account’s free tier unless you start summarizing hundreds of videos.Also, you might consider adding error handling in the code. To keep it short I’ve skipped it from this demo.You can download the Python file for this code from GitHub here.Configuring the APIsMake sure you store your OpenAI API Key and AWS Credentials in your local environment variables for secure and efficient access. The code works on the assumption that both the OpenAI API keys and AWS credentials are valid and have been already stored on your local environment variables. Alternatively, you can store your AWS ACCESS KEY and SECRET ACCESS KEY in %USERPROFILE%\.aws\credentialsMore info on that here: https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.htmlFor the code to function properly make sure the AWS credentials you are using have the following permissions:AmazonS3FullAccess: This is required to create and delete S3 buckets, upload files to the buckets and delete objects within the buckets.AmazonTranscribeFullAccess: This is needed to start transcription jobs and get the transcription job results.AmazonPollyFullAccess: This is necessary to synthesize speech from text.The most convenient and safe approach to grant the necessary permissions is though the AWS Management Console by attaching the relevant policies to the user or role associated with the credentials. RequirementsI’ve used Python v3.11. Make sure you first install all the requirements or update them to the latest version if already installed.pip install pytube pip install openai pip install boto3 pip install requests pip install python-dotenvThe CodeLet’s break it down snippet by snippet. Setup and Import Statementsimport os import boto3 import requests import openai import uuid from pytube import YouTube Downloading the Audio from YouTubeThe download_audio function uses the pytube library to download the audio from a YouTube video. The audio file is saved locally before being uploaded to S3 by the main function. Here’s a complete documentation for pytube: https://pytube.io/en/latest/def download_audio(video_id): yt = YouTube(f'https://www.youtube.com/watch?v={video_id}') return yt.streams.get_audio_only().download(filename=video_id) Transcribing Audio to TextThe transcribe_audio function uses AWS Transcribe to convert the audio into text. The UUID (Universally Unique Identifier) module is used to generate a unique identifier for each transcription job. The benefit of using UUIDs here is that every time we run the function, a new unique job name is created. This is important because AWS Transcribe requires job names to be unique. Here’s the complete documentation of AWS Transcribe: https://docs.aws.amazon.com/transcribe/latest/dg/what-is.htmldef transcribe_audio(s3, bucket, file_name): transcribe = boto3.client('transcribe') job_name = f"TranscriptionJob-{uuid.uuid4()}" transcribe.start_transcription_job( TranscriptionJobName=job_name, Media={'MediaFileUri': f"s3://{bucket}/{file_name}"}, MediaFormat='mp4', LanguageCode='en-US' ) while True: status = transcribe.get_transcription_job(TranscriptionJobName=job_name) if status['TranscriptionJob']['TranscriptionJobStatus'] in ['COMPLETED', 'FAILED']: break return status['TranscriptionJob']['Transcript']['TranscriptFileUri'] if status['TranscriptionJob']['TranscriptionJobStatus'] == 'COMPLETED' else None Summarizing the TranscriptThe summarize_transcript function leverages OpenAI's GPT-3.5-turbo to summarize the transcript. Notice the simple prompt I’ve used for this task. I’ve tried to keep it very short in order to save more tokens for the actual transcript. It can definitely be improved and tweaked according to your preferences. For a complete documentation of the OpenAI API check out this link: https://platform.openai.com/docs/api-reference/introductiondef summarize_transcript(transcript): response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a knowledge curator helping users to understand the contents of video transcripts."}, {"role": "user", "content": f"Please summarize the following transcript: '{transcript}'"} ] ) return response['choices'][0]['message']['content'].strip() Synthesizing Speech from TextThe synthesize_speech function uses AWS Polly to convert the summarized text back into audio. If you prefer other voices or want to tweak different parameters such as speed, language, or dialect, here’s the complete documentation on how to use Polly: https://docs.aws.amazon.com/polly/index.htmldef synthesize_speech(s3, bucket, transcript_uri): transcript_data = requests.get(transcript_uri).json() transcript = ' '.join(item['alternatives'][0]['content'] for item in transcript_data['results']['items'] if item['type'] == 'pronunciation') summary = summarize_transcript(transcript) summary_file_name = f"summary_{uuid.uuid4()}.txt" s3.put_object(Body=summary, Bucket=bucket, Key=summary_file_name) polly = boto3.client('polly') response = polly.synthesize_speech(OutputFormat='mp3', Text=summary, VoiceId='Matthew', Engine='neural') mp3_file_name = f"speech_{uuid.uuid4()}.mp3" with open(mp3_file_name, 'wb') as f: f.write(response['AudioStream'].read()) return mp3_file_name The Clean-up of the S3 BucketTo keep our storage in check and avoid littering the cloud, it’s best to clean up all objects from the bucket. We’ll be able to delete the bucket completely once the audio summary has been downloaded locally.Remember, we only needed the S3 bucket because it was required by AWS Transcribe and Polly.def delete_all_objects(bucket_name): s3 = boto3.resource('s3') bucket = s3.Bucket(bucket_name) bucket.objects.all().delete() The Main FunctionAnd finally, the main function, which ties everything together. It specifies the YouTube video to summarize (which you can obviously change to any another video ID), sets up the necessary AWS services and calls the functions defined above in the correct order. It also makes sure to clean up by deleting the S3 bucket after use.def main(): video_id = 'U3PiD-g7XJM' #change to any other Video ID from YouTube bucket = f"bucket-{uuid.uuid4()}" file_name = f"{video_id}.mp4" openai.api_key = os.getenv('OPENAI_API_KEY') s3 = boto3.client('s3') s3.create_bucket(Bucket=bucket) print ("Downloading audio stream from youtube video...") audio_file = download_audio(video_id) print ("Uploading video to S3 bucket...") s3.upload_file(audio_file, bucket, file_name) print("Transcribing audio...") transcript_uri = transcribe_audio(s3, bucket, file_name) print("Synthesizing speech...") mp3_file_name = synthesize_speech(s3, bucket, transcript_uri) print(f"Audio summary saved in: {mp3_file_name}\n") delete_all_objects(bucket) s3.delete_bucket(Bucket=bucket) if __name__ == "__main__": main() And that's it! With this simple tool you can now convert any YouTube video into a summarized audio file.So, sit back, relax and let AI do the work for you.Enjoy! About the AuthorAndrei Gheorghiu is an experienced trainer with a passion for helping learners achieve their maximum potential. He always strives to bring a high level of expertise and empathy to his teaching.With a background in IT audit, information security, and IT service management, Andrei has delivered training to over 10,000 students across different industries and countries. He is also a Certified Information Systems Security Professional and Certified Information Systems Auditor, with a keen interest in digital domains like Security Management and Artificial Intelligence.In his free time, Andrei enjoys trail running, photography, video editing and exploring the latest developments in technology.You can connect with Andrei on:LinkedIn: https://www.linkedin.com/in/gheorghiu/Twitter: https://twitter.com/aqg8017
Read more
  • 0
  • 0
  • 807
article-image-creating-data-dictionary-using-chatgpt
Sagar Lad
04 Jun 2023
4 min read
Save for later

Creating Data Dictionary Using ChatGPT

Sagar Lad
04 Jun 2023
4 min read
This article highlights how ChatGPT can create data dictionaries within minutes, aiding data professionals in documenting data items. By leveraging ChatGPT's capabilities, professionals gain deeper insights, enhancing data management. A practical example demonstrates the efficiency and effectiveness of using ChatGPT in generating data dictionaries. What is a data dictionary? Data professionals, such as data engineers, data scientists, analysts, database administrators, and developers, face various data challenges, ranging from business requirement definition to data volume and speed management. To effectively tackle these difficulties, they require a comprehensive understanding of the data. Data dictionaries play a vital role in providing deeper insights into the data. A data dictionary serves as documentation for the data, encompassing names, definitions, and attributes of the database's data items. Its main purpose is to comprehend and describe the significance of data items in relation to the application, along with including data element metadata. Data dictionaries are indispensable in data projects as they contribute to success by offering valuable insights into the data. Benefits of creating a data dictionary: Conquer data discrepancies Facilitate data exploration and analysisMaintain data standards throughout the projectEstablish uniform and consistent standards for the projectEstablish data standards to control the gathered data and explain it across the project A typical data dictionary has below components:  ComponentDescriptionData ElementName of the data elementDescription Definition of the data elementData TypeType of data stored in the attribute (ex. text, number, date)LengthMaximum number of characters stored in the attributeFormatFormat  for the data (e.g. date/currency format) Valid ValuesList of allowed values for the data elementRelationshipsRelationships between different tables in the databaseSource Origin of the data (e.g. system, department)ConstraintsRules related to the use of the dataListing of data objectsNames and DefinitionsDetailed properties of data elementsData type, Size, nullability, optionality, indexesBusiness rulesSchema validation or Data Quality Image 1 : Sample Database Schema with Data Attribute Name, Data Type & Constraints     As demonstrated in the example above, each database has a basic set of data about the data dictionary, but this information is insufficient when working with a database that has numerous tables, each of which may have multiple columns.  Creating a practical data dictionary with ChatGPT Data and natural language processing can be used by ChatGPT to produce in-depth knowledge on any subject. As a result, ChatGPT may be used to build instructive data dictionaries for any dataset.       Image 2: ChatGPT to create Data Dictionary Let’s understand the step-by-step process to create a data dictionary using ChatGPT: Finding and copying the data               Let us ask ChatGPT for one of the public datasets to create a data dictionary:    List of Data Sources recommended by ChatGPT Now, I will download the csv file named Institutions.csv from the FDIC Bank Data API. Image 4: Downloaded CSV file for FDIC Bank DataLet’s use this data to create a data dictionary using ChatGPT. Prepare ChatGPT Let’s now prompt the GPT to create a raw data dictionary for the dataset that we picked above:Image 5: Output Data Dictionary Request Data Dictionary with additional information Additionally, we can request that ChatGPT add new columns and other pertinent data to the output of the data dictionary. For instance, in the sample below, I've asked ChatGPT to add a new column called Active Loan and to provide descriptions to the columns based on its knowledge of banking. Output Data Dictionary from ChatGPT with additional columns and informationWe can now see that the data dictionary is updated which can be shared within the organization.ConclusionIn conclusion, leveraging ChatGPT's capabilities expedites the creation of data dictionaries, enhancing data management for professionals. Its efficiency and insights empower successful data projects, making ChatGPT a valuable tool in the data professional's toolkit. Author BioSagar Lad is a Cloud Data Solution Architect with a leading organization and has deep expertise in designing and building Enterprise-grade Intelligent Azure Data and Analytics Solutions. He is a published author, content writer, Microsoft Certified Trainer, and C# Corner MVP. Link - Medium, Amazon, LinkedIn.
Read more
  • 0
  • 0
  • 586

article-image-using-openai-python-library-to-interact-with-the-chatgpt-api
Martin Yanev
04 Jun 2023
7 min read
Save for later

Using OpenAI Python Library to Interact with the ChatGPT API

Martin Yanev
04 Jun 2023
7 min read
Using the ChatGPT API with Python is a relatively simple process. You'll first need to make sure you create a new PyCharm project called ChatGPTResponse as shown in the following screenshot: Fig 1: New Project Window in PyCharm Once you have that setup, you can use the OpenAI Python library to interact with the ChatGPT API. Open a new Terminal in PyCharm, make sure that you are in your project folder, and install the openai package: $ pip install openai Next, you need to create a new Python file in your PyCharm project on the left top corner perform a Right-click on the folder ChatGPTResponse | New | Python File. Name the file app.py and click hit Enter. You should now have a new Python file in your project directory: Fig 2: New Python File To get started, you'll need to import the openai library into your Python file. Also, you'll need to provide your OpenAI API Key. You can obtain an API Key from the OpenAI website by following the steps outlined in the previous sections of this book. Then you'll need to set it as a parameter in your Python code. Once your API Key is set up, you can start interacting with the ChatGPT API. import openaiopenai.api_key = "YOUR_API_KEY" Replace YOUR_API_KEY with the API key you obtained from the OpenAI platform page. Now, you can ask the user a question using the input() function: question = input("What would you like to ask ChatGPT? ") The input() function is used to prompt the user to input a question they would like to ask the ChatGPT API. The function takes a string as an argument, which is displayed to the user when the program is run. In this case, the question string is "What would you Like to ask ChatGPT?". When the user types their question and presses enter, the input() function will return the string that the user typed. This string is then assigned to the variable question. To pass the user question from your Python script to ChatGPT, you will need to use the ChatGPT API Completion function: response = openai.Completion.create(    engine="text-davinci-003",    prompt=question,    max_tokens=1024,    n=1,    stop=None,    temperature=0.8,) The openai.Completion.create() function in the code is used to send a request to the ChatGPT API to generate a completion of the user's input prompt. The engine parameter specifies the ChatGPT engine to use for the request, and in this case, it is set to "text-davinci-003". The prompt parameter specifies the text prompt for the API to complete, which is the user's input question in this case. The max_tokens parameter specifies the maximum number of tokens the response should contain.  The n parameter specifies the number of completions to generate for the prompt. The stop parameter specifies the sequence where the API should stop generating the response. The temperature parameter controls the creativity of the generated response. It ranges from 0 to 1. Higher values will result in more creative but potentially less coherent responses, while lower values will result in more predictable but potentially fewer interesting responses. Later in the book, we will delve into how these parameters impact the responses received from ChatGPT.The function returns a JSON object containing the generated response from the ChatGPT API, which then can be accessed and printed to the console in the next line of code.print(response)In the project pane on the left-hand side of the screen, locate the Python file you want to run. Right-click on the app.py file and select Run app.py from the context menu. You should receive a message in the Run window that asks you to write a question to the ChatGPT.  Fig 3: Run WindowOnce you have entered your question, press the Enter key to submit your request to the ChatGPT API. The response generated by the ChatGPT API model will be displayed in the Run window as a complete JSON object: {   "choices": [    {       "finish_reason": "stop",       "index": 0,       "logprobs": null,       "text": "\n\n1. Start by getting in the water. If you're swimming in a pool, you can enter the water from the side, ………….    }  ],   "created": 1681010983,   "id": "cmpl-73G2JJCyBTfwCdIyZ7v5CTjxMiS6W",   "model": "text-davinci-003",   "object": "text_completion",   "usage": {    "completion_tokens": 415,     "prompt_tokens": 4,     "total_tokens": 419  }} This JSON response produced by the OpenAI API contains information about the response generated by the GPT-3 model. This response consists of the following fields:The choices field contains an array of objects with the generated responses, which in this case only contains one response object. The text field within the response object contains the actual response generated by the GPT-3 model.The finish_reason field indicates the reason why the response was generated; in this case it was because the model reached the stop condition specified in the API request.The created field specifies the Unix timestamp of when the response was created. The id field is a unique identifier for the API request that generated this response.The model field specifies the GPT-3 model that was used to generate the response. The object field specifies the type of object that was returned, which in this case is text_completion.The usage field provides information about the resource usage of the API request. It contains information about the number of tokens used for the completion, the number of tokens in the prompt, and the total number of tokens used.The two most important parameter from the response is the text field, that contains the answer to the question asked to ChatGPT API. This is why most API users would like to access only that parameter from the JSON object. You can easily separate the text from the main body as follows: answer = response["choices"][0]["text"]print(answer)By following this approach, you can guarantee that the variable answer will hold the complete ChatGPT API text response, which you can then print to verify. Keep in mind that ChatGPT responses can significantly differ depending on the input, making each response unique.OpenAI:1. Start by getting in the water. If you're swimming in a pool, you can enter the water from the side, ladder, or diving board. If you are swimming in the ocean or lake, you can enter the water from the shore or a dock.2. Take a deep breath in and then exhale slowly. This will help you relax and prepare for swimming.Summary In this tutorial, you implemented a simple ChatGPT API response, by sending a request to generate a completion of a user's input prompt/question. You have also learned how to set up your API Key and how to prompt the user to input a question, and finally, how to access the generated response from ChatGPT in the form of a JSON object containing information about the response.  About the Author Martin Yanev is an experienced Software Engineer who has worked in the aerospace and medical industries for over 8 years. He specializes in developing and integrating software solutions for air traffic control and chromatography systems. Martin is a well-respected instructor with over 280,000 students worldwide, and he is skilled in using frameworks like Flask, Django, Pytest, and TensorFlow. He is an expert in building, training, and fine-tuning AI systems with the full range of OpenAI APIs. Martin has dual Master's degrees in Aerospace Systems and Software Engineering, which demonstrates his commitment to both practical and theoretical aspects of the industry.https://www.linkedin.com/in/martinyanev/https://www.udemy.com/user/martin-yanev-3/
Read more
  • 0
  • 0
  • 3202