Monday, 2 May 2016

Raspberry Pi 2 – Speech Recognition on device

This is a lengthy post and very dry, but it provides detailed instructions for how to build and install SphinxBase and PocketSphinx and how to generate a pronunciation dictionary and a language model, all so that speech recognition can be run directly on the Raspberry Pi, without network access. Don’t expect it to be as fast as Google’s recognizer, tho …

Creating the RASPBIAN boot MicroSD

Starting with the current RASPBIAN (Debian Wheezy) image, the creation of a bootable MicroSD Card is a well understood and well documented process.
Uncompressing the zip (again, there is no better tool than The Unarchiver, if you are on a Mac) reveals the 2015-02-16-raspbian-wheezy.img

With the MicroSD (inside an SD-Card adapter – no less than 8GB) inserted into the Mac, I run the df -h command in Terminal, to find out how to address the card. Today, it showed up as/dev/disk4s1 56Mi 14Mi 42Mi 26% 512 0 100% /Volumes/boot, which means, I run something like this, to put the boot image onto the MicroSD:
sudo diskutil unmount /dev/disk4s1
sudo dd bs=1m if=/Users/wolf/Downloads/2015-02-16-raspbian-wheezy.img of=/dev/rdisk4
… after a few minutes, once the 3.28 GB have been written onto the card, I execute:
sync
sudo diskutil eject /dev/rdisk4

Customizing the OS

Once booted, using the sudo raspi-config allow the customization of the OS, which means that time-zone, keyboard, and other settings are adjusted, to closely match its environment.
I usually start (PI is already connected to the internet via Ethernet Cable) with
  • updating the raspi-config
  • expanding the filesystem
  • internationalization: un-check en-GB, check en-US.UTF-8 UTF-8
  • internationalization: timezone ..
  • internationalization: keyboard: change to English US
  • setting the hostname to translator, there are too many Raspberry Pis on my home network, to leave it at the default
  • make sure SSH is enabled
  • force audio out on the 3.5mm headphone jack

Microphone

usbmic
Given the sparse analog-to-digital support provided by the Raspberry Pi, the probably best and easiest way to connect a decent Mic to the device, is using a USB microphone. I happen to have an older Logitech USB Mic, which works perfectly fine with the Pi.
After a reboot and now with the microphone connected, let’s get started ..
ssh pi@translator with the default password ‘raspberry’ gets me in from everywhere on my local network
cat /proc/asound/cards
returns

0 [ALSA ]: bcm2835 - bcm2835 ALSA
bcm2835 ALSA
1 [AK5370 ]: USB-Audio - AK5370
AKM AK5370 at usb-bcm2708_usb-1.2, full speed

showing that the microphone is visible and its usb extension.
Next, I edit alsa-base.conf to load snd-usb-audio like so:
sudo nano /etc/modprobe.d/alsa-base.conf
Edit
options snd-usb-audio index=-2
to
options snd-usb-audio index=0
and after a sudo reboot, cat /proc/asound/cards
looks like this

0 [AK5370 ]: USB-Audio - AK5370
AKM AK5370 at usb-bcm2708_usb-1.2, full speed
1 [ALSA ]: bcm2835 - bcm2835 ALSA
bcm2835 ALSA

Recording – Playback – Test

Before worrying about Speech Recognition and Speech Synthesis, let’s make sure that the basic recording and audio playback works.
Again, I have an USB Microphone connected to the Pi, as well as a speaker, using the 3.5mm audio plug.

Installing build tools and required libraries


sudo apt-get update
sudo apt-get upgrade
sudo apt-get install bison
sudo apt-get install libasound2-dev
sudo apt-get install swig
sudo apt-get install python-dev
sudo apt-get install mplayer
sudo reboot

/etc/asound.conf

sudo nano etc/asound.conf and enter something like this:
pcm.usb
{
    type hw
    card AK5370
}

pcm.internal
{
    type hw
    card ALSA
}

pcm.!default
{
    type asym
    playback.pcm
    {
        type plug
        slave.pcm "internal"
    }
    capture.pcm
    {
        type plug
        slave.pcm "usb"
    }
}

ctl.!default
{
    type asym
    playback.pcm
    {
        type plug
        slave.pcm "internal"
    }
    capture.pcm
    {
        type plug
        slave.pcm "usb"
    }
}

Recording

The current recording settings can be looked at with:
amixer -c 0 sget 'Mic',0
and for me that looks something like this:
  Simple mixer control 'Mic',0
  Capabilities: cvolume cvolume-joined cswitch cswitch-joined penum
  Capture channels: Mono
  Limits: Capture 0 - 78
  Mono: Capture 68 [87%] [10.00dB] [on]
alsamixer -c 0 can be used to increase the capture levels. After an increase, it looks like this:
  ...
  Mono: Capture 68 [87%] [10.00dB] [on]

Playback

The current playback settings can be looked at with:
amixer -c 1
alsamixer -c 0 can be used to increase the volume. After an increase,
amixer -c 1
it looks like this:
  Simple mixer control 'PCM',0
  Capabilities: pvolume pvolume-joined pswitch pswitch-joined penum
  Playback channels: Mono
  Limits: Playback -10239 - 400
  Mono: Playback -685 [90%] [-6.85dB] [on]

Test Recording and Playback

With the mic switched on ..
arecord -D plughw:0,0 -f cd ./test.wav .. use Control-C to stop the recording.
aplay ./test.wav
With recording and playback working, let’s get into the really cool stuff, on-device speech recognition.

Speech Recognition Toolkit

CMU Sphinx a.k.a. PocketSphinx
Currently pocket sphinx 5 pre-alpha (2015-02-15) is the most recent version. However, there are a few prerequisites that need to be installed first ..

Installing build tools and required libraries


sudo apt-get update
sudo apt-get upgrade
sudo apt-get install bison
sudo apt-get install libasound2-dev
sudo apt-get install swig
sudo apt-get install python-dev
sudo apt-get install mplayer

Building Sphinxbase


cd ~/
wget http://sourceforge.net/projects/cmusphinx/files/sphinxbase/5prealpha/sphinxbase-5prealpha.tar.gz
tar -zxvf ./sphinxbase-5prealpha.tar.gz
cd ./sphinxbase-5prealpha
./configure --enable-fixed
make clean all
make check
sudo make install

Building PocketSphinx


cd ~/
wget http://sourceforge.net/projects/cmusphinx/files/pocketsphinx/5prealpha/pocketsphinx-5prealpha.tar.gz
tar -zxvf pocketsphinx-5prealpha.tar.gz
cd ./pocketsphinx-5prealpha
./configure
make clean all
make check
sudo make install

Creating a Language Model

Create a text file, containing a list of words/sentences we want to be recognized

For instance ..
Okay Pi
Open Garage
Start Translator
Shutdown
What is the weather in Ramona
What is the time
Upload the text file here: http://www.speech.cs.cmu.edu/tools/lmtool-new.html
and then download the generated Pronunciation Dictionary and Language Model
For the the text file mentioned above, this is what the tool generates:

Pronunciation Dictionary

GARAGE G ER AA ZH
IN IH N
IS IH Z
OKAY OW K EY
OPEN OW P AH N
PI P AY
RAMONA R AH M OW N AH
SHUTDOWN SH AH T D AW N
START S T AA R T
THE DH AH
THE(2) DH IY
TIME T AY M
TRANSLATOR T R AE N S L EY T ER
TRANSLATOR(2) T R AE N Z L EY T ER
WEATHER W EH DH ER
WHAT W AH T
WHAT(2) HH W AH T

Language Model

Language model created by QuickLM on Thu Mar 26 00:23:34 EDT 2015
Copyright (c) 1996-2010 Carnegie Mellon University and Alexander I. Rudnicky

The model is in standard ARPA format, designed by Doug Paul while he was at MITRE.

The code that was used to produce this language model is available in Open Source.
Please visit http://www.speech.cs.cmu.edu/tools/ for more information

The (fixed) discount mass is 0.5. The backoffs are computed using the ratio method.
This model based on a corpus of 6 sentences and 16 words

\data\
ngram 1=16
ngram 2=20
ngram 3=15

\1-grams:
-0.9853 </s> -0.3010
-0.9853 <s> -0.2536
-1.7634 GARAGE -0.2536
-1.7634 IN -0.2935
-1.4624 IS -0.2858
-1.7634 OKAY -0.2935
-1.7634 OPEN -0.2935
-1.7634 PI -0.2536
-1.7634 RAMONA -0.2536
-1.7634 SHUTDOWN -0.2536
-1.7634 START -0.2935
-1.4624 THE -0.2858
-1.7634 TIME -0.2536
-1.7634 TRANSLATOR -0.2536
-1.7634 WEATHER -0.2935
-1.4624 WHAT -0.2858

\2-grams:
-1.0792 <s> OKAY 0.0000
-1.0792 <s> OPEN 0.0000
-1.0792 <s> SHUTDOWN 0.0000
-1.0792 <s> START 0.0000
-0.7782 <s> WHAT 0.0000
-0.3010 GARAGE </s> -0.3010
-0.3010 IN RAMONA 0.0000
-0.3010 IS THE 0.0000
-0.3010 OKAY PI 0.0000
-0.3010 OPEN GARAGE 0.0000
-0.3010 PI </s> -0.3010
-0.3010 RAMONA </s> -0.3010
-0.3010 SHUTDOWN </s> -0.3010
-0.3010 START TRANSLATOR 0.0000
-0.6021 THE TIME 0.0000
-0.6021 THE WEATHER 0.0000
-0.3010 TIME </s> -0.3010
-0.3010 TRANSLATOR </s> -0.3010
-0.3010 WEATHER IN 0.0000
-0.3010 WHAT IS 0.0000

\3-grams:
-0.3010 <s> OKAY PI
-0.3010 <s> OPEN GARAGE
-0.3010 <s> SHUTDOWN </s>
-0.3010 <s> START TRANSLATOR
-0.3010 <s> WHAT IS
-0.3010 IN RAMONA </s>
-0.6021 IS THE TIME
-0.6021 IS THE WEATHER
-0.3010 OKAY PI </s>
-0.3010 OPEN GARAGE </s>
-0.3010 START TRANSLATOR </s>
-0.3010 THE TIME </s>
-0.3010 THE WEATHER IN
-0.3010 WEATHER IN RAMONA
-0.3010 WHAT IS THE

\end\
Looking carefully, the Sphinx knowledge base generator provides links to the just generated files, which make sit super convenient to pull them down to the Pi. For me it generated a base set with the name 3199:

wget http://www.speech.cs.cmu.edu/tools/product/1427343814_14328/3199.dic
wget http://www.speech.cs.cmu.edu/tools/product/1427343814_14328/3199.lm

Running Speech-recognition locally on the Raspberry Pi

Finally everything is in place, SphinxBase and PocketSphinx have been building installed, a pronunciation dictionary and a language model has been created and locally stored.
During the build process, acoustic model files for the english language, were deployed here: /usr/local/share/pocketsphinx/model/en-us/en-us
.. time to try out the the recognizer:

cd ~/
export LD_LIBRARY_PATH=/usr/local/lib
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig

pocketsphinx_continuous -hmm /usr/local/share/pocketsphinx/model/en-us/en-us -lm 3199.lm -dict 3199.dic -samprate 16000/8000/48000 -inmic yes

Output

READY….
Listening…
INFO: ps_lattice.c(1380): Bestpath score: -7682
INFO: ps_lattice.c(1384): Normalizer P(O) = alpha(:285:334) = -403763
INFO: ps_lattice.c(1441): Joint P(O,S) = -426231 P(S|O) = -22468
INFO: ngram_search.c(874): bestpath 0.01 CPU 0.003 xRT
INFO: ngram_search.c(877): bestpath 0.01 wall 0.002 xRT
OPEN GARAGE
READY….
Listening…
Raspberry Pi 2
Raspberry Pi 2 – speech recognition and playback setup

Live Demo

This video shows the recognizer running in keyword spotting mode, using the dictionary and model mentioned above:
pocketsphinx_continuous -lm 3199.lm -dict 3199.dic -keyphrase "OKAY PI" -kws_threshold 1e-20 -inmic yes
The purpose is to provide some indication of the recognition speed that can be expected, running PocketSphinx on the Raspberry Pi 2.

Saturday, 30 April 2016

Mail me when someone runs command using sudo – Linux Security

There is situation that i wanted to monitor all the sudo users activity, When ever they type an command using sudo i should get an email. This is very important when your working as a Linux Security Administrator / Security analyst.  As a Linux Administrator you should have an evidence to prove somebody is screed up something in your environment.
Restrict your Administrator’s to use sudo for all the important commands by writing an restriction in /etc/sudoers file then change the permission of the /etc/sudoers to 600 using root. No user will able to see the

:: Prerequisites ::

  1. Restrict users by adding restrictions to /etc/sudoers
  2. Create an distribution list and add that to configuration – because every time we are not going to modify config file
Most of the time what we will do is we will provide an full rights to the administrator based an there designation and level of exportation, but we don’t know what he / she is doing an the production environment. In order to monitor the typed commands with sudo, We have to add below lines to the configuration file.
Add the entry to the /etc/sudoers as mentioned below, It will send you an alert whenever user type the command using sudo. Providing the the path of the log file it will save an every executed command as shown in below:
~]# vi /etc/sudoers
###### Get every alert when user fired an command with sudo ####
Defaults        syslog=auth, insults, syslog_goodpri=alert
Defaults        logfile=/var/log/sudo.log
Defaults        timestamp_timeout=0, log_year, tty_tickets
Defaults        mailto="theja473@gmail.com", mail_always, mail_badpass, mail_no_user
Some times we need an exceptional cases that we don’t want to get alert when particular user types and commands with sudo before the command.
we have to modify the configuration as shown in below.
~]#vi /etc/sudoers
User_Alias NoMail = goodboy, goodgirl
User_Alias MailUsers = ALL, !NoMail
Defaults           mailto="aravikumar48@gmail.com"
Defaults:MailUsers mail_always
Defaults:NoMail    !mail_badpass
Where User_Alias NoMail it will not send a mail for that specified users.

Wednesday, 27 April 2016

INSTALLING OPERATING SYSTEM IMAGES IN TO SD CARDS

INSTALLING OPERATING SYSTEM IMAGES USING WINDOWS

  • Insert the SD card into your SD card reader and check which drive letter was assigned. You can easily see the drive letter (for example G:) by looking in the left column of Windows Explorer. You can use the SD Card slot (if you have one) or a cheap SD adaptor in a USB port.
  • Download the Win32DiskImager utility from the Sourceforge Project page (it is also a zip file); you can run this from a USB drive.
  • Extract the executable from the zip file and run the Win32DiskImager utility; you may need to run the utility as administrator. Right-click on the file, and select Run as administrator.
  • Select the image file you extracted above.
  • Select the drive letter of the SD card in the device box. Be careful to select the correct drive; if you get the wrong one you can destroy your data on the computer's hard disk! If you are using an SD card slot in your computer and can't see the drive in the Win32DiskImager window, try using a cheap SD adaptor in a USB port.
  • Click Write and wait for the write to complete.
  • Exit the imager and eject the SD card.

INSTALLING OPERATING SYSTEM IMAGES ON LINUX

Please note that the use of the dd tool can overwrite any partition of your machine. If you specify the wrong device in the instructions below you could delete your primary Linux partition. Please be careful.
  • Run df -h to see what devices are currently mounted.
  • If your computer has a slot for SD cards, insert the card. If not, insert the card into an SD card reader, then connect the reader to your computer.
  • Run df -h again. The new device that has appeared is your SD card. The left column gives the device name of your SD card; it will be listed as something like /dev/mmcblk0p1 or /dev/
    sdd1. The last part (p1 or 1respectively) is the partition number but you want to write to the whole SD card, not just one partition. Therefore you need to remove that part from the name (getting, for example, /dev/mmcblk0 or /dev/sdd) as the device for the whole SD card. Note that the SD card can show up more than once in the output of df; it will do this if you have previously written a Raspberry Pi image to this SD card, because the Raspberry Pi SD images have more than one partition.
  • Now that you've noted what the device name is, you need to unmount it so that files can't be read or written to the SD card while you are copying over the SD image.
  • Run umount /dev/sdd1, replacing sdd1 with whatever your SD card's device name is (including the partition number).
  • If your SD card shows up more than once in the output of df due to having multiple partitions on the SD card, you should unmount all of these partitions.
  • In the terminal, write the image to the card with the command below, making sure you replace the input file if= argument with the path to your .imgfile, and the /dev/sdd in the output file of= argument with the right device name. This is very important, as you will lose all data on the hard drive if you provide the wrong device name. Make sure the device name is the name of the whole SD card as described above, not just a partition of it; for example sdd, not sdds1 or sddp1; or mmcblk0, not mmcblk0p1.
    dd bs=4M if=2015-11-21-raspbian-jessie.
    img of=/dev/sdd
    
  • Please note that block size set to 4M will work most of the time; if not, please try 1M, although this will take considerably longer.
  • Also note that if you are not logged in as root you will need to prefix this withsudo.
  • The dd command does not give any information of its progress and so may appear to have frozen; it could take more than five minutes to finish writing to the card. If your card reader has an LED it may blink during the write process. To see the progress of the copy operation you can run pkill -USR1 -n -x dd in another terminal, prefixed with sudo if you are not logged in as root. The progress will be displayed in the original window and not the window with the pkill command; it may not display immediately, due to buffering.
  • Instead of dd you can use dcfldd; it will give a progress report about how much has been written.
  • You can check what's written to the SD card by dd-ing from the card back to another image on your hard disk, truncating the new image to the same size as the original, and then running diff (or md5sum) on those two images.
  • The SD card might be bigger than the original image, and dd will make a copy of the whole card. We must therefore truncate the new image to the size of the original image. Make sure you replace the input file if= argument with the right device name. diff should report that the files are identical.
    dd bs=4M if=/dev/sdd of=from-sd-card.img
    truncate --reference 2015-11-21-raspbian-jessie.img from-sd-card.img
    diff -s from-sd-card.img 2015-11-21-raspbian-jessie.img
  • Run sync; this will ensure the write cache is flushed and that it is safe to unmount your SD card.
  • Remove the SD card from the card reader.

INSTALLING OPERATING SYSTEM IMAGES ON MAC OS

On Mac OS you have the choice of the command line dd tool or using the graphical tool ImageWriter to write the image to your SD card.

(MOSTLY) GRAPHICAL INTERFACE

  • Connect the SD card reader with the SD card inside. Note that it must be formatted in FAT32.
  • From the Apple menu, choose About This Mac, then click on More info...; if you are using Mac OS X 10.8.x Mountain Lion or newer then click on System Report.
  • Click on USB (or Card Reader if using a built-in SD card reader) then search for your SD card in the upper right section of the window. Click on it, then search for the BSD name in the lower right section; it will look something like 'diskn' where n is a number (for example, disk4). Make sure you take a note of this number.
  • Unmount the partition so that you will be allowed to overwrite the disk; to do this, open Disk Utility and unmount it (do not eject it, or you will have to reconnect it). Note that On Mac OS X 10.8.x Mountain Lion, "Verify Disk" (before unmounting) will display the BSD name as "/dev/disk1s1" or similar, allowing you to skip the previous two steps.
  • From the terminal run:
    sudo dd bs=1m if=path_of_your_image.img of=/dev/rdiskn
    Remember to replace n with the number that you noted before!
    • If this command fails, try using disk instead of rdisk:
      sudo dd bs=1m if=path_of_your_image.img of=/dev/diskn

COMMAND LINE

  • If you are comfortable with the command line, you can write the image to a SD card without any additional software. Open a terminal, then run:
    diskutil list
  • Identify the disk (not partition) of your SD card e.g. disk4 (not disk4s1).
  • Unmount your SD card by using the disk identifier to prepare copying data to it:
    diskutil unmountDisk /dev/disk<disk# from diskutil>
    e.g. diskutil unmountDisk /dev/disk4
  • Copy the data to your SD card:
    sudo dd bs=1m if=image.img of=/dev/rdisk<disk# from diskutil>
    e.g. sudo dd bs=1m if=2015-11-21-raspbian-jessie.
    img of=/dev/rdisk4
    • This may result in an dd: invalid number '1m' error if you have GNU coreutils installed. In that case you need to use 1M:
      sudo dd bs=1M if=image.img of=/dev/rdisk<disk# from diskutil>
  • This will take a few minutes, depending on the image file size. You can check the progress by sending a SIGINFO signal pressing 
    Ctrl
    +
    T
    .
    • If this command still fails, try using disk instead of rdisk:
      e.g. `sudo dd bs=1m if=2015-11-21-raspbian-jessie.
      img of=/dev/disk4`
      
      or
      e.g. `sudo dd bs=1M if=2015-11-21-raspbian-jessie.
      img of=/dev/disk4`
      

ALTERNATIVE METHOD

Note: Some users have reported issues with using Mac OS X to create SD cards.
These commands and actions need to be performed from an account that has administrator privileges.
  • From the terminal run df -h.
  • Connect the SD card reader with the SD card inside.
  • Run df -h again and look for the new device that wasn't listed last time. Record the device name of the filesystem's partition, for example /dev/disk3s1.
  • Unmount the partition so that you will be allowed to overwrite the disk:
    sudo diskutil unmount /dev/disk3s1
    (or open Disk Utility and unmount the partition of the SD card (do not eject it, or you will have to reconnect it)
  • Using the device name of the partition, work out the raw device name for the entire disk by omitting the final "s1" and replacing "disk" with "rdisk". This is very important as you will lose all data on the hard drive if you provide the wrong device name. Make sure the device name is the name of the whole SD card as described above, not just a partition of it (for example, rdisk3, not rdisk3s1). Similarly, you might have another SD drive name/number like rdisk2 or rdisk4; you can check again by using the df -h command both before and after you insert your SD card reader into your Mac. For example, /dev/disk3s1 becomes /dev/rdisk3.
  • In the terminal, write the image to the card with this command, using the raw disk device name from above. Read the above step carefully to be sure you use the correct rdisk number here:
    sudo dd bs=1m if=2015-11-21-raspbian-jessie.
    img of=/dev/rdisk3
    
    If the above command reports an error (dd: bs: illegal numeric value), please change bs=1m to bs=1M.
    If the above command reports an error dd: /dev/rdisk3: Permission denied then that is because the partition table of the SD card is being protected against being overwritten by MacOS. Erase the SD card's partition table using this command:
    sudo diskutil partitionDisk /dev/disk3 1 MBR "Free Space" "%noformat%" 100%
    That command will also set the permissions on the device to allow writing. Now try the dd command again.
    Note that dd will not feedback any information until there is an error or it is finished; information will be shown and the disk will re-mount when complete. However if you wish to view the progress you can use 'ctrl-T'; this generates SIGINFO, the status argument of your tty, and will display information on the process.
  • After the dd command finishes, eject the card:
    sudo diskutil eject /dev/rdisk3
    (or: open Disk Utility and eject the SD card)