codingdirectional: Resize the video with python program

Hallo mein Freund, Jetzt ist es Zeit für ein weiteres tutorial, lasst uns beginnen! If you are following this website then you should know that recently I am exploring which is supposed to be a website which allows us to create game with python program and I am on the way to get into the game creation stage after solving some basic python questions on this site, but starting from today our plan has changed a little bit, I am going to start a brand new python project while continue to discover that above site at the same time, so you can expect more daily articles from this site soon on both the previous topic as well as the new topic, I might create a few more python related topics at the same time in the future as well. The project which we are going to create together is the video editing/streaming application project written in python with the help of the ffmpeg multimedia framework. I am going to create the project in windows os but if you are the mac or Linux user then you can just slightly modify the program code to suit your need, no problem at all.

FFmpeg is a complete, cross-platform solution tool uses to record, convert and stream audio and video. We are not going to use this tool directly on the command prompt instead we will use tkinter to create the video editing application user interface which wraps around this FFmpeg tool which can then be used to perform various video editing/streaming processes. Before we start you need to download and install FFmpeg on your computer first, you can search google for the keyword ‘FFmpeg’ and then download and install the tool on your computer through below search box.

We can now create a simple tkinter’s interface with a button which when we click on it will open up a file dialog box where we can then select a video to edit, in this example we will change the size of the video from it’s previous size of 1280 x 720 pixels to 1920 x 1080 pixels, the aspect ratio of the original video will be kept and the program will create a new video based on that new video size.

The UI is very simple

The entire program is as followed.

 from tkinter import * from tkinter import filedialog import os import subprocess  win = Tk() # Create instance win.title("Manipulate Video") # Add a title win.resizable(0, 0) # Disable resizing the GUI win.configure(background='black') # change background color  #  Create a label aLabel = Label(win, text="Click on below button to select a video", anchor="center", padx=13, pady=10, relief=RAISED,) aLabel.grid(column=0, row=0, sticky=W+E) aLabel.configure(foreground="white") aLabel.configure(background="black") aLabel.configure(wraplength=160)  # Open a video file def openVideo():         fullfilename = filedialog.askopenfilename(initialdir="/", title="Select a file", filetypes=[("Video file", "*.mp4; *.avi ")]) # select a video file from the hard drive         if(fullfilename != ''):                                  dir_path = os.path.dirname(os.path.realpath(fullfilename))                 os.chdir(dir_path)                 f = '1920.mp4' # the new output file format       ['ffmpeg', '-i', fullfilename, '-vf', 'scale=1920:-1', f]) # resize the video with ffmpeg                  action_vid = Button(win, text="Open Video", command=openVideo, padx=2) action_vid.grid(column=0, row=1, sticky=E+W) action_vid.configure(background='black') action_vid.configure(foreground='white')  win.mainloop() 

Because the FFmpeg tool runs on command prompt we will need to use the python’s subprocess module to pass in the FFmpeg’s command arguments as a list to the call method of the subprocess module.

Basically what the below line does is simply to resize the original video then saves it as a new video.['ffmpeg', '-i', fullfilename, '-vf', 'scale=1920:-1', f]) # resize the video with ffmpeg 

The time spends to resize the video will depend on the file size of the original video.

In this example the time spends to resize the video is a little bit longer than before

Friend, have you downloaded the application which we have created together previously? If not here is the link.


At the moment the application does not offer many selections of the video size for us to change, in the next article, we will include the selection box on this same application so we can then select any video’s size which we prefer. (If you have not yet subscribed to this site then click on the red bell button to subscribe).

Planet Python

Roberto Alsina: Coding in anger: not-gitbook

I have, intermitently, for the past few months, been writing a book. You can see it here and I am fairly happy with how it’s going.

I am not so happy with the tooling.

When I started writing it, I didn’t want to write a tool, I just wanted to write a book. So, I looked for “things to make a book out of markdown” and found a few, including mdBook and gitbook and tried them both, then decided to go with gitbook because it seemed more developed.

But, you know how this works. Things started drifting.

One initial obstacle was that I wanted the code in the book to come from the actual working code, not be a copy. I also wanted to “execute” the chapters and make the output of the chapter’s code part of the chapter itelf.

I found a nice tool for this called pyLiterate which… I ended up extending to allow for things such as “include this piece of code from that file but do not execute it” and whatever, and integrating it into gitbook involved … a lot of Makefiles.

And then wen the output appeared in gitBook … I really didn’t like how syntax highlighting worked. I wanted prettier and specifically to be able to highlight some lines, and to have line numbers matching the file contents and not starting from 1 … and I ended up writing a Gitbook Extension

And I added support for graphviz in pyLiterate because I wanted SVG diagrams as part of the code and not as separate things.

And I wrote and I wrote.

And then life happened and I stopped writing. And whenever I wanted to start writing again in a new setup something broke.

  • Maybe the gitbook version installed or its dependencies had a security issue and needed updating.
  • Maybe the updated gitbook broke my plugin
  • Maybe things just were “off” and I had to track it down*

And a couple of days ago, I just got angry. And what the hell this is just a lame static file generator and I know those suckers.

So, I decided to see how much work would it be to reimplement, somewhat dumbly, gitbook.

Well, really, it’s about a day’s work (for a low quality version)

  • Supports all I want
  • Supports plugins
  • Supports arbitrary markdown preprocessing
  • Supports arbitrary markdown renderer hacking
  • Uses mistune for markdown, which kicks ass
  • Uses jinja2 for templates and they are 10x simpler than in gitbook AND THE OUTPUT LOOK THE SAME. I mean, there is one template

I logged the work, which was at a very relaxed pace over a couple of days here and published not-gitbook in gitlab

I could migrate my book to the new toolchain in a day more work, mostly involving implementing things gitbook doesn’t do and I am hacking via Makefiles.

It’s surely not ready for any real usage but feel free to poke around and contact me if you want to use it.

Planet Python

Ofosos: Integrating Sphinx doctests with Travis

Integrating Sphinx doctests with Travis

If you want to run Sphinx doc tests in Travis you will need to jump through some hoops. Fortunately it isn’t that complicated, I’ve created some sample code on Github/doctest-travis for you to follow along.

Doc test are a way to ensure that your documentation is up to date. In principle doc tests should be largely analogous to unit tests. That’s the reason we want to be able to run them from our CI job. On the other hand, doc tests are part of the documentation, so they will actually be visible to the reader. In practice, if using Sphinx, you will likely add sample code to your documentation in a doc test as part of you regular documentation. Actually executing doc tests as part of your CI ensures that what the user perceives as sample code will actually work the way they expect it to.

The Python module

Doc tests are currently only supported for Python code, that means there is no easy way to thread in command line invocation, compile C++ or run Ruby code. We’ll start with a simple Python module in doctest_travis/

def stupid_sum(a, b):     return a+b+1  def stupid_mul(a, b):     return a*b*2 

Additionally there’s some support code in the to load these functions into the package by default.

The basic unit tests

To test our stupid functions, we’ll create some basic unit tests. These reside in tests/ and get executed by pytest. They use the Python unittest framework.

from doctest_travis import *  class TestStupidFunctions(unittest.TestCase):  	def test_stupid_sum(self): 		self.assertEqual(stupid_sum(1,2), 4)  	def test_stupid_mul(self):         self.assertEqual(stupid_mul(2,2), 8) 

Now running pytest tests/ from the top level will execute our unit tests.

Autodoc and doctest

We’ll use autodoc to import function signatures from Python. Running doc tests is a lot like running regular unit tests. We’ll can use a testsetup and testcleanup directive in the document and initialize and tear down the testing environment in there. Both of these directives will not generate any output.

See the doctest docs for a full description of all options available.

Here’s an excerpt from mashing up these two functionalities.

doctest_travis --------------  .. automodule:: doctest_travis    :members:   .. autofunction:: doctest_travis.stupid_sum  .. doctest::  	>>> stupid_sum(2, 3) 	6 

You provide a python expression prefixed by >>> on thefirst line and end with an expression that is parseable by Python on the second line. The Sphinx doctest module will compare both and return success, if they match.

You can find the output of doctest-travis on doctest-travis rtd.

The user will generally perceive this as sample code in the HTML form. Of course we want to go beyond just providing sample code, we want to have a doc test.

Go to the project’s root directory and run the following command to check if our doc tests work.

$   python -msphinx -b doctest docs foo ... Document: index --------------- 1 items passed all tests:    2 tests in default 2 tests in 1 items. 2 passed and 0 failed. Test passed.  Doctest summary ===============     2 tests     0 failures in tests     0 failures in setup code     0 failures in cleanup code 

There we go. Our example code now runs as a doc test.

Tying everything into Travis

We’ll use tox to automate the test runs. We’ll have unit tests, a sample doc build and our doc test runner all running in the test step. All will be driven by tox. Here is the sample tox.ini to make this happen.

[travis] python =   2.7: py27   3.6: py36  [testenv] deps =      pytest     sphinx commands =      pytest --basetemp={envtmpdir} tests/     python -msphinx -b html -d {toxworkdir}/_build/doctrees docs {toxworkdir}/_build/html     python -msphinx -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest 

We’ll map Travis environments to Python interpreters manually, using the [travis] section and the we’ll pass our dependencies into [testenv]. We need both pytest and sphinx in the virtualenv that will be generated by tox. Finally we’ll specify a set of commands. pytest runs our unit tests, python -msphinx -b html... runs the HTML builder and python -msphinx -b doctest... runs the doc test runner. All the output will later show up in Travis. We can now run tox locally by calling it on the console.

$   tox 

The missing piece of information is our Travis configuration file. Travis runs different Python builds in different containers and that’s what we want to do. So Python 2.7 will run in a specific container and Python 3.6 will run in a different container. This is a little bit redundant with tox, which also can spawn different virtualenv environments to run different versions of Python. What we need is a Travis file that triggers different build per Python version, the tox file given above will simply pick up the current Python version and build based on that version. Here’s the .travis.yml.

sudo: false language: python python:   - "2.7"   - "3.6" install: pip install tox-travis script: tox -vv 

The [travis] section in the tox.ini is filled out by this tox-travis plug-in that we trigger.


You can find the build status of this project on the Travis site here.

Now we’ve wrapped up everything. Travis calls tox, which calls the test runners and test builds. I hope you can adapt this scheme to your own projects.

Image credits: I, Avenafatua [GFDL (, CC-BY-SA-3.0 ( or CC BY-SA 2.5 (]

Planet Python

Weekly Python StackOverflow Report: (clix) stackoverflow python report

These are the ten most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2019-01-05 22:23:15 GMT

  1. Why does `if None.__eq__(“a”)` evaluate to True? – [79/3]
  2. For loops with pandas – When should I care? – [18/1]
  3. Python performance comparison for creating sets – set() vs. {} literal – [13/1]
  4. pandas replace NaN to None exhibits counterintuitive behaviour – [12/1]
  5. How to remove duplicate lines – [11/6]
  6. What does underscore in a number mean? – [10/3]
  7. Pip install – do downloaded whl files persist & take disk space? – [9/2]
  8. Print specific keys and values from a deep nested dictionary in python 3.X – [8/3]
  9. AWS Lambda Python 3.7 runtime exception logging – [8/2]
  10. Find all subarrays of fixed length with a given ranking – [7/3]

Planet Python