Daniel Bark

Daniel Bark

1641552280

Self reproducing Code that prints itself - Quines in Javascript

https://www.youtube.com/watch?v=qJ4ea50Vv8E

A quine is a program that writes its own source code. Let's create our own. 
The Art of code talk: https://www.youtube.com/watch?v=6avJH... 
Twitter: https://twitter.com/BarelyDaniel 
Github: https://github.com/danba340

What is GEEK

Buddha Community

Self reproducing Code that prints itself - Quines in Javascript
Tamale  Moses

Tamale Moses

1669003576

Exploring Mutable and Immutable in Python

In this Python article, let's learn about Mutable and Immutable in Python. 

Mutable and Immutable in Python

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.

Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.

Mutable Definition

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.

Immutable Definition

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

List of Mutable and Immutable objects

Objects of built-in type that are mutable are:

  • Lists
  • Sets
  • Dictionaries
  • User-Defined Classes (It purely depends upon the user to define the characteristics) 

Objects of built-in type that are immutable are:

  • Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
  • Strings
  • Tuples
  • Frozen Sets
  • User-Defined Classes (It purely depends upon the user to define the characteristics)

Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.

Objects in Python

In Python, everything is treated as an object. Every object has these three attributes:

  • Identity – This refers to the address that the object refers to in the computer’s memory.
  • Type – This refers to the kind of object that is created. For example- integer, list, string etc. 
  • Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2 and 3

While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.

Check out this free python certificate course to get started with Python.

Mutable Objects in Python

I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:

#Creating a list which contains name of Indian cities  

cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:
		print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [2]: 0x1691d7de8c8

#Adding a new city to the list cities

cities.append(‘Chennai’)

#Printing the elements from the list cities, separated by a comma & space 

for city in cities:
	print(city, end=’, ’)

Output [3]: Delhi, Mumbai, Kolkata, Chennai

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [4]: 0x1691d7de8c8

The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.

Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.

Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0. 

#Creating a Tuple with variable name ‘foo’

foo = (1, 2)

#Changing the index[0] value from 1 to 3

foo[0] = 3
	
TypeError: 'tuple' object does not support item assignment 

Immutable Objects in Python

Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:

#Creating a Tuple which contains English name of weekdays

weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays

print(weekdays)

Output [1]:  (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [2]: 0x1691cc35090

#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’

weekdays  +=  ‘Pythonday’,

#Printing the elements of tuple weekdays

print(weekdays)

Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [4]: 0x1691cc8ad68

This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it.  Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.

Also Read: Understanding the Exploratory Data Analysis (EDA) in Python

Where can you use mutable and immutable objects:

Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.

Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.

Watch outs:  Non transitive nature of Immutability:

OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–

#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements

#The elements (lists) contains the name, age & gender 

person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the tuple

print(person)

Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [2]: 0x1691ef47f88

#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4

person[0][1] = 4

#printing the updated tuple

print(person)

Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [4]: 0x1691ef47f88

In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.

Also Read: Real-Time Object Detection Using TensorFlow

Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–

#creating a list (mutable object) which contains tuples(immutable) as it’s elements

list1 = [(1, 2, 3), (4, 5, 6)]

#printing the list

print(list1)

Output [1]: [(1, 2, 3), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [2]: 0x1691d5b13c8	

#changing object reference at index 0

list1[0] = (7, 8, 9)

#printing the list

Output [3]: [(7, 8, 9), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [4]: 0x1691d5b13c8

As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.

Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’ 

x = 10
 

#printing the value of ‘x’

print(x)

Output [1]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(x)))

Output [2]: 0x538fb560

#creating an object of integer type with value 10 and reference variable name ‘y’

y = 10

#printing the value of ‘y’

print(y)

Output [3]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(y)))

Output [4]: 0x538fb560

As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.

Quick checkPython Data Structures

Immutability of Tuple

Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.

Exceptions in immutability

Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.

Consider a tuple ‘tup’.

Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;

We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.

FAQs

1. Difference between mutable vs immutable in Python?

Mutable ObjectImmutable Object
State of the object can be modified after it is created.State of the object can’t be modified once it is created.
They are not thread safe.They are thread safe
Mutable classes are not final.It is important to make the class final before creating an immutable object.

2. What are the mutable and immutable data types in Python?

  • Some mutable data types in Python are:

list, dictionary, set, user-defined classes.

  • Some immutable data types are: 

int, float, decimal, bool, string, tuple, range.

3. Are lists mutable in Python?

Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)

4. Why are tuples called immutable types?

Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.

A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.

5. Are sets mutable in Python?

A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.

6. Are strings mutable in Python?

Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.

Join Great Learning Academy’s free online courses and upgrade your skills today.


Original article source at: https://www.mygreatlearning.com

#python 

How to Bash Read Command

Bash has no built-in function to take the user’s input from the terminal. The read command of Bash is used to take the user’s input from the terminal. This command has different options to take an input from the user in different ways. Multiple inputs can be taken using the single read command. Different ways of using this command in the Bash script are described in this tutorial.

Syntax

read [options] [var1, var2, var3…]

The read command can be used without any argument or option. Many types of options can be used with this command to take the input of the particular data type. It can take more input from the user by defining the multiple variables with this command.

Some Useful Options of the Read Command

Some options of the read command require an additional parameter to use. The most commonly used options of the read command are mentioned in the following:

OptionPurpose
-d <delimiter>It is used to take the input until the delimiter value is provided.
-n <number>It is used to take the input of a particular number of characters from the terminal and stop taking the input earlier based on the delimiter.
-N <number>It is used to take the input of the particular number of characters from the terminal, ignoring the delimiter.
-p <prompt>It is used to print the output of the prompt message before taking the input.
-sIt is used to take the input without an echo. This option is mainly used to take the input for the password input.
-aIt is used to take the input for the indexed array.
-t <time>It is used to set a time limit for taking the input.
-u <file descriptor>It is used to take the input from the file.
-rIt is used to disable the backslashes.

 

Different Examples of the Read Command

The uses of read command with different options are shown in this part of this tutorial.

Example 1: Using Read Command without Any Option and variable

Create a Bash file with the following script that takes the input from the terminal using the read command without any option and variable. If no variable is used with the read command, the input value is stored in the $REPLY variable. The value of this variable is printed later after taking the input.

#!/bin/bash  
#Print the prompt message
echo "Enter your favorite color: "  
#Take the input
read  
#Print the input value
echo "Your favorite color is $REPLY"

Output:

The following output appears if the “Blue” value is taken as an input:

Example 2: Using Read Command with a Variable

Create a Bash file with the following script that takes the input from the terminal using the read command with a variable. The method of taking the single or multiple variables using a read command is shown in this example. The values of all variables are printed later.

#!/bin/bash  
#Print the prompt message
echo "Enter the product name: "  
#Take the input with a single variable
read item

#Print the prompt message
echo "Enter the color variations of the product: "  
#Take three input values in three variables
read color1 color2 color3

#Print the input value
echo "The product name is $item."  
#Print the input values
echo "Available colors are $color1, $color2, and $color3."

Output:

The following output appears after taking a single input first and three inputs later:

Example 3: Using Read Command with -p Option

Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -p option. The input value is printed later.

#!/bin/bash  
#Take the input with the prompt message
read -p "Enter the book name: " book
#Print the input value
echo "Book name: $book"

Output:

The following output appears after taking the input:

Example 4: Using Read Command with -s Option

Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -s option. The input value of the password will not be displayed for the -s option. The input values are checked later for authentication. A success or failure message is also printed.

#!/bin/bash  
#Take the input with the prompt message
read -p "Enter your email: " email
#Take the secret input with the prompt message
read -sp "Enter your password: " password

#Add newline
echo ""

#Check the email and password for authentication
if [[ $email == "admin@example.com" && $password == "secret" ]]
then
   #Print the success message
   echo "Authenticated."
else
   #Print the failure message
   echo "Not authenticated."
fi

Output:

The following output appears after taking the valid and invalid input values:

Example 5: Using Read Command with -a Option

Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -a option. The array values are printed later after taking the input values from the terminal.

#!/bin/bash  
echo "Enter the country names: "  
#Take multiple inputs using an array  
read -a countries

echo "Country names are:"
#Read the array values
for country in ${countries[@]}
do
    echo $country
done

Output:

The following output appears after taking the array values:

Example 6: Using Read Command with -n Option

Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -n option.

#!/bin/bash  
#Print the prompt message
echo "Enter the product code: "  
#Take the input of five characters
read -n 5 code
#Add newline
echo ""
#Print the input value
echo "The product code is $code"

Output:

The following output appears if the “78342” value is taken as input:

Example 7: Using Read Command with -t Option

Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -t option.

#!/bin/bash  
#Print the prompt message
echo -n "Write the result of 10-6: "  
#Take the input of five characters
read -t 3 answer

#Check the input value
if [[ $answer == "4" ]]
then
   echo "Correct answer."
else
   echo "Incorrect answer."
fi

Output:

The following output appears after taking the correct and incorrect input values:

Conclusion

The uses of some useful options of the read command are explained in this tutorial using multiple examples to know the basic uses of the read command.

Original article source at: https://linuxhint.com/

#bash #command 

Monty  Boehm

Monty Boehm

1675304280

How to Use Hotwire Rails

Introduction

We are back with another exciting and much-talked-about Rails tutorial on how to use Hotwire with the Rails application. This Hotwire Rails tutorial is an alternate method for building modern web applications that consume a pinch of JavaScript.

Rails 7 Hotwire is the default front-end framework shipped with Rails 7 after it was launched. It is used to represent HTML over the wire in the Rails application. Previously, we used to add a hotwire-rails gem in our gem file and then run rails hotwire: install. However, with the introduction of Rails 7, the gem got deprecated. Now, we use turbo-rails and stimulus rails directly, which work as Hotwire’s SPA-like page accelerator and Hotwire’s modest JavaScript framework.

What is Hotwire?

Hotwire is a package of different frameworks that help to build applications. It simplifies the developer’s work for writing web pages without the need to write JavaScript, and instead sending HTML code over the wire.

Introduction to The Hotwire Framework:

1. Turbo:

It uses simplified techniques to build web applications while decreasing the usage of JavaScript in the application. Turbo offers numerous handling methods for the HTML data sent over the wire and displaying the application’s data without actually loading the entire page. It helps to maintain the simplicity of web applications without destroying the single-page application experience by using the below techniques:

Turbo Frames: Turbo Frames help to load the different sections of our markup without any dependency as it divides the page into different contexts separately called frames and updates these frames individually.
Turbo Drive: Every link doesn’t have to make the entire page reload when clicked. Only the HTML contained within the tag will be displayed.
Turbo Streams: To add real-time features to the application, this technique is used. It helps to bring real-time data to the application using CRUD actions.

2. Stimulus

It represents the JavaScript framework, which is required when JS is a requirement in the application. The interaction with the HTML is possible with the help of a stimulus, as the controllers that help those interactions are written by a stimulus.

3. Strada

Not much information is available about Strada as it has not been officially released yet. However, it works with native applications, and by using HTML bridge attributes, interaction is made possible between web applications and native apps.

Simple diagrammatic representation of Hotwire Stack:

Hotwire Stack

Prerequisites For Hotwire Rails Tutorial

As we are implementing the Ruby on Rails Hotwire tutorial, make sure about the following installations before you can get started.

  • Ruby on Rails
  • Hotwire gem
  • PostgreSQL/SQLite (choose any one database)
  • Turbo Rails
  • Stimulus.js

Looking for an enthusiastic team of ROR developers to shape the vision of your web project?
Contact Bacancy today and hire Ruby developers to start building your dream project!

Create a new Rails Project

Find the following commands to create a rails application.

mkdir ~/projects/railshotwire
cd ~/projects/railshotwire
echo "source 'https://rubygems.org'" > Gemfile
echo "gem 'rails', '~> 7.0.0'" >> Gemfile
bundle install  
bundle exec rails new . --force -d=postgresql

Now create some files for the project, up till now no usage of Rails Hotwire can be seen.
Fire the following command in your terminal.

  • For creating a default controller for the application
echo "class HomeController < ApplicationController" > app/controllers/home_controller.rb
echo "end" >> app/controllers/home_controller.rb
  • For creating another controller for the application
echo "class OtherController < ApplicationController" > app/controllers/other_controller.rb
echo "end" >> app/controllers/home_controller.rb
  • For creating routes for the application
echo "Rails.application.routes.draw do" > config/routes.rb
echo '  get "home/index"' >> config/routes.rb
echo '  get "other/index"' >> config/routes.rb
echo '  root to: "home#index"' >> config/routes.rb
echo 'end' >> config/routes.rb
  • For creating a default view for the application
mkdir app/views/home
echo '<h1>This is Rails Hotwire homepage</h1>' > app/views/home/index.html.erb
echo '<div><%= link_to "Enter to other page", other_index_path %></div>' >> app/views/home/index.html.erb
  • For creating another view for the application
mkdir app/views/other
echo '<h1>This is Another page</h1>' > app/views/other/index.html.erb
echo '<div><%= link_to "Enter to home page", root_path %></div>' >> app/views/other/index.html.erb
  • For creating a database and schema.rb file for the application
bin/rails db:create
bin/rails db:migrate
  • For checking the application run bin/rails s and open your browser, your running application will have the below view.

Rails Hotwire Home Page

Additionally, you can clone the code and browse through the project. Here’s the source code of the repository: Rails 7 Hotwire application

Now, let’s see how Hotwire Rails can work its magic with various Turbo techniques.

Hotwire Rails: Turbo Drive

Go to your localhost:3000 on your web browser and right-click on the Inspect and open a Network tab of the DevTools of the browser.

Now click on go to another page link that appears on the home page to redirect from the home page to another page. In our Network tab, we can see that this action of navigation is achieved via XHR. It appears only the part inside HTML is reloaded, here neither the CSS is reloaded nor the JS is reloaded when the navigation action is performed.

Hotwire Rails Turbo Drive

By performing this action we can see that Turbo Drive helps to represent the HTML response without loading the full page and only follows redirect and reindeer HTML responses which helps to make the application faster to access.

Hotwire Rails: Turbo Frame

This technique helps to divide the current page into different sections called frames that can be updated separately independently when new data is added from the server.
Below we discuss the different use cases of Turbo frame like inline edition, sorting, searching, and filtering of data.

Let’s perform some practical actions to see the example of these use cases.

Make changes in the app/controllers/home_controller.rb file

#CODE

class HomeController < ApplicationController
   def turbo_frame_form
   end
   
   def turbo_frame submit
      extracted_anynumber = params[:any][:anynumber]
      render :turbo_frame_form, status: :ok, locals: {anynumber: extracted_anynumber,      comment: 'turbo_frame_submit ok' }
   end
end

Turbo Frame

Add app/views/home/turbo_frame_form.html.erb file to the application and add this content inside the file.

#CODE

<section>

    <%= turbo_frame_tag 'anyframe' do %>
            
      <div>
          <h2>Frame view</h2>
          <%= form_with scope: :any, url: turbo_frame_submit_path, local: true do |form| %>
              <%= form.label :anynumber, 'Type an integer (odd or even)', 'class' => 'my-0  d-inline'  %>
              <%= form.text_field :anynumber, type: 'number', 'required' => 'true', 'value' => "#{local_assigns[:anynumber] || 0}",  'aria-describedby' => 'anynumber' %>
              <%= form.submit 'Submit this number', 'id' => 'submit-number' %>
          <% end %>
      </div>
      <div>
        <h2>Data of the view</h2>
        <pre style="font-size: .7rem;"><%= JSON.pretty_generate(local_assigns) %></pre> 
      </div>
      
    <% end %>

</section>

Add the content inside file

Make some adjustments in routes.rb

#CODE

Rails.application.routes.draw do
  get 'home/index'
  get 'other/index'

  get '/home/turbo_frame_form' => 'home#turbo_frame_form', as: 'turbo_frame_form'
  post '/home/turbo_frame_submit' => 'home#turbo_frame_submit', as: 'turbo_frame_submit'


  root to: "home#index"
end
  • Next step is to change homepage view in app/views/home/index.html.erb

#CODE

<h1>This is Rails Hotwire home page</h1>
<div><%= link_to "Enter to other page", other_index_path %></div>

<%= turbo_frame_tag 'anyframe' do %>        
  <div>
      <h2>Home view</h2>
      <%= form_with scope: :any, url: turbo_frame_submit_path, local: true do |form| %>
          <%= form.label :anynumber, 'Type an integer (odd or even)', 'class' => 'my-0  d-inline'  %>
          <%= form.text_field :anynumber, type: 'number', 'required' => 'true', 'value' => "#{local_assigns[:anynumber] || 0}",  'aria-describedby' => 'anynumber' %>
          <%= form.submit 'Submit this number', 'id' => 'submit-number' %>
      <% end %>
  <div>
<% end %>

Change HomePage

After making all the changes, restart the rails server and refresh the browser, the default view will appear on the browser.

restart the rails serverNow in the field enter any digit, after entering the digit click on submit button, and as the submit button is clicked we can see the Turbo Frame in action in the below screen, we can observe that the frame part changed, the first title and first link didn’t move.

submit button is clicked

Hotwire Rails: Turbo Streams

Turbo Streams deliver page updates over WebSocket, SSE or in response to form submissions by only using HTML and a series of CRUD-like operations, you are free to say that either

  • Update the piece of HTML while responding to all the other actions like the post, put, patch, and delete except the GET action.
  • Transmit a change to all users, without reloading the browser page.

This transmit can be represented by a simple example.

  • Make changes in app/controllers/other_controller.rb file of rails application

#CODE

class OtherController < ApplicationController

  def post_something
    respond_to do |format|
      format.turbo_stream {  }
    end
  end

   end

file of rails application

Add the below line in routes.rb file of the application

#CODE

post '/other/post_something' => 'other#post_something', as: 'post_something'
Add the below line

Superb! Rails will now attempt to locate the app/views/other/post_something.turbo_stream.erb template at any moment the ‘/other/post_something’ endpoint is reached.

For this, we need to add app/views/other/post_something.turbo_stream.erb template in the rails application.

#CODE

<turbo-stream action="append" target="messages">
  <template>
    <div id="message_1">This changes the existing message!</div>
  </template>
</turbo-stream>
Add template in the rails application

This states that the response will try to append the template of the turbo frame with ID “messages”.

Now change the index.html.erb file in app/views/other paths with the below content.

#CODE

<h1>This is Another page</h1>
<div><%= link_to "Enter to home page", root_path %></div>

<div style="margin-top: 3rem;">
  <%= form_with scope: :any, url: post_something_path do |form| %>
      <%= form.submit 'Post any message %>
  <% end %>
  <turbo-frame id="messages">
    <div>An empty message</div>
  </turbo-frame>
</div>
change the index.html.erb file
  • After making all the changes, restart the rails server and refresh the browser, and go to the other page.

go to the other page

  • Once the above screen appears, click on the Post any message button

Post any message button

This action shows that after submitting the response, the Turbo Streams help the developer to append the message, without reloading the page.

Another use case we can test is that rather than appending the message, the developer replaces the message. For that, we need to change the content of app/views/other/post_something.turbo_stream.erb template file and change the value of the action attribute from append to replace and check the changes in the browser.

#CODE

<turbo-stream action="replace" target="messages">
  <template>
    <div id="message_1">This changes the existing message!</div>
  </template>
</turbo-stream>

change the value of the action attributeWhen we click on Post any message button, the message that appear below that button will get replaced with the message that is mentioned in the app/views/other/post_something.turbo_stream.erb template

click on Post any message button

Stimulus

There are some cases in an application where JS is needed, therefore to cover those scenarios we require Hotwire JS tool. Hotwire has a JS tool because in some scenarios Turbo-* tools are not sufficient. But as we know that Hotwire is used to reduce the usage of JS in an application, Stimulus considers HTML as the single source of truth. Consider the case where we have to give elements on a page some JavaScript attributes, such as data controller, data-action, and data target. For that, a stimulus controller that can access elements and receive events based on those characteristics will be created.

Make a change in app/views/other/index.html.erb template file in rails application

#CODE

<h1>This is Another page</h1>
<div><%= link_to "Enter to home page", root_path %></div>

<div style="margin-top: 2rem;">
  <%= form_with scope: :any, url: post_something_path do |form| %>
      <%= form.submit 'Post something' %>
  <% end %>
  <turbo-frame id="messages">
    <div>An empty message</div>
  </turbo-frame>
</div>

<div style="margin-top: 2rem;">
  <h2>Stimulus</h2>  
  <div data-controller="hello">
    <input data-hello-target="name" type="text">
    <button data-action="click->hello#greet">
      Greet
    </button>
    <span data-hello-target="output">
    </span>
  </div>
</div>

Make A changeMake changes in the hello_controller.js in path app/JavaScript/controllers and add a stimulus controller in the file, which helps to bring the HTML into life.

#CODE

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "name", "output" ]

  greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}

add a stimulus controller in the fileGo to your browser after making the changes in the code and click on Enter to other page link which will navigate to the localhost:3000/other/index page there you can see the changes implemented by the stimulus controller that is designed to augment your HTML with just enough behavior to make it more responsive.

With just a little bit of work, Turbo and Stimulus together offer a complete answer for applications that are quick and compelling.

Using Rails 7 Hotwire helps to load the pages at a faster speed and allows you to render templates on the server, where you have access to your whole domain model. It is a productive development experience in ROR, without compromising any of the speed or responsiveness associated with SPA.

Conclusion

We hope you were satisfied with our Rails Hotwire tutorial. Write to us at service@bacancy.com for any query that you want to resolve, or if you want us to share a tutorial on your query.

For more such solutions on RoR, check out our Ruby on Rails Tutorials. We will always strive to amaze you and cater to your needs.

Original article source at: https://www.bacancytechnology.com/

#rails #ruby 

создать QProgressbar с реальным примером QThread | PyQt5 | Python

В этом руководстве по python — PyQt5 мы узнаем, как создать QProgressbar с использованием реального примера QThread | PyQt5 | Python. Индикатор выполнения используется для индикации пользователем хода выполнения операции и подтверждения того, что приложение все еще работает.

Что такое PyQt5 QProgressbar?

Виджет QProgressBar состоит из горизонтальной или вертикальной полосы, которая постепенно заполняется, показывая ход выполнения задачи. он часто используется в приложениях, которые включают в себя трудоемкие операции, такие как загрузка или загрузка файлов, установка программного обеспечения или любой другой процесс, который может занять некоторое время.

Виджет QProgressBar можно настроить для отображения различных цветов, шрифтов и размеров. Он также предоставляет различные свойства и методы, которые позволяют разработчикам управлять его поведением, например минимальное и максимальное значения, текущее значение и ориентацию полосы.

В целом, виджет QProgressBar является полезным инструментом для обеспечения визуальной обратной связи с пользователями о ходе выполнения задачи и может помочь сделать приложения более удобными и интуитивно понятными.

Это импорт, который нам нужен, например


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time

Это наш класс потока, и этот класс расширяется от QThread, объект QThread управляет одним потоком управления внутри программы. QThreads начинают выполняться в run(). По умолчанию run() запускает цикл событий, вызывая exec(), и запускает цикл событий Qt внутри потока.


class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)

После того, как мы создадим наш класс Window, который расширяется от QDialog, и в этот класс мы добавим требования к нашему окну, такие как заголовок, геометрия и значок с помощью QProgresBar, а также QPushButton . также мы использовали некоторый стиль и дизайн для нашего индикатора выполнения.

class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::chunk {background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()

Это методы, которые мы собираемся использовать для запуска и установки значения QProgressBar.


  def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)

Также каждое приложение PyQt5 должно создавать объект приложения. 

App = QApplication(sys.argv)

Наконец, мы входим в основной цикл приложения. Обработка события начинается с этой точки. 

window = Window()
sys.exit(App.exec_())

Полный исходный код для QProgressbar с QThread


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time
 
 
class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)
class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::
        # chunk {background:
        # qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()
 
    def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)
 
 
 
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

Это будет результат кода для PyQt5 QProgressBar.

PyQt5 QProgressbar с практическим примером QThread

PyQt5 QProgressbar с практическим примером QThread

Также вы можете посмотреть полное видео для PyQt5 QProgressbar с практическим примером QThread.

источник статьи: https://codeloop.org

#python  #pyqt5 

Hoang  Kim

Hoang Kim

1635843812

Chatbot AI hội thoại với Máy biến áp được đào tạo trước bằng Python

Tìm hiểu cách sử dụng thư viện máy biến áp Huggingface để tạo phản hồi hội thoại bằng mô hình DialoGPT được đào tạo trước bằng Python.

Chatbots đã trở nên phổ biến trong những năm gần đây và khi mối quan tâm ngày càng tăng trong việc sử dụng chatbots cho kinh doanh, các nhà nghiên cứu cũng đã làm rất tốt trong việc phát triển các chatbot AI đàm thoại.

Trong hướng dẫn này, chúng tôi sẽ sử dụng thư viện máy biến áp Huggingface để sử dụng mô hình DialoGPT đã được đào tạo trước để tạo phản hồi hội thoại.

DialoGPT là một mô hình tạo phản hồi hội thoại thần kinh có thể điều chỉnh quy mô lớn được đào tạo trên 147 triệu cuộc hội thoại được trích xuất từ ​​Reddit và điều tốt là bạn có thể tinh chỉnh nó với bộ dữ liệu của mình để đạt được hiệu suất tốt hơn so với đào tạo từ đầu.

Để bắt đầu, hãy cài đặt máy biến áp :

$ pip3 install transformers

Mở tệp hoặc sổ ghi chép Python mới và thực hiện như sau:

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# model_name = "microsoft/DialoGPT-large"
model_name = "microsoft/DialoGPT-medium"
# model_name = "microsoft/DialoGPT-small"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

Có ba phiên bản của DialoGPT; nhỏ, vừa và lớn. Tất nhiên, càng lớn càng tốt, nhưng nếu bạn chạy điều này trên máy của mình, tôi nghĩ nhỏ hoặc trung bình phù hợp với bộ nhớ của bạn mà không có vấn đề gì. Bạn cũng có thể sử dụng Google Colab để thử cái lớn.

Tạo phản hồi bằng Tìm kiếm tham lam

Trong phần này, chúng tôi sẽ sử dụng thuật toán tìm kiếm tham lam để tạo phản hồi. Đó là, chúng tôi chọn phản hồi chatbot có xác suất cao nhất được chọn trên mỗi bước thời gian.

Hãy tạo mã để trò chuyện với AI của chúng tôi bằng cách sử dụng tìm kiếm tham lam:

# chatting 5 times with greedy search
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        pad_token_id=tokenizer.eos_token_id,
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Hãy giải thích cốt lõi của mã này:

  • Đầu tiên chúng tôi lấy thông tin đầu vào từ người dùng để trò chuyện.
  • Chúng tôi mã hóa văn bản input_idsbằng cách sử dụng trình mã hóa DialoGPT, chúng tôi cũng nối vào cuối chuỗi mã thông báo và trả về nó dưới dạng bộ căng Pytorch.
  • Nếu đây là lần đầu tiên trò chuyện với bot, thì chúng tôi sẽ trực tiếp cung cấp input_idscho mô hình của mình trong một thế hệ. Nếu không, chúng tôi nối lịch sử trò chuyện bằng cách nối với sự trợ giúp của torch.cat()phương thức.
  • Sau đó, chúng tôi sử dụng model.generate()phương pháp tạo phản hồi chatbot.
  • Cuối cùng, như sản lượng trở lại là một chuỗi tokenized quá, chúng tôi giải mã trình tự sử dụng tokenizer.decode()và thiết lập skip_special_tokensđể Trueđảm bảo chúng tôi không thấy bất kỳ đặc biệt gây phiền nhiễu mã thông báo như <|endoftext|>. Ngoài ra, vì mô hình trả về toàn bộ chuỗi, chúng tôi bỏ qua lịch sử trò chuyện trước đó và chỉ in câu trả lời chatbot mới được tạo.

Dưới đây là một cuộc thảo luận mẫu với bot:

>> You:How can you be rich so quickly?
DialoGPT: I'm not rich, I'm just a rich man.
>> You:Ok, you don't make sense, how old are you ?
DialoGPT: I'm not a rich man, I'm just a rich man.
>> You:How can you be happy ?
DialoGPT: I'm not happy, I'm just a rich man.
>> You:But they say money buys happiness!
DialoGPT: Money buys happiness, but not happiness itself.
>> You:You don't make sense again!
DialoGPT: I'm not happy, I'm just a rich man.

Bạn thấy mô hình lặp lại rất nhiều phản hồi, vì đây là xác suất cao nhất và nó luôn chọn nó.

Theo mặc định, model.generate()sử dụng thuật toán tìm kiếm tham lam khi không có tham số nào khác được đặt, trong các phần tiếp theo, chúng tôi sẽ thêm một số đối số vào phương thức này để xem liệu chúng tôi có thể cải thiện việc tạo không.

Tạo phản hồi với Tìm kiếm chùm

Tìm kiếm theo chùm cho phép chúng tôi giảm nguy cơ bỏ lỡ các chuỗi có xác suất cao bằng cách giữ lại num_beamscác giả thuyết có khả năng xảy ra nhất ở mỗi bước thời gian và sau đó lấy các chuỗi có xác suất cao nhất tổng thể, đoạn mã dưới đây sẽ tạo ra các phản hồi của chatbot với tìm kiếm theo chùm:

# chatting 5 times with beam search
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        num_beams=3,
        early_stopping=True,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Khi đặt num_beamsthành 3trong model.generate()phương thức, chúng tôi sẽ chọn 3 từ ở mỗi bước và phát triển chúng để tìm xác suất tổng thể cao nhất của chuỗi, đặt num_beamsthành 1 cũng giống như tìm kiếm tham lam.

Dưới đây là một cuộc thảo luận mẫu với chatbot bằng cách sử dụng tìm kiếm chùm:

>> You:How can I be rich?
DialoGPT: You can't.
>> You:Why not?
DialoGPT: Because you can't.
>> You:Then how am I supposed to live well?
DialoGPT: You can't.
>> You:So basically, you want me to be a poor guy?
DialoGPT: No, I want you to be a rich guy.
>> You:Ok how to be rich, then?
DialoGPT: I don't know.

Tạo phản hồi bằng lấy mẫu

Trong các phần trước, chúng tôi đã sử dụng tìm kiếm chùm và tham lam để tạo ra chuỗi xác suất cao nhất. Giờ đây, điều đó thật tuyệt vời cho các tác vụ như dịch máy hoặc tóm tắt văn bản trong đó kết quả đầu ra có thể dự đoán được. Tuy nhiên, nó không phải là lựa chọn tốt nhất cho thế hệ kết thúc mở như trong chatbots.

Để có một thế hệ tốt hơn, chúng tôi cần đưa ra một số ngẫu nhiên trong đó chúng tôi lấy mẫu từ một loạt các trình tự ứng viên dựa trên xác suất:

# chatting 5 times with sampling
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_k=0,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Lần này, chúng tôi đặt do_sampleđể Truelấy mẫu và chúng tôi đặt top_kđể 0chỉ ra rằng chúng tôi đang chọn tất cả các xác suất có thể xảy ra, sau đó chúng ta sẽ thảo luận về top_ktham số.

Đây là một cuộc trò chuyện với các thông số này:

>> You:Hello, how can I be rich?
DialoGPT: You can't
>> You:Really? then how others get rich?
DialoGPT: They work as money artists
>> You:How to be a money artist?
DialoGPT: I don't know, I don't have enough knowledge on artists
>> You:Alright, thank you!
DialoGPT: No problem, if you need tips pm me.
>> You:Great, you're my savior!
DialoGPT: Thank you for helping a stranger out like me!

Rõ ràng là có một số cải tiến. Tuy nhiên, việc lấy mẫu trên một danh sách rộng các chuỗi với xác suất thấp có thể dẫn đến việc tạo ngẫu nhiên (như bạn thấy trong câu cuối cùng).

Để cải thiện nó hơn nữa, chúng tôi có thể:

  • Hạ thấp mẫu temperature, điều đó giúp chúng tôi giảm khả năng chọn các từ có xác suất thấp và tăng khả năng chọn các từ có xác suất cao.
  • Sử dụng lấy mẫu Top-k thay vì chọn tất cả các lần xuất hiện có thể xảy ra, điều này sẽ giúp chúng tôi loại bỏ các từ có xác suất thấp để được chọn.
# chatting 5 times with Top K sampling & tweaking temperature
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_k=100,
        temperature=0.75,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Bây giờ, chúng ta thiết lập top_kđể 100lấy mẫu từ đỉnh 100từ được sắp xếp descendingly bởi xác suất. Chúng tôi cũng đặt temperaturethành 0.75(mặc định là 1.0) để có cơ hội chọn các từ có xác suất cao hơn, đặt nhiệt độ 0.0giống như tìm kiếm tham lam, đặt nhiệt độ thành vô cùng giống như hoàn toàn ngẫu nhiên.

Đây là một cuộc thảo luận với các thông số này:

>> You:How can I get rich?
DialoGPT: I'd also like to know this.
>> You:So you don't know it?
DialoGPT: I know it, but it doesn't matter.
>> You:Really? money matters, man!
DialoGPT: Well, money is money and I gotta get my money.
>> You:Yeah how to get them?
DialoGPT: Well, that's a question. I'd like to know more, just for curiosity's sake, to know what other people have said about how I should get rich.
>> You:Some robots like you told me you have to buy gold, silver or stocks.
DialoGPT: I think my wallet is empty.

Như bạn có thể thấy, bây giờ nó đã tốt hơn nhiều, hãy thoải mái tinh chỉnh temperaturetop_kcác thông số và xem liệu nó có thể cải thiện nó hay không.

Lấy mẫu hạt nhân

Lấy mẫu hạt nhân hoặc lấy mẫu Top-p chọn từ các từ nhỏ nhất có thể có xác suất tích lũy vượt quá tham số pchúng tôi đặt.

Dưới đây là một ví dụ sử dụng lấy mẫu Top-p:

# chatting 5 times with nucleus sampling & tweaking temperature
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_p=0.95,
        top_k=0,
        temperature=0.75,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Chúng tôi đặt top_kđể 0tắt lấy mẫu Top-k, nhưng bạn có thể sử dụng cả hai phương pháp có xu hướng hoạt động tốt hơn. Đây là một cuộc trò chuyện:

>> You:How can I be rich fast?
DialoGPT: Inflation and free money
>> You:lol, but that takes time, I need fast money.
DialoGPT: Your post makes no sense. You just need a lot of money to be rich fast
>> You:Ok how to get a lot of money?
DialoGPT: Buy gold and then trade it for money.
>> You:Hmm, I got your point, thanks.
DialoGPT: No problem. You have to have money to buy gold, but its only good for trading it.
>> You:Yeah, I understand, thank you so much.
DialoGPT: Ok, let me know if you need help

Giờ đây, chatbot rõ ràng có ý nghĩa trong nhiều trường hợp.

Bây giờ, hãy thêm một số mã để tạo nhiều hơn một phản hồi chatbot và sau đó chúng tôi chọn phản hồi nào sẽ bao gồm trong đầu vào tiếp theo:

# chatting 5 times with nucleus & top-k sampling & tweaking temperature & multiple
# sentences
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids_list = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_p=0.95,
        top_k=50,
        temperature=0.75,
        num_return_sequences=5,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the outputs
    for i in range(len(chat_history_ids_list)):
      output = tokenizer.decode(chat_history_ids_list[i][bot_input_ids.shape[-1]:], skip_special_tokens=True)
      print(f"DialoGPT {i}: {output}")
    choice_index = int(input("Choose the response you want for the next input: "))
    chat_history_ids = torch.unsqueeze(chat_history_ids_list[choice_index], dim=0)

Tôi đã thiết lập num_return_sequencesđể 5trả lại 5 câu cùng một lúc, chúng ta phải chọn một câu sẽ có trong chuỗi tiếp theo. Dưới đây là làm thế nào nó đi:

>> You:Hello, friend.
DialoGPT 0: Hey there!
DialoGPT 1: I am your friend, and I am also your friend.
DialoGPT 2: Hello. :
DialoGPT 3: Hiya! How are you?
DialoGPT 4: Hello. I like your username.
Choose the response you want for the next input: 3
>> You:Fine, thanks, what about you?
DialoGPT 0: Good. Not much to do.
DialoGPT 1: Not much, you?
DialoGPT 2: Fine, thanks.
DialoGPT 3: I'm okay, thank you for asking.
DialoGPT 4: I'm fine too.
Choose the response you want for the next input: 2
>> You:Can you tell me how can I get rich quickly?
DialoGPT 0: Yes, I can!
DialoGPT 1: Yes, just look up how to get rich on Google.
DialoGPT 2: Just keep doing your thing. You'll get rich.
DialoGPT 3: No, I can't.
DialoGPT 4: no, i have no money
Choose the response you want for the next input: 1
>> You:Yeah, but I thought you have an answer...
DialoGPT 0: I'm getting married in the morning.
DialoGPT 1: How do you get rich?
DialoGPT 2: I think there are many good answers, but I could send you one, if you want.
DialoGPT 3: I will, thanks!
DialoGPT 4: I thought you have an answer.
Choose the response you want for the next input: 2
>> You:Yes, please send me.
DialoGPT 0: You can send me link.
DialoGPT 1: I am very interested
DialoGPT 2: I sent you a PM
DialoGPT 3: I'll send you a PM
DialoGPT 4: I am always interested in new ideas.
Choose the response you want for the next input: 2

Phần kết luận

Và bạn hiểu rồi, tôi hy vọng hướng dẫn này đã giúp bạn cách tạo văn bản trên DialoGPT và các mô hình tương tự. Để biết thêm thông tin về cách tạo văn bản, tôi thực sự khuyên bạn nên đọc hướng dẫn Cách tạo văn bản bằng Transformers .

Tôi sẽ để bạn điều chỉnh các thông số để xem liệu bạn có thể làm cho bot hoạt động tốt hơn hay không.

Ngoài ra, bạn có thể kết hợp điều này với các hướng dẫn chuyển văn bản thành giọng nói và chuyển lời nói thành văn bản để xây dựng một trợ lý ảo như Alexa , Siri , Cortana , v.v.

#python #ai #chatbot