Parerga und Paralipomena

Pyglet: multimedia library for python

Posted in programming by magicrebirth on December 12, 2009

UPDATE 14/12/09: pyProcessing is a project building on pyglet that that creates an environment for graphics applications that closely resembles that of the Processing system. Quite neat uh?
>>>

>>>

pyglet provides an object-oriented programming interface for developing games and other visually-rich applications for Windows, Mac OS X and Linux. Some of the features of pyglet are:

No external dependencies or installation requirements. For most application and game requirements, pyglet needs nothing else besides Python, simplifying distribution and installation.
Take advantage of multiple windows and multi-monitor desktops. pyglet allows you to use as many windows as you need, and is fully aware of multi-monitor setups for use with fullscreen games.
Load images, sound, music and video in almost any format. pyglet can optionally use AVbin to play back audio formats such as MP3, OGG/Vorbis and WMA, and video formats such as DivX, MPEG-2, H.264, WMV and Xvid.

>>>
I’ve been playing with it for an hour or so, and was surprised of how quickly it can let you create a python-based multimedia application. Two possibly useful tips when getting started:
- Go get AVBIN without hesitations – you’ll need it. MP3 and other compressed audio formats require AVbin to be installed (this is the default for the Windows and Mac OS X installers). Uncompressed WAV files can be played without AVbin.
- [tested on OSx leopard only] If you try running the hello-world example from the console, after hitting window = pyglet.window.Window() you’ll see a new window appearing on your screen. That looks like good news obviously, but soon you’ll find out that the Finder doesn’t like that, and apparently the Python launcher results being as ‘not responding’ on the Force Quit Application menu. Well nothing to worry there: it’s because you haven’t issued the pyglet.app.run() command yet (which is where the main event loop gets handled).

>>>
The screenshot above is taken from one of the example apps you can download. Balls keeps bouncing around in a window, playing a sound when they hit the border. Check out the code:


import os
import random
import sys

from pyglet.gl import *
import pyglet
from pyglet.window import key

BALL_IMAGE = 'ball.png'
BALL_SOUND = 'ball.wav'

if len(sys.argv) > 1:
    BALL_SOUND = sys.argv[1]

sound = pyglet.resource.media(BALL_SOUND, streaming=False)

class Ball(pyglet.sprite.Sprite):
    ball_image = pyglet.resource.image(BALL_IMAGE)
    width = ball_image.width
    height = ball_image.height

    def __init__(self):
        x = random.random() * (window.width - self.width)
        y = random.random() * (window.height - self.height)

        super(Ball, self).__init__(self.ball_image, x, y, batch=balls_batch)

        self.dx = (random.random() - 0.5) * 1000
        self.dy = (random.random() - 0.5) * 1000

    def update(self, dt):
        if self.x = window.width:
            self.dx *= -1
            sound.play()
        if self.y = window.height:
            self.dy *= -1
            sound.play()
        self.x += self.dx * dt
        self.y += self.dy * dt

        self.x = min(max(self.x, 0), window.width - self.width)
        self.y = min(max(self.y, 0), window.height - self.height)

window = pyglet.window.Window(640, 480)

@window.event
def on_key_press(symbol, modifiers):
    if symbol == key.SPACE:
        balls.append(Ball())
    elif symbol == key.BACKSPACE:
        if balls:
            del balls[-1]
    elif symbol == key.ESCAPE:
        window.has_exit = True

@window.event
def on_draw():
    window.clear()
    balls_batch.draw()
    label.draw()

def update(dt):
    for ball in balls:
        ball.update(dt)
pyglet.clock.schedule_interval(update, 1/30.)

balls_batch = pyglet.graphics.Batch()
balls = []
label = pyglet.text.Label('Press space to add a ball, backspace to remove',
                          font_size=14,
                          x=window.width // 2, y=10,
                          anchor_x='center')

if __name__ == '__main__':
    pyglet.app.run()

Tagged with: , , ,

Creating Questionnaires with Django

Posted in programming by magicrebirth on December 3, 2009



>>>
Simple and useful application from Aperte: Django Questionnaire. The Django Questionnaire app allows you to easily set up a working questionnaire, complete with email-invitations and CSV export functionality. This app allows you to spread your questions over multiple pages (categories), and currently supports 4 types of answers.

Also, if you don’t feel like setting up the questionnaire yourself you can easily create one on Pervidet.com, which is (I assume) managed by the guys at Aperte.

The application is pretty simple but well designed. Useful for doing large user-studies, for example. The download page lets you have it packaged as a django project, but transforming it into a reusable app is not too difficult (I’ve done that but I’m not posting it here because of several other little hacks I had to do so to accommodate the project I’m using the questionnaire for).
>>>
Tip: if you’re using django 1.1 one little thing that might help you get going quickly is changing these lines of templates/admin/admin_index.html:



{% block stylesheet %}{% load adminmedia %}{% admin_media_prefix %}css/dashboard.css{% endblock %}

..with this:



{% block extrastyle %}{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% load adminmedia %}
{% admin_media_prefix %}css/dashboard.css" />
{% endblock %}

Tagged with: , ,

Echoing freedom’s requests

Posted in opinions by magicrebirth on December 2, 2009


>>>
From the latest post on Beppe Grillo’s blog:

We are living through an unequalable historical phase. The worst of the Italian State. Berlusconi is the worst President of the Council of the last 150 years. Napolitano is the worst President of the Republic (a true “outsider” that makes one miss even Giovanni Leone who was kicked out). The PDminusL is the worst Opposition since the start of the existence of Parliament with Bersani as major-domo to D’Alema, the most intelligent and f**ked politician but also f**king, of the Republic. I want to be optimistic. We are at the bottom of the well and we can stop digging. We have got to the other side. I feel like an Italian towards the end of the second world war under the bombs. He knows it cannot go on for long. That the sky will once more be pale blue and that he will be able to go out into the street, happy as a child, and kiss the first stranger. My optimism is reasoned. The State has gone bust, a billion a day in Public Debt Is insuperable even for “Tremorti”. Millions of people have lost their job. The fund for those who are laid off is close to collapse. Parliament does not exist. It has been expropriated by Constitutional delinquents. The Church is in command. The camorra is in command. The ‘ndrangheta is in command. The citizen counts for nothing. Everything is lost and above all honour. Italian and clown are synonyms throughout the world. “Italian fucking clown”. The Council of Ministers is a continual replay of “Oggi le comiche” {Today the comics}. Any prostitute, any idiot could become Minister in Italy. This regime, like fascism in its time, can no longer be saved by anyone. It has shattered together with the dishonesty and the indifference of many Italians in the last few years. It’s like, after a tragedy, you pick yourself up out of necessity, that’s how it will happen in the near future. The Five Star Movement has no connections with the past, with none of the rotten names of corruption that govern us. The Movement is starting from zero, from the bottom, this is its strength. The Movement will present itself for the regional elections in Emilia Romagna, Campania, Veneto and Piedmont, with Davide Bono heading the list. Many 5 Star Lists are in preparation for the local elections. The Statute is nearly ready as is online registration. On 5 December I am supporting “No B-day”. I will not be on the stage and I will not speak as that has been requested by the organisers. “For us he is a politician and thus will not speak” is the decision of the promoting committee. We are living through social and institutional ruin that no one would have believed possible, starting with me. We are still in the basement, from the TV stations arrive voices of a present that is already past, of people like Schifani, Gasparri, Dell’Utri, Casini. So present and yet already far off. They will never give up (but is it in their interests?). Neither will we.

>>>
By the way, Beppe Grillo is doing a gig in London on Wednesday, 27 January 2010. Sounds interesting?

Tagged with: ,

New song with Impromptu: KALI

Posted in livecoding, music by magicrebirth on November 23, 2009


>>>
Hey ya – new livecoding stuff from me on Vimeo. I’t s a song I’ve been working on recently, called Kali. Unfortunately I still haven’t figured what the best export options for the original movie file are (1.6 Gigs), so that it looks less blurry on Vimeo.. but slowly I’m getting there! The sound is ok though, so hopefully you’ll enjoy!

Tagged with: , ,

Django signals

Posted in programming by magicrebirth on November 11, 2009

This is a really cool feature of django that I’ve never explored, so I though I’d made a post about it so to remind myself of using it more often! It’s discussed extensively in the docs here and here. In a nutshell:

Django includes a “signal dispatcher” which helps allow decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.

Django provides a set of built-in signals that let user code get notified by Django itself of certain actions. These include some useful notifications:

django.db.models.signals.pre_save & django.db.models.signals.post_save

Sent before or after a model’s save() method is called.

django.db.models.signals.pre_delete & django.db.models.signals.post_delete

Sent before or after a model’s delete() method is called.

django.core.signals.request_started & django.core.signals.request_finished

Sent when Django starts or finishes an HTTP request.

How to use them? Really simple: modify the code below as needed and put it at the bottom of your models.py file (it could be located anywhere, but by putting it there we make sure it’s loaded at the right time):


from django.db.models.signals import post_save

def my_handler(sender, instance, created, **kwargs):
	if created:
		# if the instance is effectively saved
		try:
			if instance.my_favourite_method():
				instance.special_field = instance.my_favourite_method()
		except:
			instance.special_field = "undefined"
		instance.save() 

post_save.connect(my_handler, sender=SomeModel)

>>>
Imagine that each time an instance of SomeModel gets saved you want to perform some other operation, such as adding something to one of its fields. Three simple steps: import the post_save signal, define a function my_handler that does the operation, connect your handler to a specific model.

Tagged with: ,