Archive

Archive for the ‘python’ Category

extract an animated gif from a video

Problem
You have a video and you want to create an animated gif from a part of it.

Solution
You can use MoviePy for that. Here you can find a blog post from the author of MoviePy, where the process is explained through several examples. Here I copy three simple examples:

Example 1:

from moviepy.editor import *

clip = (VideoFileClip("frozen_trailer.mp4")  # input video
        .subclip((1,22.65),(1,23.2))         # part to extract, where 1’22.65 means 1 minute 22.65 seconds
        .resize(0.3))                        # resize to 30% of the original
clip.write_gif("use_your_head.gif")          # output animated gif

Example 2 (cropping):

kris_sven = (VideoFileClip("frozen_trailer.mp4")
             .subclip((1,13.4),(1,13.9))
             .resize(0.5)
             .crop(x1=145,x2=400))  # cropping: remove left-right borders

Example 3 (play forward and backward):

def time_symetrize(clip):
    return concatenate([clip, clip.fx( vfx.time_mirror )])

clip = (VideoFileClip("frozen_trailer.mp4", audio=False)
        .subclip(36.5,36.9)
        .resize(0.5)
        .crop(x1=189, x2=433)
        .fx( time_symetrize ))  # the effect is added here

For more advanced usage, see the original blog post.

Categories: python Tags: , , ,

copy large files between computers at home over the network

January 2, 2015 Leave a comment

Problem
I have a desktop machine at home with a Windows 2007 virtual machine. I mainly have it because of Powerpoint. Recently I prefer to work on my laptop in the living room. Today I needed Powerpoint, so I decided to copy the whole Windows virtual machine and put it on my laptop. The only problem is that it was 67 GB and I didn’t have that much space on my external HDDs :(

Solution
Don’t panic. On my desktop machine I entered the folder that I wanted to copy and started a web server:

python -m SimpleHTTPServer

With “ifconfig” I checked the local IP address of the machine, it was 192.168.0.53.

On my laptop I opened a browser and navigated to “http://192.168.0.53:8000“. All the files I needed were there. Since I’m lazy and I didn’t want to click on each link one by one, I issued the following command (tip from here):

wget -r --no-parent http://192.168.0.53:8000

The download speed was about 10 MB/sec, so it took almost 2 hours.

Categories: network, python Tags: , ,

media info

December 28, 2014 Leave a comment

Problem
You have a media file (audio, video, image) and you want to get some detailed information about it: duration, bit rate, resolution, etc. How to extract these pieces of information?

Solution
Use the MediaInfo project. You can install it via your package manager and you will get a command called “mediainfo”.

Example:

$ mediainfo movie.avi

Output:

General
Complete name                            : movie.avi
Format                                   : AVI
Format/Info                              : Audio Video Interleave
Format profile                           : OpenDML
Format settings                          : rec
File size                                : 1.27 GiB
Duration                                 : 2h 29mn
Overall bit rate                         : 1 218 Kbps
Writing application                      : AVI-Mux GUI 1.17.8.3, Feb 16 201019:42:50

Video
ID                                       : 0
Format                                   : MPEG-4 Visual
Format profile                           : Advanced Simple@L5
Format settings, BVOP                    : 2
Format settings, QPel                    : No
Format settings, GMC                     : No warppoints
Format settings, Matrix                  : Default (H.263)
Muxing mode                              : Packed bitstream
Codec ID                                 : XVID
Codec ID/Hint                            : XviD
Duration                                 : 2h 29mn
Bit rate                                 : 1 086 Kbps
Width                                    : 720 pixels
Height                                   : 304 pixels
Display aspect ratio                     : 2.35:1
Frame rate                               : 23.976 fps
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Compression mode                         : Lossy
Bits/(Pixel*Frame)                       : 0.207
Stream size                              : 1.13 GiB (89%)
Writing library                          : XviD 64

Audio
ID                                       : 1
Format                                   : MPEG Audio
Format version                           : Version 1
Format profile                           : Layer 3
Mode                                     : Joint stereo
Mode extension                           : MS Stereo
Codec ID                                 : 55
Codec ID/Hint                            : MP3
Duration                                 : 2h 29mn
Bit rate mode                            : Constant
Bit rate                                 : 128 Kbps
Channel(s)                               : 2 channels
Sampling rate                            : 48.0 KHz
Compression mode                         : Lossy
Stream size                              : 136 MiB (11%)
Alignment                                : Aligned on interleaves
Interleave, duration                     : 747 ms (17.92 video frames)
Interleave, preload duration             : 216 ms
Title                                    : mp3
Writing library                          : LAME3.99r
Encoding settings                        : -m j -V 4 -q 2 -lowpass 17 -b 128

Python
There is a simple Python wrapper for it called pymediainfo. Its github page is here.

Categories: bash, python Tags: , , ,

autocompile LaTeX project when a file changes

November 19, 2014 Leave a comment

Problem
When I work with LaTeX, I always create a script called “compile.sh” that compiles the project and produces a PDF. For viewing the PDF file I use okular since it refreshes automatically if the PDF changes. However, if I change the LaTeX source, I need to call the “compile.sh” script manually. Could it be automated? That is, when I save the LaTeX source, the project should compile automatically, so I should only switch between my text editor and the PDF viewer.

Solution
I found a complete solution for the problem: autocompile.py. It’s a demo script that is part of the pyinotify project.

Usage:

./autocompile.py . .tex,.bib ./compile.sh

I put autocompile.py in the root folder of the LaTeX project, next to the compile.sh script. The command above means the following: “monitor the current directory recursively. When a .tex or .bib file changes, call the compile.sh script.”

Related

Categories: python Tags: , , , ,

a terminal-based YouTube player

November 2, 2014 Leave a comment

mps-youtube is a terminal-based YouTube player and downloader. If you use YouTube a lot for listening music, then you must give it a try.

Screenshot:

Categories: python Tags: , , ,

Dr. Strangelove or: How I Learned to Stop Worrying and Love Bash

July 30, 2014 1 comment

In this post, Steve shows how to include Python code snippets in Bash scripts! Do you hate Bash? Me too :) However, with this trick bash becomes much less painful.

For more info, please refer to Steve’s post. Here I write a short summary for future references.

Example 1:

#!/bin/bash

function current_datetime {
python - <<END
import datetime
print datetime.datetime.now()
END
}

# Call it
current_datetime

# Call it and capture the output
DT=$(current_datetime)
echo Current date and time: $DT

Example 2 (passing parameters to the wrapping function):


#!/bin/bash

function line {
PYTHON_ARG="$1" python - <<END
import os
line_len = int(os.environ['PYTHON_ARG'])
print '-' * line_len
END
}

# Do it one way
line 80

echo 'Handy'

# Do it another way
echo $(line 80)

You can find another example with JSON at Steve’s blog.

Categories: bash, python Tags:

Firefox: restore your lost tabs

April 30, 2014 Leave a comment

Problem
Over the last 1.5-2 years, I collected 700+ tabs in my Firefox :) Maybe this summer I will have some time to sort them out. However, today when I switched my computer on, all my tabs were gone and I got a clean Firefox instance with one tab only. Hmm… I had a similar problem once and then I installed an add-on called “Session Manager”. In this add-on I made the setting to offer the list of previous sessions upon restart but it didn’t do anything! Damn, how to get back my tab collection?

Solution
In the .mozilla directory there is a file called sessionstore.js that stores — among others — the opened tabs. However, this file was very small, my previous tabs were clearly not in it. Thank God there was a backup copy of this file next to it called sessionstore.bak. It was a big file and the timestamp of the file indicated that it was created 2 days ago when everything was OK with my tabs.

So, how to extract the old tabs from sessionstore.bak?

This is a JSON file, but it’s not pretty printed. I suggest copying this file to somewhere else where you can experiment with it. First, let’s make it readable:

$ python -m json.tool sessionstore.bak > session.json

Now you can open session.json with a text editor. You will find lines with a “url” key, but the number of these rows is huge. I had 731 tabs (that I lost) but this file contained 6500+ URLs. As I noticed, it also contains the URLs of closed tabs. How to extract the URLs of the opened tabs only?

Again, Python came to my rescue. After analyzing the structure of this JSON file, I could extract the tab URLs the following way:

$ python  # version 2.7
>>> import json
>>> f = open('session.json')  # input file
>>> g = open('tabs.txt', 'w')  # output file
>>> d = json.load(f)
>>> tabs = d["windows"][0]["tabs"]
>>> cnt = 0
>>> for t in tabs:
...     print >>g, t["entries"][0]["url"]
...     cnt += 1
>>> cnt
731    # Yeah! All of them are here!
>>> g.close()
>>> f.close()

The URLs of the lost tabs are now in the tabs.txt file.

I didn’t make a script of it but feel free to do it. From now on I will make regular backups of my opened tabs with the URL Lister add-on.

Categories: firefox, python Tags: , , , ,
Follow

Get every new post delivered to your Inbox.

Join 78 other followers