Saturday, September 11, 2010

Retrieve MP3 Metadata

I know, there are many modules can be used: eyeD3, mutagen, etc. But I think it is a good idea to understand first what is the concept of MP3 metadata.

Based on this Wikipedia article, the ID3v1 metadata container (which I used for this script) occupies 128 bytes beginning with the string TAG. The tag is placed at the end of the file to maintain compatibility with older media players.

ID3v1 consists of the following informations, including the bytes position:


for deeper information about ID3, including the extended tags, visit Wikipedia link above.

Just in case you haven't got this information yet, in Windows, you must read MP3 file as binary file, therefore you should use 'rb' for open function.

Here is my script:
import sys

filename = sys.argv[1]

fsock = open(filename, "rb", 0)
fsock.seek(-128,2) # get the last 128 bytes
tagdata = fsock.read(128)

fsock.close()

if tagdata[:3] == "TAG":
print "title\t: ", tagdata[3:33]
print "artist\t: ", tagdata[33:63]
print "album\t: ", tagdata[63:93]
print "year\t: ", tagdata[93:97]
print "comment\t: ", tagdata[97:126]
print "genre\t: ", tagdata[127:128]

Sunday, August 29, 2010

HTML Parsing using HTMLParser

Simple script to get the video download link from here, which are hosted at archive.org
This script is adapted from here.

HTMLParser usage
from Python documentation:

Usage:
    p = HTMLParser()
    p.feed(data)
    ...
    p.close()

Start tags are handled by calling handle_starttag() or
handle_startendtag(); end tags by handle_endtag().  The
data between tags is passed from the parser to the derived class
by calling handle_data() with the data as argument (the data
may be split up in arbitrary chunks).  Entity references are
passed by calling handle_entityref() with the entity
reference as the argument.  Numeric character references are
passed to handle_charref() with the string containing the
reference as the argument.

import sys
import urllib
import HTMLParser
import re

class GetLinks(HTMLParser.HTMLParser):
    def handle_starttag(self,tag,attrs):
        if tag == 'a':
            for name,value in attrs:
                if name == 'href':
                    if re.search('ArabicLanguageCourseVideos',value):
                        print(value)
                    
gl = GetLinks()
url = 'http://www.lqtoronto.com/videodl.html'

urlconn = urllib.urlopen(url)

# read and put the downloaded html code into url content
urlcontents = urlconn.read()

# input the downloaded material into HTMLParser's member function 
# for parsing
gl.feed(urlcontents)

Friday, August 27, 2010

Socket Exception Handlers

Based on book 'Foundations of Python Network Programming' chapter 2.

Based on Python documentation, there are four socket exceptions (error, herror, gaierror, timeout). Here, I only use the socket.error only. It is used for general I/O and communication problems.

For an illustration, try the following from command line:
> python.exe socket.py google.com 80 index.html

import socket,sys

# standard input
host = sys.argv[1]
port = sys.argv[2]
filename = sys.argv[3]

# error handler 
def errorHandler(message,e):
    print('{0} {1}' .format(message,e))
    sys.exit(1)
    
# create socket 
try:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error, e:
    errorHandler('Socket creation error: ',e)

# input port manipulation
try:
    port = int(port)
except ValueError,e:
    errorHandler('Error port number: ',e)

# connection initiation
try:
    s.connect((host,port))
except socket.error, e:
    errorHandler('error socket initiation: ',e)
    
# sending HTTP request
try:
    s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename)
except socket.error, e:
    errorHandler('Error sending HTTP request: ',e)
    
# receiving data from server
while 1:
    try:
        buf = s.recv(2048)
    except socket.error, e:
        errorHandler('Error receiving data: ',e)
    if not len(buf):
        break
    sys.stdout.write(buf)

Monday, August 23, 2010

Install zope.interface for Twisted

Twisted uses Zope Interface to define and document APIs.
  1. Download it from here. It's in egg format. Choose the appropriate Python version with ours.
  2. To install .egg, we need 'Easy Install' that is part of setuptools. So, we have to install setuptools first. Download it from here. Choose the appropriate Python version with ours. Because our aim is to be able to install .egg, choose setuptools in .exe format.
  3. Run the installer. 
  4. It will install a new executable file called 'easy_install.exe' under Python's 'Scripts' folder.
  5. To install the zope.interface in .egg format, I did the following in Command Line:
c:\Python26\Scripts\easy_install.exe c:\zope.interface-3.6.1-py2.6-win32.egg
Now we can use the zope.interface for our twisted.

---
Further readings:

Thursday, August 19, 2010

SyntaxHighlighter

SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript. In short, it beautifies your code posts, something like this for Python codes:
class SimpleDescriptor(object):

    def __get__(self, instance, owner):
        # Check if the value has been set
        if (not hasattr(self, "_value")):
            raise AttributeError
        print "Getting value: %s" % self._value
        return self._value

    def __set__(self, instance, value):
        print "Setting to %s" % value
        self._value = value

    def __delete__(self, instance):
        del(self._value)
This article provides very-easy steps to utilize SyntaxHighlighter.
-

Checking Input Type

The idea:
check whether input is numeric or not. First, try to convert the input into float object. If failed, then it is not numeric for sure :p
while True:
    try:
        radius = float(input('masukkan jari-jari lingkaran: '))
        break
    except ValueError:
        print('masukkan angka!')
-

Tuesday, April 20, 2010

Test


\int_{-\infty}^{\infty}e^{-x^{2}}\;dx=\sqrt{\pi}


Just trying my jsTeXrender

Plotting Discontinuous Graph

From one of the problem in here :









I've got some clue from here. So, here is my solution :
t = -5:0.01:5;     % total range of the graph

q1 = t<-4;            % range 1
q2 = t>=-4 & t<3;     % range 2 
q3 = t>=3;            % range 3

y = zeros(size(t));    % initialization

y(q1) = 0;             % curve 1
y(q2) = t(q2) + 2;     % curve 2
y(q3) = t(q3) - 2;     % curve 3

plot(t,y); axis([-5 5 -4 7])

And here is the graph :
















Okay. The x(t) above is quite simple. How if it is --in example-- an polynomial equation? The concept remains the same. But, don't forget to use the dot operator, because we will power each of array member.

Monday, April 19, 2010

Plotting Continuous Signal #1 - Unit Step Function

x(t) = 4u(t) + 2sin(3t)




Matlab's inline function is convenient for creating unit step function.

Code :
t = -pi:0.01:pi;
u = inline('t >= 0');  
y = 4*u(t) + 2*sin(3*t);

plot(t,y,'r');grid on;
axis([-4 4 -3 7]);
xlabel('t'); ylabel('x(t)');
title('x(t) = 4u(t) + 2sin(3t)')

(From exercise 1C, chapter 1, book Fundamentals of Signals and Systems, 2nd ed. (Edward W. Kanen, Bonnie S. Heck))

Sunday, April 18, 2010

Demonstrating Convolution in Matlab

This simulation demonstrates convolution between two signals.
Graph 1 -> signal A
Graph 2 -> signal B
Graph 3 -> convolution of A and B




The code :


clear all;

x = [0 0 -1 2 3 -2 0 1 0 0];
dtx = -2:7;     % non-zero range of x
y = [1 -1 2 4];
dty = 8:11;     % non-zero range of y
z = conv(x,y);
dtz = 6:18;     % non-zero range of z

% plotting
dt = -2:20;
subplot(311);stem(dt,[x zeros(size(8:20))]);
title('Signal A');

subplot(312);stem(dt,[zeros(size(-2:7)) ...
y zeros(size(12:20))]);
title('Signal B');

subplot(313);stem(dt,[zeros(size(-2:5)) ...
z zeros(size(19:20))]);
title('A * B');

I use the example from here, at page 3.

Preface - Mukadimah

Hi.
This blog is all about my notes of everything that I currently learn. I'm expecting that I'll fill it out with Matlab and network programming stuff.

Hopefully I'm able to resist against my biggest enemy : laziness
Just wish me luck :D

---

Hai.
Blog ini berisi catatan saya selama belajar Matlab dan network programming. Semoga saja saya mampu bertahan lama dalam mengisi blog ini. Saya punya banyak blog. Dan dari kesemuanya itu, tak ada satupun yang terpelihara dengan baik :D Semoga blog ini tidak bernasib sama :-)

Yang pasti, blog ini akan sangat berguna bagi saya. Dan saya harap, blog ini juga memberikan efek yang sama juga bagi Anda.

makasih.