Wednesday, July 26, 2017

The gtts python module.

This python module named gtts will create an mp3 file from spoken text via the Google TTS (Text-to-Speech) API.
The installation of the gtts python module under Windows 10.
C:\Python27\Scripts>pip install gtts
Collecting gtts
  Downloading gTTS-1.2.0.tar.gz
Requirement already satisfied: six in c:\python27\lib\site-packages (from gtts)
Requirement already satisfied: requests in c:\python27\lib\site-packages (from gtts)
Collecting gtts_token (from gtts)
Requirement already satisfied: chardet<3 .1.0="">=3.0.2 in c:\python27\lib\site-packages (from requests->gtts)
Requirement already satisfied: certifi>=2017.4.17 in c:\python27\lib\site-packages (from requests->gtts)
Requirement already satisfied: idna<2 .6="">=2.5 in c:\python27\lib\site-packages (from requests->gtts)
Collecting urllib3<1 .22="">=1.21.1 (from requests->gtts)
  Using cached urllib3-1.21.1-py2.py3-none-any.whl
Installing collected packages: gtts-token, gtts, urllib3
  Running install for gtts-token ... done
  Running install for gtts ... done
  Found existing installation: urllib3 1.22
    Uninstalling urllib3-1.22:
      Successfully uninstalled urllib3-1.22
Successfully installed gtts-1.2.0 gtts-token-1.1.1 urllib3-1.21.1
Let's see a basic example:
from gtts import gTTS
import os
import pygame.mixer
from time import sleep
user_text=input("Type your text: ")
translate=gTTS(text=user_text ,lang='en')'output.wav')

The text will be taken by input into a user_text variable.
You need to type the text into quotes also you will get an error.
The result will be one audio file named output.wav and play it by pygame python module.
This uses the default voices for all languages. I don't find a way to change this voices with python.

Monday, July 24, 2017

Fix Gimp with python script.

Today I will show you how python language can help GIMP users.
From my point of view, Gimp does not properly import frames from GIF files.
This program imports GIF files in this way:

Using the python module, you can get the correct frames from the GIF file.
Here's my script that uses the python PIL module.
import sys
from PIL import Image, ImageSequence
        img =[1])
except IOError:
        print "Cant load", infile

pal = img.getpalette()
prev = img.convert('RGBA')
prev_dispose = True
for i, frame in enumerate(ImageSequence.Iterator(img)):
    dispose = frame.dispose

    if frame.tile:
        x0, y0, x1, y1 = frame.tile[0][1]
        if not frame.palette.dirty:
        frame = frame.crop((x0, y0, x1, y1))
        bbox = (x0, y0, x1, y1)
        bbox = None

    if dispose is None:
        prev.paste(frame, bbox, frame.convert('RGBA'))'result_%03d.png' % i)
        prev_dispose = False
        if prev_dispose:
            prev ='RGBA', img.size, (0, 0, 0, 0))
        out = prev.copy()
        out.paste(frame, bbox, frame.convert('RGBA'))'result_%03d.png' % i)
Name the python script with and then you can use it on the GIF file as follows:
C:\Python27>python.exe 0001.gif
The final result has a smaller number of images than in Gimp, but this was to be expected.

Saturday, July 22, 2017

About py-translate python module.

This python module is used for translating text in the terminal.
You can read and see examples with this API on this web page.

  • Fast! Translate an entire book in less than 5 seconds.
  • Made for Python 3 but still works on Python 2
  • Fast and easy to install, easy to use
  • Supports translation from any language
  • Highly composable interface, the power of Unix pipes and filters.
  • Simple API and documentation

C:\>cd Python27

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install py-translate
Collecting py-translate
  Downloading py_translate-1.0.3-py2.py3-none-any.whl (61kB)
    100% |################################| 61kB 376kB/s
Installing collected packages: py-translate
Successfully installed py-translate-1.0.3

Let's test it with a simple example:
>>> import translate
>>> dir(translate)
['TestLanguages', 'TestTranslator', '__author__', '__build__', '__builtins__', '__copyright__', '__doc__', '__file__', '__license__', '__name__', '__package__', '__path__', '__title__', '__version__', 'accumulator', 'coroutine', 'coroutines', 'languages', 'print_table', 'push_url', 'set_task', 'source', 'spool', 'tests', 'translation_table', 'translator', 'write_stream']
>>> from translate import translator
>>> translator('ro', 'en', 'Consider ca dezvoltarea personala este un pas important')
[[[u'I think personal development is an important step', u'Consider ca dezvoltarea personala este un pas important', None, None, 0]], None, u'ro']

Wednesday, July 19, 2017

PyCharm an integrated development environment.

The development team comes with this integrated development environment (I.D.E.) named: PyCharm.
They tell us about this integrated development environment:
Python IDE with a complete set of tools for productive development with Python programming language. In addition, the IDE provides high-class capabilities for professional Web development with Django framework and Google App Engine. It has powerful coding assistance, navigation, a lot of refactoring features, tight integration with various Version Control Systems, Unit testing, powerful all-singing all-dancing Debugger, and entire customization. PyCharm is developer driven IDE. It was developed with the aim of providing you almost everything you need for your comfortable and productive development!
I usually use it and from my point of view, it is very quick to learn and use.
Also, some features like Servers come is supported in the Professional edition only.
The menu is easy to remember and the project settings come automatically.
You can start from the main menu: File - New Project...
A little more complicated element is putting new scripts into the project File - New.
The python file can be added and the type of python version can by editing the configuration menu: Run - Edit Configurations...
The editor comes with unindent and convert fro tabs and spaces.
This I.D.E. comes with common version control operations integrations, like:
  • CVS Reference
  • Git Reference
  • Mercurial Reference
  • Perforce Reference
  • Subversion Reference
Also, some official tutorials can also be found on the official website.
You can read more about this software here.

The JetBrainsTV is the official youtube channel of this I.D.E.

Monday, July 10, 2017

Python tutor - web tool for python programming.

The website comes with this intro about this web tool.
Python Tutor, created by Philip Guo, helps people overcome a fundamental barrier to learning programming: understanding what happens as the computer runs each line of source code.
Using this tool, you can write Python, Java, JavaScript, TypeScript, Ruby, C, and C++ code in your web browser and visualize what the computer is doing step-by-step as it runs your code.
Over 3.5 million people in over 180 countries have used Python Tutor to visualize over 30 million pieces of code, often as a supplement to textbooks, lectures, and online tutorials.

I tested and worked very well.
You can use python programming language 2.7 and 3.6 versions.
No need to import python modules, you will get an error.
Just programming on the fly to test and see the result.
The website comes with some example to see how to deal with this tool.
Let's see some examples:

example with factorial :

# dumb recursive factorial
def fact(n):
    if (n <= 1):
        return 1
        return n * fact(n - 1)


example with for - else:

# find primes using a for-else construct
for n in range(2, 10):
    x_range = range(2, n)
    for x in x_range:
        if n % x == 0:
        # loop fell through without finding a factor

example with inputs:

prefix = "Hello "

n1 = raw_input("Enter your name")

n2 = raw_input("Enter another name")

res = prefix + n1 + " and " + n2

Run your script just press: Visualize Execution or Live Programming Mode buttons and the will run step by step with:
First, Back, Forward and Last.
One good feature of this tool - with a single line of JavaScript code, you can embed a Python Tutor visualization within any webpage.
Another good feature is COLLABORATE to learn together - this allow us to give and get direction with real-time python programming.
Can be a good tool for python chat users.
Let's show you a screenshot to see how this tool working with python scripting.

Sunday, July 9, 2017

The speech python module.

About this python module can be read here.
It's a little undocumented and I have not found tutorials about this python module but I tested with a simple example.
I'm sure he can do more than I tried with my example.
First, the install of this python module:
C:\Python27\Scripts>pip install speech
Collecting speech
  Downloading speech-0.5.2.tar.gz
Installing collected packages: speech
  Running install for speech ... done
Successfully installed speech-0.5.2
Let's see more about this python module:
>>> dir(speech)
['Listener', '_ListenerBase', '_ListenerCallback', '__builtins__', '__doc__', '__file__', '__name__', '__package__'
, '_constants', '_ensure_event_thread', '_eventthread', '_handlerqueue', '_listeners', '_recognizer', 
'_startlistening', '_voice', 'gencache', 'input', 'islistening', 'listenfor', 'listenforanything', 'pythoncom',
 'say', 'stoplistening', 'thread', 'time', 'win32com']>>> help(speech)
Help on module speech:

    speech - speech recognition and voice synthesis module.


    Please let me know if you like or use this module -- it would make my day! Copyright 2008 Michael Gundlach  (gundlach at gmail)
    License: Apache 2.0 (

    For this module to work, you'll need pywin32 (
    for Python 2.5 or for Python 2.4) and
    the Microsoft Speech kit (

        Listener: represents a command to execute when phrases are heard.

        say(phrase): Say the given phrase out loud.
        input(prompt, phraselist): Block until input heard, then return text.
        stoplistening(): Like calling stoplistening() on all Listeners.
        islistening(): True if any Listener is listening.
        listenforanything(callback): Run a callback when any text is heard.
        listenfor(phraselist, callback): Run a callback when certain text is heard.
Let's make a simple example with one script that tells us something:
>>> speech.say('Hello Catalin George')
The result of this line of code will be heard into your audio device like Hello Catalin George.

Saturday, July 8, 2017

Python Qt4 - part 006.

Today I will deal with QFileDialog widget.
You can read the more about this widget here.
This allows us to open a dialog to load a resource - a file.
The example comes with the base PyQt4 application window with a my_example dialog from fileDialogSample python class.
Into this python class, I have some variable for the file: file_name, data and my_file_open.
The my_text_edit for text area and my_button to open the QFileDialog.
Also, the vbox variable to put all on QVBoxLayout from the application.
Let's see the example:
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore

class fileDialogSample(QtGui.QWidget):
    def __init__(self):

        #make text area and button
        self.my_text_edit = QtGui.QTextEdit()
        self.my_button = QtGui.QPushButton('Select File', self)

        #open the showDialog

        #put all into application area
        vbox = QtGui.QVBoxLayout()

        #set title and geometry of application
        self.setWindowTitle('File Dialog example')
        self.setGeometry(50, 50, 300, 300)

    #make a function with seeting for my QFileDialog
    def showDialog(self):
        file_name = QtGui.QFileDialog.getOpenFileName(self, 'Open file', 'C://')
        my_file_open = open(file_name)
        data =

#run the application 
app = QtGui.QApplication(sys.argv)
my_dialog = fileDialogSample()
Now, just press the Select File button, take a text file and open it.

Friday, July 7, 2017

Python Qt4 - part 005.

Another example with PyQt4 that allow seeing images over the internet.
Here's another simple example with PyQt4 that allows you to view images on the internet.
You can use any image on the internet to display with this python script.
This example is done in two steps:
  • take a single image from the internet - httplib python module;
  • displaying - PyQt4 python module
from PyQt4 import QtGui
import sys
import httplib

def getTempPNG():
   conn = httplib.HTTPConnection("")
   conn.request("GET", "/sateliti/img/id814/id814_2017070718.png")
   return conn.getresponse().read()

def main():
   app = QtGui.QApplication(sys.argv)
   png = getTempPNG()
   pixmap = QtGui.QPixmap()
   label = QtGui.QLabel()
   label.setWindowTitle('METEOSAT-10 Thermal Infrared Channel 10.8 micrometers Glowing temperature')

if __name__ == '__main__':
The result can be seen in this screenshot:

Python Qt4 - part 004.

Another tutorial about PyQt4 with QLCDNumber widget displays a number with LCD-like digits.
This tutorial will show you how to deal with this widget.
First, you need to know more about QLCDNumber, so take a look here.
The first example is very simple and will show just one digit, see:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Digit(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle("One digit")
        lcd = QLCDNumber(self)

app = QApplication(sys.argv)
ls = Digit()
Now, the next step is to send data to this digit.
One good example is with one slider.
The position of the slider will be send to the QLCDNumber.
How can do that? Will need a vbox to put the QLCDNumber and the slider and then using signal and slot.
Let's see the example:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Digit(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        #make widgets
        self.setWindowTitle("One digit with slider")
        lcd = QLCDNumber(self)
        slider = QSlider(Qt.Horizontal, self)
        #set layout variable vbox
        vbox = QVBoxLayout()
        #add widgests
        #set the vbox to layout
        #create signal to slot
        self.connect(slider, SIGNAL("valueChanged(int)"),lcd, SLOT("display(int)"))
        self.resize(200, 170)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ls = Digit()
In the source code in the example, you can see the comments that mark the steps of creating and executing the python script.
Let's try another example with a digital clock:
import sys
from PyQt4 import QtCore, QtGui

class digital_clock(QtGui.QLCDNumber):
    def __init__(self, parent=None):
        super(digital_clock, self).__init__(parent)
        #the defaul is 5 , change to 8 for seconds
        self.setWindowTitle("Digital Clock")
        self.resize(200, 70)
        timer = QtCore.QTimer(self)

    def showTime(self):
        time = QtCore.QTime.currentTime()
        text = time.toString('hh:mm')
        #if you setDigitsCount to 8
        #uncomment the next line of code
        #text = time.toString('hh:mm:ss')
        if (time.second() % 2) == 0:
            text = text[:2] + ' ' + text[3:]

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    clock = digital_clock()
If you want to see seconds, then you need to set the digit count of the LCD to 8 ( it's 5 by default) of setDigitCount.
Also you need to uncomment this line of code: text = time.toString('hh:mm:ss') and comment the old one.
You can solve multiple issues with this widget, like: stopwatch, timer, clock down timer ...

Thursday, July 6, 2017

Python Qt4 - part 003.

Today I've taken a simple example with PyQt4 compared to the other tutorials we have done so far.
The main reason was to understand and use PyQt4 to display an important message.
To make this example I have set the following steps for my python program.
  • importing python modules
  • creating the application in PyQt4 as a tray icon class
  • establishing an exit from the application
  • setting up a message to display
  • display the message over a period of time
  • closing the application
  • running the python application
Let's see my source code of my python application:
#! /usr/bin/env python
import sys
from PyQt4 import QtGui, QtCore

class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, parent)
        menu = QtGui.QMenu(parent)
        exitAction = menu.addAction("Exit")
        QtCore.QObject.connect(exitAction,QtCore.SIGNAL('triggered()'), self.exit)

    def click_trap(self, value):
        if value == self.Trigger: #left click!

    def welcome(self):
        self.showMessage("Hello user!", "This is a message from PyQT4")

    def show(self):
        QtCore.QTimer.singleShot(600, self.welcome)

    def exit(self):

def main():
    app = QtGui.QApplication([])
    tray = SystemTrayIcon()

if __name__ == '__main__':
I used PyQt4 python module to make the application and sys python module for exit from application.
About running application: the main function will run the application.
The python class SystemTrayIcon will work only if we used QApplication to make like any application.
This is the reason I used the variable app.
The tray variable is used to run it like tray icon application.
Into the SystemTrayIcon class, I put some functions to help me with my issue.
Under __init__ I used all settings for my tray icon application: the icon, the exit menu, signal for the exit.
The next functions come with:
  • click_trap - take the click of the user ;
  • welcome - make a message to display;
  • show - display the welcome message;
  • exit - exit from the application
The result of my python script is this message:

About the showMessage then this helps you:

QSystemTrayIcon.showMessage (self, QString title, QString msg, MessageIcon icon = QSystemTrayIcon.Information, int msecs = 10000)

Shows a balloon message for the entry with the given title, message and icon for the time specified in millisecondsTimeoutHint. title and message must be plain text strings.
The message can be clicked by the user; the messageClicked() signal will be emitted when this occurs.
Note that the display of messages is dependent on the system configuration and user preferences and that messages may not appear at all. Hence, it should not be relied upon as the sole means for providing critical information.
On Windows, the millisecondsTimeoutHint is usually ignored by the system when the application has focus.
On Mac OS X, the Growl notification system must be installed for this function to display messages.
This function was introduced in Qt 4.3.

Tuesday, July 4, 2017

The pdb python interactive debugging - part 001.

This is a short intro tutorial on python debugger to summarize this topic related to Python.
According to the development team, this python module called pdb has the following objectives:
The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame. It also supports post-mortem debugging and can be called under program control.

Let's start it with some example:
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\", line 1270, in pm
AttributeError: 'module' object has no attribute 'last_traceback'
>>> import os
> c:\python27\lib\
-> post_mortem(sys.last_traceback)
(Pdb) ?

Documented commands (type help ):
EOF    bt         cont      enable  jump  pp       run      unt
a      c          continue  exit    l     q        s        until
alias  cl         d         h       list  quit     step     up
args   clear      debug     help    n     r        tbreak   w
b      commands   disable   ignore  next  restart  u        whatis
break  condition  down      j       p     return   unalias  where

Miscellaneous help topics:
exec  pdb

Undocumented commands:
retval  rv
As you can see, this module will work correctly with just another python module. In the example presented above is the os python module.
With the argument? we can see the commands that we can execute.
Let's see the list command ( l ):
(Pdb) l
1265        p = Pdb()
1266        p.reset()
1267        p.interaction(None, t)
1269    def pm():
1270 ->     post_mortem(sys.last_traceback)
1273    # Main program for testing
1275    TESTCMD = 'import x; x.main()'
You can see the pm function loaded by pdb python module.
Post-mortem debugging is a method that requires an environment that provides dynamic execution of code.
One of the greatest benefits of post-mortem debugging is that you can use it directly after something has gone wrong.
You can move between frames within the current call stack using up and down.
This moves towards older frames on the stack.
The debugger prints the current location with where, see example:
(Pdb) where
> c:\python27\lib\
-> post_mortem(sys.last_traceback)
To execute the current line and then stop at the next execution point use step.
The until command can be used to step past the end of a loop.
Use break command used for setting breakpoints, example: (Pdb) break 4.
Turning off a breakpoint with disabling tells the debugger not to stop when that line is reached, example: (Pdb) disable 1.
Also, we can have the other breakpoints like conditional breakpoints and temporary breakpoint.
Use clear to delete a breakpoint entirely.
Changing execution flow with the jump command lets you alter the flow of your program.
The jump can be ahead and back and moves the point of execution past the location without evaluating any of the statements in between.
We can also have illegal jumps in and out of certain flow control statements prevented by the debugger.
When the debugger reaches the end of your program, it automatically starts it over.
With run command, the program can be restarted.
We can avoid typing complex commands repeatedly by using alias and unalias to define the shortcuts.
The pdb python module lets you save configuration using text files read and interpreted on startup.