One place for hosting & domains

      Library

      Build A Media Library with React, Redux, and Redux-saga – Part 1

      Introduction

      Building applications with React can be overwhelming even after you’ve understood the elegant philosophy behind it. More so, managing large applications with React can be confusing at first. The ecosystem has grown with great libraries to save you some nightmares. But that also makes it difficult at first to figure out which library to use.

      In this two-part tutorial, we’ll build and deploy a media library app. The application allows users to search and display images and short videos from external services (Flickr and Shutterstock). It would also allow users to select images and videos for preview.

      We will build this application with:

      We will be using Yahoo’s Flickr API and ShutterStock API for images and short videos respectively.

      This tutorial assumes you have a basic understanding of JavaScript and React. Don’t worry if you have none. We will walk through and build the application from the ground up.

      Part 1 of this tutorial would cover basic React setup with create-react-app package, organizing our project workflow, defining routes, and of course testing it out.

      In Part 2, we will be using Redux and its async libraries; we will set it up and then integrate it into our application. Finally, we will deploy our application to Heroku for sharing with our friends. Our application would look thus when we’re done.

      Our app will be structured to allow you to either contribute to it or use it as a sample boilerplate for bootstrapping your React/Redux applications.

      There are loads of React boilerplate out there to help you get started with React. But we’ll be using create-react-app authored by the Facebook team. It allows you to create React applications with no configuration. create-react-app provides developers with the benefits of a more complex setup out of the box.

      Let’s get started…

      First, install the package globally:

      1. npm install -g create-react-app

      Then, create the media-library application:

      1. create-react-app media-library

      Bam. Our React basic setup is complete with scripts to start, build, and eject. Take a look at your package.json.

      Let’s test it out.

      1. cd media-library
      2. npm start

      Now, we can structure our project directory and add other dependencies.

      1. npm install --save redux redux-saga [email protected] react-redux

      Then, remove the default sample app:

      1. rm -rf src/**

      Project Directory

      Media-library
          - public
              - favicon.ico
              - index.html
          - src
              - Api
                  - api.js
              - actions
                  - mediaActions.js
              - common
                  - Header.js
              - components
                  - HomePage.js
                  - PhotoPage.js
                  - VideoPage.js
              - constants
                  - actionTypes.js
              - containers
                  - App.js
                  - MediaGalleryPage.js
              - reducers
                  - imageReducer.js
                  - index.js
                  - initialState.js
                  - videoReducer.js
              - sagas
                  - mediaSaga.js
                  - index.js
                  - watcher.js
              - styles
                  - style.css
              - store
                  - configureStore.js
              - routes.js
              - index.js
          - package.json
      

      If the project directory looks verbose, just be patient, and let’s walk-through. The intent of the project structure is to allow you to extend the application’s functionality beyond this tutorial. This would help you stay organized moving forward.

      What the heck is happening up there?

      1. View layer is our React component. It makes a request for action based on interactions on/with the application.
      2. Action, commonly called action creator returns a formatted object of the action type and optional payload which is then dispatched to the store.
      3. Redux-saga is a Redux middleware for handling async operations like fetching photos and videos from our API. It makes asynchronous operations look like standard JavaScript synchronous code making it easy to read, test, and reason.
      4. APIs are resource locations to fetch photos and videos in our own case.
      5. Reducers are simply pure functions whose purpose in life is to accept the state tree and an action from the store; make a copy of the previous state, transform it and then return a new state to the store.
      6. Store is a single object that holds the complete state of your application. It delegates the reducer with the responsibility of changing state when an action is dispatched.

      When the store receives an updated state, it transmits to the view layer to be rerendered.

      Now that we understand the workflow, let’s dive into coding.

      common/Header.js

      import React from 'react';
      import { Link, IndexLink } from 'react-router';
      
      const Header = () => (
        <div className="text-center">
          <nav className="navbar navbar-default">
            <IndexLink to="/" activeClassName="active">Home</IndexLink>
            {" | "}
            <Link to="library" activeClassName="active">Library</Link>
          </nav>
        </div>
      );
      
      export default Header;
      

      Link allows you to navigate to different routes in your application.

      IndexLink is the same as Link with the exception of OnlyActiveOnIndex prop set on it.

      components/HomePage.js

      import React from 'react';
      import { Link } from 'react-router';
      
      
      const HomePage = () => (
        <div className="jumbotron center">
          <h1 className="lead">Welcome to Media Library built with React, Redux, and Redux-saga </h1>
          <div>
            <Link to="library">
              <button className="btn btn-lg btn-primary"> Visit Library</button>
            </Link>
          </div>
        </div>
      );
      
      export default HomePage;
      

      containers/App.js

      import React, { Component, PropTypes } from 'react';
      import Header from '../common/Header';
      
      
      
      class App extends Component {
        render() {
          return (
            <div className="container-fluid text-center">
              <Header />
              {this.props.children}
            </div>
          );
        }
      }
      App.propTypes = {
        children: PropTypes.object.isRequired
      };
      
      export default App;
      

      App component is the parent component of our app. Every other component is a child to it. this.props.children is where other child components are rendered.

      We will implement the library route and the component that maps to it in Part 2 of this tutorial.

      You would notice that for Header and HomePage components, we’re using stateless functional component. This approach allows us to separate our presentational components from the container components.

      It’s a good practice as it enforces functional composition and component reusability.
      Whereas container components are responsible for your business logic and connecting with the store, presentational components are responsible for the look of your view.

      Simply put, presentational components are components whose purpose in life is to render values to the DOM. Container components also known as smart components provide props and behavior to presentational components.

      Let’s wire up our project routes.

      routes.js

      import React from 'react';
      import { Route, IndexRoute } from 'react-router';
      import App from './containers/App';
      import HomePage from './components/HomePage';
      
      
      
      
      
      export default (
        <Route path="/" component={App}>
          <IndexRoute component={HomePage} />
        </Route>
      );
      

      Now let’s add the entrance to our application – index.js.

      import React from 'react';
      import ReactDOM from 'react-dom';
      import { Router, browserHistory } from 'react-router';
      import routes from './routes';
      
      
      ReactDOM.render(
          <Router history={browserHistory} routes={routes} />,
          document.getElementById('root')
      );
      

      We pass in our routes and browserHistory as props to Router here.
      browserHistory uses your browser’s History API to create a clean and real URL without the gibberish that comes with using hashHistory. hashHistory has its use case, though.

      Router is a high-level API that keeps your UI and URL in sync. It ensures that required props are passed whenever you change URL.

      ReactDOM is the API for mounting our application on the DOM node(root, in our own case).

      Two more things before we test our app.

      Add a bootstrap link to a CDN in our public/index.html.

      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
      

      Let’s add some custom styling.

      styles/style.css

      body {
        margin: 0;
        padding: 0;
        font-family: Helvetica, Arial, Sans-Serif, sans-serif;
        background: white;
      }
      
      .title {
        padding: 2px;
        text-overflow-ellipsis: overflow;
        overflow: hidden;
        display: block;
      }
      
      .selected-image, .select-video {
        height: 500px;
      }
      
      .selected-image img, .select-video video {
        width: 100%;
        height: 450px;
      }
      
      .image-thumbnail, .video-thumbnail {
        display: flex;
        justify-content: space-around;
        overflow: auto;
        overflow-y: hidden;
      }
      
      .image-thumbnail img, .video-thumbnail video {
        width: 70px;
        height: 70px;
        padding: 1px;
        border: 1px solid grey;
      }
      

      Let’s test our app now…

      1. npm start

      Navigate to http://localhost:3000 on your browser.

      Bam!!! We’re up again

      Building application with React gets better as you understand the flow. In this part, we did:

      1. Set up configurations.
      2. Set up the project structure.
      3. Complete Header, Homepage, and App (parent) components.
      4. Map routes to different components.
      5. What else? We tested our app.

      In the second part of this tutorial, we will be exploring the power of Redux, Redux-saga, and separating our state management system from the React components for scalability and maintainability.

      Decoding WordPress: The Media Library


      The WordPress Block Editor enables you to upload images and files directly to your site’s posts and pages. However, your media collection can become disorganized over time, and you might struggle to find media that you uploaded in the past.

      Fortunately, you can use the WordPress Media Library to organize your images and files. Thanks to multiple views and filters, you can develop an effective organizational system for your uploaded files. Additionally, you can optimize your images to rank higher in search results.

      In this post, we’ll give you an overview of the WordPress Media Library and its main features. Then, we’ll show you how to extend these features and fix any potential errors that occur. Let’s get started!

      An Introduction to the WordPress Media Library

      When you upload images, videos, and audio files to your WordPress website, these are stored in your Media Library. Essentially, this catalogs every piece of media you’ve used in your posts and pages.

      To open the Media Library, click on the Media tab in your admin dashboard. Then, you’ll be able to view your files and upload new ones if needed:

      WordPress Media Library

      Here are some files you may see in the Media Library:

      • Images (.jpeg, .jpeg, .png, .gif, .ico)
      • Audio files (.mp3, .m4a, .ogg, .wav)
      • Videos (.mp4, .mov, .wmv, .avi, .mpg, .ogv, .3gp, .3g2)
      • Documents (.pdf. .doc, .docx, .odt, .psd)
      • Spreadsheets (.xls, .xlsx)
      • Powerpoint presentations (.pps, .ppsx, .ppt, .pptx)

      If you need to narrow down your results by type, you can use the dropdown menu. Here, you’ll see the file types listed above, along with items labeled Unattached, Archives, and Mine:

      Media type

      You can also select a specific upload date. This can be particularly helpful if you’re unable to find an image but you know when it was uploaded:

      Upload date

      To organize your Media Library, you can use the Bulk select button. Then, you can select multiple images and delete them permanently:

      Bulk select

      In the top-right corner, you’ll see a search bar. Here, you can enter keywords to filter your results:

      Search Media Library

      Please note that you’ll have to have tagged the images with these keywords beforehand — but adding this little bit of extra effort to your workflow can make a huge difference when you’re trying to find things in the future.

      As you can see, the Media Library can help you organize the files on your website. It provides an all-in-one solution for uploading, editing, and deleting files.

      5 Useful Media Library Features

      If you’re new to WordPress, you might not know how to use the Media Library. Fortunately, this tool is very user-friendly, and it enables you to upload, view, and edit media files on your website. Let’s take a look at its main features.

      1. Multiple Views

      The Media Library lets you change the way files are displayed. You can either view them in a grid or a list.

      By default, the Media Library shows items in a grid view, with a thumbnail for each file:

      Grid view

      As we mentioned earlier, you can filter the results by media type and date. If you want to view the details of a certain file, you just have to click on it:

      Grid view attachment details

      Alternatively, you can switch to the list view. Instead of a gallery-like grid, your files will be displayed in a list:

      List view

      On the left-hand side, you can use the checkboxes to bulk-select files. Next to this, you’ll see a thumbnail representing each media item.

      Here’s what else you can see in a list view:

      • File: The file title, as well as the full name of the file.
      • Author: The user that uploaded the file.
      • Uploaded to: The title of the post or page where the file was uploaded.
      • Comment bubble: The number of comments for that file.
      • Date: The date when the media was uploaded.

      If you click on the file name, this will open the image editor:

      List view image editor

      You can switch between these two views at any time, depending on your preference. However, the list view can be a better option if you want to view a file’s details without having to click on it.

      2. Multiple Ways to Upload Files

      When you need to upload a file to your website, you can add it directly to a post or page. The Block Editor lets you add images, videos, and other files with blocks:

      Image block

      Once you select the relevant block, you can click on Upload and choose a file from your computer. If you’ve uploaded the file to WordPress before, you can select it from your Media Library:

      Upload from Media Library

      You can also drag and drop a file directly into this section. This will automatically upload it into the Media Library, and you can then add it to the post:

      Upload new file

      You can also upload images directly to the Media Library. Simply click on Add New, then drag and drop files into the upload area or select them from your computer:

      Add new media file

      With any of these methods, your media files will be automatically imported into WordPress. Even if you uploaded your files in the Block Editor, you’ll still be able to find them in the Media Library.

      3. Downloadable Files

      The Media Library also lets you download your files to your computer. This can be useful if you need to use the same images or videos on another site.

      To download a file from your WordPress dashboard, click on the Tools tab and select Export:

      WordPress export

      On this page, you can download all of your site’s content. This includes posts, pages, and media files.

      Select Media, then use the dropdown menus to download files that were uploaded within a certain timeframe. You’ll simply have to specify a Start date and End date:

      Export media

      If you want to download all of your media files, you can leave these fields blank. When you’re finished, click on Download Export File. This will download links to the relevant files to your computer in an XML file format that can then be imported into another WordPress install.

      4. Image Editing

      As a website owner, it’s vital that you optimize your images before publishing them. Large files can slow down your site and take up a lot of storage space.

      The Media Library has many native image editing features. For example, you can crop your images, scale them, and more.

      Start by clicking on an image to open the Attachment details page. Then, under the photo, select the Edit image button:

      Edit image

      This will automatically open the image editor. On the left, you’ll see options to crop, rotate, or flip the image:

      Image editing features

      If you select the Crop button, you can use the handles on the box to remove certain parts of the image. When you’re finished, click on Crop again:

      Crop image

      Using the rotate options, you can flip the image 90 degrees to the left or right:

      Rotate image

      If you need to invert the image, you can use the Flip buttons. These will reflect the photo vertically or horizontally:

      Flip image

      On the right side of the page, you’ll see the original dimensions of the image. To scale the image, you’ll just need to enter the new dimensions:

      Scale image

      Additionally, you can click on the Crop button and enter the size in the Selection fields. You can also choose an Aspect ratio, which is the relationship between the height and width of the image:

      Image crop selection

      The last feature you’ll see in the image editor is the Thumbnail Settings. Here, you can apply your changes to all image sizes, the thumbnail only, or all sizes except the thumbnail:

      Thumbnail settings

      When you’re finished, save your changes. You can now view the edited photo in the Media Library.

      5. Image Metadata

      In the Attachment details page of your image, you’ll see an option to add metadata. This contains basic information about the image, including the file name, author, and description:

      Image metadata

      After you upload an image, WordPress will use the file name as its title. However, you can edit this to provide a more accurate description:

      Image title

      You can also add alternative text. This describes the contents of the image when it can’t be displayed. Additionally, it can make your website more accessible to users with screen readers:

      Add alt text

      Along with improving user experience, alternative text can boost your search ranking. It enables search engines to understand your images and their purpose on the page.

      You might also want to write a caption and description to provide more information about the image. While the alt text is only visible to search engines and screen readers, the caption is visible to all front-end users:

      Image caption

      Meanwhile, descriptions will appear on the image attachment page. Here, you can post copyright details, keywords, links, and more:

      Image description

      This information will be saved in the Media Library. When someone visits the image URL, they’ll be able to see its description.

      How to Extend the Features in the Media Library

      The Media Library provides the essential tools you need to upload and edit media files. However, you may need to install a plugin to extend its core functionality.

      As you upload more images to your website, your Media Library can get a little disorganized. Although you can delete images in bulk and use filters to find what you need, you may become overwhelmed by the volumes of files on your website.

      With the Real Media Library plugin, you can create folders in your Media Library:

      Real Media Library

      This tool has a drag-and-drop interface that enables you to easily move media items to different sections. Plus, the pro version supports subfolders, image galleries, and rearranging within a folder.

      Alternatively, you can use the free version of Media Library Organizer to add media categories for better media management:

      Media Library Organizer

      The native editing features in the Media Library may not fully optimize your images. Often, you’ll need to compress image files in order to speed up your website.

      With the TinyPNG plugin, you can let your WordPress install automatically compress your images as you upload them:

      TinyPNG plugin

      Additionally, you may want to replace old files with newer versions. With the Media Library, you’ll have to upload the new file, locate the old version, and delete it.

      Enable Media Replace is a popular WordPress plugin that you can use to quickly replace files in your Media Library:

      Enable Media Replace

      Even though you might not need these tools, they are available to help you optimize your website and manage your files more efficiently. They can be particularly useful when activated on media-heavy sites.

      How to Fix Common Media Library Errors

      Although the Media Library is very user-friendly, you might run into some common image upload issues. Fortunately, most of these problems are easy to fix.

      HTTP Error

      One of the most common issues in the Media Library is an undefined HTTP error. This crops up when something goes wrong during the upload process.

      When this happens, it’s a good idea to wait a few minutes before trying to upload the file again. Sometimes, it’s just a temporary resource allocation problem.

      Alternatively, this common image error could be caused by your browser. You can try switching to another browser to see if it solves the problem.

      If the error persists, you can try clearing your browser cache and deactivating your plugins. Alternatively, you might need to increase your site’s memory limit.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      Upload: Failed to Write File to Disk

      When you’re uploading files to your website, you may also come across the Upload: Failed to Write File to Disk error. Usually, this results from incorrect file permissions. However, you could have maxed out your hosting plan’s disk space limit or temporary folder.

      To fix this error, you’ll need to check the file permissions for your website. First, you’ll need to connect to a Secure File Transfer Protocol (SFTP) client to access your site files. Alternatively, you can use the File Manager in your hosting account.

      If you have a DreamHost account, open your dashboard and go to Websites > Files and FTP Users:

      DreamHost manage files

      Then, click on Manage Files next to your website. In your File Manager, find the wp-content file and right-click on it:

      Open file permissions

      For DreamHost accounts, you can select CHMOD. If you’re using another program, click on the File Permissions option. This will open a pop-up window:

      File permissions

      Make sure the Numeric value is set to ‘755’. Then, click on OK to save your changes. This should help resolve the issue.

      Media Library Failing to Load

      Occasionally, your Media Library might fail to load altogether. This can happen if you’re using a poorly-coded theme or plugin.

      You might also see this error when there’s a conflict between two plugins. Third-party software can cause compatibility issues with other programs.

      To resolve the issue, start by deactivating your plugins. Select them all, then choose Deactivate from the Bulk actions menu and hit Apply:

      Deactivate plugins

      Now, refresh the Media Library page to see if this solved the problem. If so, you’ll need to reactivate each plugin one at a time and keep refreshing the Media Library until the issue reappears. This should help you identify the culprit.

      If deactivating the plugins doesn’t help, then the problem might be your theme. Consider activating a default WordPress theme, then try accessing your Media Library again.

      Organize Your WordPress Images

      The WordPress Media Library enables you to upload, modify, and delete files on your website. You can also use it to crop and scale images without leaving your dashboard.

      To review, here are the main things you can do in the Media Library:

      1. View uploads in a grid or list view.
      2. Upload files in the Media Library or Block Editor.
      3. Download files to your computer.
      4. Edit image size, pixels, and orientation.
      5. Add image metadata.

      Although optimizing images can improve your loading times, you’ll want to build a fast website from the ground up. Our managed WordPress hosting plans come with several performance tools to help you grow your site. Check out our plans today!

      Do More with DreamPress

      DreamPress Plus and Pro users get access to Jetpack Professional (and 200+ premium themes) at no added cost!

      Managed WordPress Hosting - DreamPress



      Source link

      How To Create an Intelligent Chatbot in Python Using the spaCy NLP Library


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Interacting with software can be a daunting task in cases where there are a lot of features. In some cases, performing similar actions requires repeating steps, like navigating menus or filling forms each time an action is performed. Chatbots are virtual assistants that help users of a software system access information or perform actions without having to go through long processes. Many of these assistants are conversational, and that provides a more natural way to interact with the system.

      To create a conversational chatbot, you could use platforms like Dialogflow that help you design chatbots at a high level. Or, you can build one yourself using a library like spaCy, which is a fast and robust Python-based natural language processing (NLP) library. spaCy provides helpful features like determining the parts of speech that words belong to in a statement, finding how similar two statements are in meaning, and so on.

      In this tutorial, you will create a chatbot that not only helps users simplify their interactions with a software system, but is also intelligent enough to communicate with the user in natural language (American English in this tutorial). The chatbot will use the OpenWeather API to tell the user what the current weather is in any city of the world, but you can implement your chatbot to handle a use case with another API.

      Prerequisites

      Before you begin, you will need the following:

      This tutorial assumes you are already familiar with Python—if you would like to improve your knowledge of Python, check out our How To Code in Python 3 series. This tutorial does not require foreknowledge of natural language processing.

      Step 1 — Setting Up Your Environment

      In this step, you will install the spaCy library that will help your chatbot understand the user’s sentences.

      Having set up Python following the Prerequisites, you’ll have a virtual environment. Let’s activate that environment.

      Make sure you are in the directory where you set up your environment and then run the following command:

      • source my_env/bin/activate

      Now install spaCy:

      Finally, you will download a language model. spaCy’s language models are pre-trained NLP models that you can use to process statements to extract meaning. You’ll be working with the English language model, so you’ll download that.

      Run the following command:

      • python -m spacy download en_core_web_md

      If you run into an error like the following:

      Output

      ERROR: Failed building wheel for en-core-web-md

      You need to install wheel:

      Then download the English-language model again.

      To confirm that you have spaCy installed properly, open the Python interpreter:

      Next, import spaCy and load the English-language model:

      >>> import spacy
      >>> nlp = spacy.load("en_core_web_md")
      

      If those two statements execute without any errors, then you have spaCy installed.

      Now close the Python interpreter:

      >>> exit()
      

      You now have everything needed to begin working on the chatbot. In the next section, you’ll create a script to query the OpenWeather API for the current weather in a city.

      Step 2 — Creating the City Weather Program

      In this section, you will create a script that accepts a city name from the user, queries the OpenWeather API for the current weather in that city, and displays the response.

      First, create and open a Python file called weather_bot.py with your preferred editor:

      Next, you’ll create a function to get the current weather in a city from the OpenWeather API. This function will take the city name as a parameter and return the weather description of the city.

      Add the following code into your weather_bot.py file:

      weather_bot.py

      import requests
      
      api_key = "your_api_key"
      
      def get_weather(city_name):
          api_url = "http://api.openweathermap.org/data/2.5/weather?q={}&appid={}".format(city_name, api_key)
      
          response = requests.get(api_url)
          response_dict = response.json()
      
          weather = response_dict["weather"][0]["description"]
      
          if response.status_code == 200:
              return weather
          else:
              print('[!] HTTP {0} calling [{1}]'.format(response.status_code, api_url))
              return None
      

      First, you import the requests library, so you are able to work with and make HTTP requests. Make sure to replace your_api_key with your own API key. The next line begins the definition of the function get_weather() to retrieve the weather of the specified city.

      In this function, you construct the URL for the OpenWeather API. This URL returns the weather information (temperature, weather description, humidity, and so on) of the city and provides the result in JSON format. After that, you make a GET request to the API endpoint, store the result in a response variable, and then convert the response to a Python dictionary for easier access.

      On the next line, you extract just the weather description into a weather variable and then ensure that the status code of the API response is 200 (meaning there were no issues with the request). Finally, you return the weather description.

      If there is an issue with the request, the status code is printed out to the console, and you return None.

      To test the script, call the get_weather() function with a city of your choice (for example, London) and print the result. Add the highlighted code following your function:

      ~/weather_bot.py

      import requests
      
      def get_weather(city_name):
      
        ...
      
        return weather
      
      weather = get_weather("London")
      print(weather)
      

      Save and run the script:

      You will receive a result like the following:

      Output

      scattered clouds

      Having completed that successfully, you can now delete the last two lines from the script.

      Open it with:

      Then delete the two highlighted lines at the end of the file:

      ~/weather_bot.py

      import requests
      
      def get_weather(city_name):
      
        ...
      
        return weather
      
      weather = get_weather("London")
      print(weather)
      

      Save and close the file.

      You now have a function that returns the weather description for a particular city.

      In the next step, you’ll create a chatbot capable of figuring out whether the user wants to get the current weather in a city, and if so, the chatbot will use the get_weather() function to respond appropriately.

      Step 3 — Creating the Chatbot

      In the previous two steps, you installed spaCy and created a function for getting the weather in a specific city. Now, you will create a chatbot to interact with a user in natural language using the weather_bot.py script.

      You’ll write a chatbot() function that compares the user’s statement with a statement that represents checking the weather in a city. To make this comparison, you will use the spaCy similarity() method. This method computes the semantic similarity of two statements, that is, how similar they are in meaning. This will help you determine if the user is trying to check the weather or not.

      To begin, open the script:

      Then, import spaCy and load the English language model:

      ~/weather_bot.py

      import spacy
      import requests
      
      nlp = spacy.load("en_core_web_md")
      
      . . .
      
      

      After the get_weather() function in your file, create a chatbot() function representing the chatbot that will accept a user’s statement and return a response.

      Following your definition, add the highlighted code to create tokens for the two statements you’ll be comparing. Tokens are the different meaningful segments of a statement, like words and punctuation. This is necessary to allow spaCy to compute the semantic similarity:

      ~/weather_bot.py

      import spacy
      
      . . .
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
      

      Here the weather and statement variables contain spaCy tokens as a result of passing each corresponding string to the nlp() function.

      Save and close your file.

      Next you’ll be introducing the spaCy similarity() method to your chatbot() function. The similarity() method computes the semantic similarity of two statements as a value between 0 and 1, where a higher number means a greater similarity. You need to specify a minimum value that the similarity must have in order to be confident the user wants to check the weather.

      For example, if you check the similarity of statements 2 and 3 with statement 1 following, you get:

      1. Current weather in a city
      2. What is the weather in London? (similarity = 0.86)
      3. Peanut butter and jelly (similarity = 0.31)

      To try this for yourself, open the Python interpreter:

      Next, import spaCy and load the English-language model:

      >>> import spacy
      >>> nlp = spacy.load("en_core_web_md")
      

      Now let’s create tokens from statements 1 and 2:

      >>> statement1 = nlp("Current weather in a city")
      >>> statement2 = nlp("What is the weather in London?")
      

      Finally, let’s obtain the semantic similarity of the two statements:

      >>> print(statement1.similarity(statement2))
      

      You will receive a result like this:

      Output

      0.8557684354027663

      Setting a low minimum value (for example, 0.1) will cause the chatbot to misinterpret the user by taking statements (like statement 3) as similar to statement 1, which is incorrect. Setting a minimum value that’s too high (like 0.9) will exclude some statements that are actually similar to statement 1, such as statement 2.

      We will arbitrarily choose 0.75 for the sake of this tutorial, but you may want to test different values when working on your project.

      Let’s add this value to the script. First, open the file:

      Then add the following highlighted code to introduce the minimum value:

      ~/weather_bot.py

      import spacy
      
      . . .
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      

      Now check if the similarity of the user’s statement to the statement about the weather is greater than or equal to the minimum similarity value you specified. Add the following highlighted if statement to check this:

      ~/weather_bot.py

      import spacy
      
      . . .
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      
        if weather.similarity(statement) >= min_similarity:
          pass
      

      The final step is to extract the city from the user’s statement so you can pass it to the get_weather() function to retrieve the weather from the API call. Add the following highlighted for loop to implement this:

      ~/weather_bot.py

      import spacy
      
      ...
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      
        if weather.similarity(statement) >= min_similarity:
          for ent in statement.ents:
            if ent.label_ == "GPE": # GeoPolitical Entity
              city = ent.text
              break
      

      To do this, you’re using spaCy’s named entity recognition feature. A named entity is a real-world noun that has a name, like a person, or in our case, a city. You want to extract the name of the city from the user’s statement.

      To extract the city name, you get all the named entities in the user’s statement and check which of them is a geopolitical entity (country, state, city). To do this, you loop through all the entities spaCy has extracted from the statement in the ents property, then check whether the entity label (or class) is “GPE” representing Geo-Political Entity. If it is, then you save the name of the entity (its text) in a variable called city.

      You also need to catch cases where no city was entered by adding an else block:

      ~/weather_bot.py

      import spacy
      
      ...
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      
        if weather.similarity(statement) >= min_similarity:
          for ent in statement.ents:
            if ent.label_ == "GPE": # GeoPolitical Entity
              city = ent.text
              break
            else:
              return "You need to tell me a city to check."
      

      Now that you have the city, you can call the get_weather() function:

      ~/weather_bot.py

      import spacy
      
      ...
      
      def chatbot(statement):
        weather = nlp("Current weather in a city")
        statement = nlp(statement)
        min_similarity = 0.75
      
        if weather.similarity(statement) >= min_similarity:
          for ent in statement.ents:
            if ent.label_ == "GPE": # GeoPolitical Entity
              city = ent.text
              break
            else:
              return "You need to tell me a city to check."
      
          city_weather = get_weather(city)
          if city_weather is not None:
            return "In " + city + ", the current weather is: " + city_weather
          else:
            return "Something went wrong."
        else:
          return "Sorry I don't understand that. Please rephrase your statement."
      

      Recall that if an error is returned by the OpenWeather API, you print the error code to the terminal, and the get_weather() function returns None. In this code, you first check whether the get_weather() function returns None. If it doesn’t, then you return the weather of the city, but if it does, then you return a string saying something went wrong. The final else block is to handle the case where the user’s statement’s similarity value does not reach the threshold value. In such a case, you ask the user to rephrase their statement.

      Having completed all of that, you now have a chatbot capable of telling a user conversationally what the weather is in a city. The difference between this bot and rule-based chatbots is that the user does not have to enter the same statement every time. Instead, they can phrase their request in different ways and even make typos, but the chatbot would still be able to understand them due to spaCy’s NLP features.

      Let’s test the bot. Call the chatbot() function and pass in a statement asking what the weather is in a city, for example:

      ~/weather_bot.py

      import spacy
      
      . . .
      
      def chatbot(statement):
      
      . . .
      
      response = chatbot("Is it going to rain in Rome today?")
      print(response)
      

      Save and close the file, then run the script in your terminal:

      You will receive output similar to the following:

      Output

      In Rome, the current weather is: clear sky

      You have successfully created an intelligent chatbot capable of responding to dynamic user requests. You can try out more examples to discover the full capabilities of the bot. To do this, you can get other API endpoints from OpenWeather and other sources. Another way to extend the chatbot is to make it capable of responding to more user requests. For this, you could compare the user’s statement with more than one option and find which has the highest semantic similarity.

      Conclusion

      You have created a chatbot that is intelligent enough to respond to a user’s statement—even when the user phrases their statement in different ways. The chatbot uses the OpenWeather API to get the current weather in a city specified by the user.

      To further improve the chatbot, you can:



      Source link