Archive for the ‘Développement’ Category

SMIL-animated SVG for accessible textbooks

Friday, November 27th, 2009

Dyspraxia is a serious learning disability for 250.000 children in elementary schools in France. Not that French children are particularly disadvantaged. It just happens that it seems to be a very wide spread kind of disability and the proportion of dyspraxic children should roughly be the same from country to country. In order to overcome this obstacle, the nonprofit organization I currently work for is leading the way toward adapting the ergonomy of existing paper textbooks and helping textbook editors creating the accessible (and digital) textbook of the future. Maybe you’ve heard of any similar initiatives ?

Their first attemps were made using a French e-learning authoring tool called Didapages. Up to version 1.1 it was free for non-commerciale uses. Version 2 is much more commercially oriented. And closed-source. And only runs on Windows. And despite its ease of use for educators and non-IT specialists, it has several drawbacks and limitations, partly due to the technology it uses, Flash, and partly because its developer does not think he can build a sustainable business model using free software licensing. Too bad. I am looking for an alternative solution, as some part of its user community does.

Free software packages such as Xerte, eXe, Scenari, Docebo and others look attractive. But none is the ideal solution : either they are also based on Flash, or their community is almost non-existant and their development may have stopped some time ago. Educators are not developers. And the crowd of educators might be missing a critical mass of developers in order for a very striving free software community to have developped around any elearning authoring tool. The bells and whistles of proprietary products have much more appeal to the average teacher.

From a technology perspective, I had a look at open standards for acessible, animated and interactive contents. W3C, please show me the way. The relevant standards seem to be :

  • HTML 5 for content, with its Javascript-animated “canvas” element for sprite-based animations (for bitmaps graphics) ;
  • SMIL for animated documents and for limited interactivity, possibly also combined/extended with Ecmascript for more interactivity ;
  • CSS for styling, possibly some day with Webkit-like CSS animation but this option does not excite me much ; CSS animation may require Javascript or SMIL
  • SVG for graphics : there is such a thing as SVG Animation, and Ecmascript can be embedded in a SVG file in order to provide more interactivity and to overcome some current interactivity limitation of SMIL ; SVG is for vector graphics but could also embed (and animate) bitmap graphics (used as sprites).

The advantage of SMIL and SMIL-animated SVG over Flash seems to be that SMIL is a declarative technology. This “document” model allows less dependency on scripting and more flexibility through earlier or further transformations (with templating, XSLT or content management engines). This allows the animation and, to a lesser extent, interactivity aspects of educational content to be a native part of the content itself and not to be an afterthought. It facilitate later and looser coupling with further technologies. It allows more ReSTfullness (restafari !). It does not cause cancer. Well, I don’t know. It tastes good. (note to myself : consider discarding this whole paragraph) :)

Flash applets, on the other hand, can be made somewhat accessible but this may not be an easy task for the average Flash developer, and SMIL sounds like a much more accessibility-friendly technology. There even is a DAISY profile for SMIL documents. I should have a deeper look into these profiles.

But interactivity with specific application logic seems to require a bit of scripting anyway, doesn’t it ? Here comes Ecmascript with SMIL, which should probably be limited to a minimum. Can you always provide accessibility-safe fallback mechanisms for a SMIL document if you introduce scripting for interactivity ? I am not sure. I will have to figure this out. Maybe the DAISY SMIL profile tells me more about this.

After a first glance at these standards and being an non-expert in animated contents, it seems to me that there ARE available and mature open standards which cover most of the accessible and digital textbook related concerns. There should be no need to develop any addiction for Flash authoring systems.

But the problem is that these standards are still “emerging”. They were proposed several years ago, are slowly maturing and their support in modern web browsers only starts to become a reality. The most advanced support for SMIL-animated SVG comes with Opera. And is said to be available in Firefox 3.6 as far as I understood. I’ll test this stuff with Opera until Firefox 3.6 comes to ubuntu. The lack of consistent support for SMIL and SVG animation can be overcome with the use of free software SDK or Javascript libraries which take SMIL elements as input and generate equivalent Javascript instructions as output. For instance, the RaphaelJS Javascript library allows browsers to support animated SVG even if such a support is not built-in for them. As far as I understand, the Ample SDK allows SMIL animations to be supported by non SMILable browsers, too.

The main problem is not in web browser support, though. The main problem is that there is almost no (free software) authoring tools for such animation and interactivity technologies. Limsee2 is a code editor/development environment for SMIL (does it support SVG animation ?) but its INRIA authors stopped working on it some time ago. And there seems to be no real community behind it. Limsee3 is not a further version of Limsee 2 (despite the name). It is a WYSIWYG SMIL authoring tool but it does not seem to support SVG animation (does it ?). And it may also probably stop being developed as soon as the governmental subsidies behind the corresponding research project end. Yet another research package soon to be dying on the labs shelves ?

This sends me back to my above observation about the non-existence of a sufficiently-big or proficient-enough community of educators who can use AND develop such advanced authoring tools with accessibility in mind. Too bad…

Madswatter and Ajax animator are very early prototypes for animation authoring environments. There are other free software attempts currently aiming at proposing a proper animation editor: clash/geesas (which is a fork of pencil) and moing… Maybe you’ve heard of other projects ? Inkscape has some plan for introducing SMIL authoring capabilities. There even is a mockup of the user interface for the timeline-based authoring of animations. This is work in progress. Well, maybe this is more than just a work on blueprints : the Inkscape roadmap mentions simple and limited animation authoring as a feature for their next release (version 0.48) ! The 0.49 version should focus on much more support for animated SVG. Exciting ! This topic is hot right now. Itches are starting to be scratched a lot !

That being said, I realize I already have a tool for authoring animations. It’s Open Office Impress. And the Impress wiki tells me that its animation are based on SMIL ! When I have a look at the xml file saved by Impress (inside its ODP zipped archive), I can indeed see SMIL element names and attribute names mixed with Open Office specific elements and attributes, even though the resulting document may not be SMIL compliant, strictly speaking. A limited effort (XLST or a custom extension) may allow to produce real SMIL documents.

Instead of using elearning-specific authoring tools (think Xerte, eXe, …), what if futur editing software for educational contents were tools I (or any educator) already have on my desk : Inkscape for the creation of bits of animated graphics and/or Open Office Impress for the layout and animation of the overall animated document? In Inkscape, the “properties” window of any object even reveals some event fields for Ecmascript/Javascript instructions (onclick, onmouseover, etc.). Too bad Impress can’t properly import SVG content. But maybe this is not required. In the end, e-learning specific tools would be required anyway for the packaging of the resulting animated and interactive content into Learning Management Systems such as Moodle. Such content packages would need to be made SCORM or AICC compatible so that they expose their navigational and educational structure to these platforms via a standard API. I read the SCORM is not ideal as such an API from an accessibility perspective because it heavily relies on Javascript (it is a Javascript API). But does the use of a scripting language always prevent accessibility ? I don’t know. SCORM may be nice for portability from LMS to LMS. But so nice for accessibility.

At the moment, I feel like the ideal authoring chain of tools for educational content / textbooks would be as follows :

  1. Inkscape in order to create the graphism, layout and animation of individual educational “applets” : cross words, coloring books, simulations, geometry tools, … the result being saved as an animated (and partial SMIL-interactivity) SVG file with event-hooks being defined so that we can go to the next step
  2. an ECMAscript code editor (I am not into this emacs thing… Eclipse anyone ?) in order to transform this animated SVG file into an animated AND interactive SVG piece of content
  3. Open Office Impress in order to create the layout, structure and general content of your course/manual/textbook chapter/whatever, inserting the SVG file and adding further animations as well as individual multimedia items (sound clips, videos, hyperlinks), the result being saved as a SMIL/HTML document
  4. More scripting edition of this document if needed (but would it be needed at this stage ? I can’t tell)
  5. CSS styling would be made ready for the document at this stage or earlier (can Open Office make any use of existing CSS stylesheets or would it always mix them into its own content format ?)
  6. a SCORM packager such as Reload Editor would import this content and allow the author to specify the SCORM relevant bits of information, the result being saved as a Moodle-ready package
  7. Your favority Moodle-like LMS platform would serve the content to users, possibly running on their laptop in an offline fashion

This whole chain of tools would probably benefit from being powered by a web content management system (Plone ? Drupal ?) so that the assembly line is smoother and allows widespread collaboration, with workflows, access control and so on. No need to get stuck back to the Dreamweaver era of the I-am-waiting-for-the-Dreamweaver-guy-to-update-my-textbook.

Now it’s your turn. What do you think ?

La téléconférence du geek

Tuesday, November 10th, 2009

Une grande SSII a enfin signé avec l’une des associations qui bénéficie du wecena. Le communiqué de presse est prêt. L’appel au volontariat destiné aux 4000 salarié est prêt à être envoyé. Il ne me manquait plus qu’une chose pour faire nickel : avoir une solution de téléconférence gratuite pour accueillir les volontaires à distance, répondre aux questions des personnes intéressées (managers, volontaires en puissance, etc.). J’ai donc dû mettre au point un système de téléconférence spécial geek dont j’espère bientôt faire la démo. Voici mes notes de travail, prenez-en soin !

Sous ubuntu 9.04, j’ai installé webcamstudio, téléchargeable via http://www.ws4gl.org/, installable depuis un dépôt ou bien depuis les sources, facile à compiler avec NetBeans sous Ubuntu (installer le paquet NetBeans). Webcamstudio est un logiciel en Java qui permet de créer une webcam virtuelle qui peut capture l’image de votre bureau, des animations, du texte, un canal IRC, une vidéo Youtube, le flux video d’une vraie webcam branchée sur le PC…
Mettre la sortie en 320×240 pour éviter tout risque d’incompatibilité avec le site qui va diffuser la vidéo (ustream.tv par exemple).
WCS créé un device “Video loopback” de type “Video 4 Linux” (et pas Video 4 Linux 2).
Lancer l’utilitaire gstreamer-properties pour vérifier que ubuntu arrive à lire cette webcam et informe ubuntu de la webcam par défaut. Video / entrée / Video for linux 1, device = Video Loopback 1. Faire un test pour vérifier que ubuntu détecte bien la webcam virtuelle créée par webcamstudio.
Aller sur ustream.tv et y créer son compte utilisateur.
Sur le site de webcamstudio, il y a une explication pour savoir comment faire en sorte que flashplayer accepte d’utiliser comme il se doit la webcam virtuelle : fait aller sur un site macromedia.com pour y régler les paramètres de sécurité du flashplayer de votre navigateur : “toujours autoriser www.ustream.tv, cdn1.ustream.tv” (et aussi quantserve. com ?).
Puis se logger dans ustream et aller dans l’interface de broadcast. Y sélectionner son périphérique vidéo (video loopback) et son périphérique audio (”linux microphone”).
Ensuite, il y a un certain nombre de réglages à faire pour avoir du son diffusé. On lance donc l’utilitaire “pavucontrol” de pulseaudio sur ubuntu (à partir de la 9.04). Cet utilitaire permet de :

  • régler chaque périphérique audio d’entrée (les sources) et de sortie (les sinks)
  • régler aussi les “moniteurs” qui sont des genres de périphériques virtuels créés par pulseaudio ; notamment, pulseaudio créée un “moniteur” associé à votre périphérique de sortie son (vos hauts-parleurs) ; ce moniteur se comporte comme une sorte de microphone virtuel qui serait branché sur vos hauts-parleurs et vous permet de capturer tout son émis par votre PC pour pouvoir l’enregistrer à nouveau ou le diffuser en streaming par exemple,
  • relier chaque logiciel qui produit du son (lecture) ou en capture (enregistrement) à un périphérique de sortie son de son choix, y compris aux “moniteurs” ; en l’occurence avec une seule carte son en sortie (pas de casque audio USB), vous n’avez qu’un seul choix pour les logiciels de lecture. Par contre, pour les logiciels de capture, vous pouvez choisir de capturer ce qui entre dans le microphone ou bien ce qui entre dans le moniteur de la sortie de votre carte son, à savoir ce qui sort de la carte son… Vous suivez ? J’explique…

En pratique, le périphérique de sortie par défaut, c’est la sortie carte son (un casque dans mon cas). Et le périphérique d’entrée par défaut, c’est mon microphone du casque audio. Je mets en sourdine le microphone de ma webcam.
De plus, le site ustream.tv qui diffuse votre video et votre son est utilisé via votre navigateur web, firefox dans mon cas. Firefox apparaît donc dans pavucontrol de 2 manières :

  1. en tant que logiciel de lecture (c’est le son joué par firefox), je le relie à la sortie de ma carte son mais je le mets en sourdine le temps de mon broadcast (sinon, ça pourrait faire de l’écho).
  2. mais aussi et surtout en tant que logiciel d’enregistrement (c’est l’applet flash de ustream.tv qui capture mon son) que je relie au moniteur pulseaudio de ma carte son de manière à enregistrer tout le son qui sort de ma carte et pas seulement ma voix captée par mon microphone mais aussi les MP3 joués en local, les conversations téléphoniques via un softphone, etc.

Le problème, c’est que ma voix qui entre dans le microphone ne ressort pas dans la sortie de ma carte son. Sinon, ça me ferait de l’écho dans les oreilles. Donc ma voix n’est plus capturée par l’applet flash de firefox/ustream puisque celle-ci est maintenant associée au moniteur de la sortie son.
Pour contourner ce problème, on créé une loopback audio grâce à 2 utilitaires de pulseaudio. Ouvrez une fenêtre de terminal et tapez-y parec | pacat.
parec apparaît dans pavucontrol en tant que logiciel de capture son à qui on demande de capter l’entrée son du microphone. Il envoie ce son (ma voix) vers pacat via un pipe. pacat, lui, apparaît dans pavucontrol comme logiciel de lecture. Et il envoie forcément sa sortie (ma voix) vers la carte son. Donc ya de l’écho. Tant pis, on diminue le son dans le casque (physiquement), si ça gêne.
Mais on obtient le résultat recherché : à savoir permettre à firefox/ustream de capturer non seulement ma voix mais également tout ce qui sort des logiciels audio du PC.
Maintenant, l’audioconférence. Pour cela, j’utilise un softphone, en l’occurence Twinkle (ou parfois Ekiga). J’ai un compte SIP chez un opérateur de voix sur IP. Je recommande ippi.fr, c’est gratuit. Ippi.fr offre (gratuitement via SIP) des salles d’audioconférence. J’appelle donc avec twinkle cette salle d’audioconférence. Twinkle apparaît dans pavucontrol à la fois comme logiciel de lecture et comme logiciel d’enregistrement. En tant que logiciel d’enregistrement, je lui demande simplement d’enregistrer ma voix. En tant que logiciel de lecture, je lui demande juste de faire son travail, c’est-à-dire d’envoyer le son produit par les interlocuteurs de l’audioconférence vers la sortie de ma carte son, de manière à ce qu’il puisse être capté, comme ma voix à travers le moniteur pulseaudio de cette sortie, sur lequel est branché la capture audio de firefox/ustream.
Et voila.
Les inconvénients actuels :

  • ça bouffe un max de CPU tout ça : twinkle, webcamstudio, firefox avec l’applet flash de ustream, pulseaudio en plus. C’est tout juste tenable sur mon laptop dual core 2×1,2 GHz. On peut rendre les choses vivables grâce à un ajustement des priorités via “sudo htop”. pulseaudio tourne d’office à haute priorité (-11). Je mets manuellement twinkle à -2 (prioritaire). Et firefox à -1 et on laisse webcamstudio à 0. Toutes les applis non prioritaires (applets Gnome par exemple) peuvent être passées à 1 (non prioritaires). Faute de ce type de réglages, l’audioconférence peut être ingérable ou la capture sur ustream de trop mauvaise qualité (y compris des pertes de trames entraînant une désynchronisation de la voix et de l’image si on demande à ustream d’enregistrer le broadcast pour la postérité). Autre possibilité de contournement : faire tourner le tout sur un PC plus puissant. Autre possibilité de contournement, faire une conférence main libre avec un téléphone normal. On évite ainsi le softphone mais le son capté le sera via un microphone près du téléphone.
  • j’entends de l’écho quand je parle (à cause de parec|pacat). Possibilités de contournement : est-ce qu’utiliser le module-loopback de pulseaudio règlerait ce problème (pacmd load-module module-loopback) ? a priori non. Autre possibilité de contournement : le téléphone main libre à côté du PC. Autre possibilité : baisser le son du casque quand je parle et le remonter quand j’ai fini de parler. Autre possibilité : trouver un moyen pour dire à pulseaudio qu’un logiciel de capture devrait combiner 2 périphériques d’entrées au lieu d’un seul : le microphone qui capte ma voix et le moniteur de la sortie son qui ne capterait plus ma voix (on se passerait de parec|pacat).
  • ma webcam est une caméra sur batterie, il faut que je pense à la brancher sur secteur sinon… elle se vide.
  • il faudrait voir si on ne peut pas diffuser une meilleure qualité d’image (640×480) et ce que ça implique en terme de CPU.

Au final, je me dis qu’il faut que je remette la main sur mon téléphone SIP matériel (Gigaset de Siemens) et ça simplifera mon problème de CPU. Mais ça ne donne pas une solution “portable”…

How to record VoIP calls from your PC ?

Wednesday, July 29th, 2009

Beyond having low and flat rates, beyond allowing mobility without a mobile phone, voice-over-IP has another advantage : it allows calls to be recorded. Here is how to proceed (assuming you are geeky enough…).

For instance, this week, I could not physically join an interesting meeting between French NGO leaders and IT professionnals considering how to best volunteer for these NGOs. So I gave the organizer of the meeting a VoIP phone (Siemens Gigaset) and asked him to call the Asterisk-powered SIP call conference system our nonprofit has (thank you Fred and JML  for this !). It allowed me to join the meeting as a distant caller and… to record a big MP3 file of the 3-hours long discussion.

For recording this voice-over-IP conference, here is my setup. I was calling from a linux PC, 2GB of RAM and a great free software SIP-compatible softphone called Twinkle (greater than Ekiga IMHO). My voice-over-IP provider was our Asterisk server. I could have used any other free SIP provider, such as ippi. Ippi is great and I am a happy customer of their service.

I was also running the Wireshark packet sniffer as root. After the call, I had to post-process the VoIP packets Wireshark captured. Wireshark decoded them and extracted the audio content of the conversation. Then I used Audacity to normalize, level and compress the audio and to save it as a big podcast-ready MP3 file.

The tricky parts :

- The Siemens Gigaset can’t (easily ?) be configured to call an SIP address which does not have the same domain as the SIP account it is using. For instance, if the audioconference system is at sip:conference@sipprovider.org then you’d better configure the phone to use a sip:mygigaset@sipprovider.org account rather than a sip:mygigaset@anotherprovider.org Too bad… :(

- You should warn the participants they are being recorded. Not only can this be required by your local laws but it also gives them another incentive to think of speaking close to the phone which is recording them in the meeting room.

- During the conversation, people in the meeting room would sometimes forget the presence of the phone and speak too far from its microphone. Hence I had to say “Can’t hear you !” from time to time and participants would take the phone in their hand as if it were a microphone. Local participants (in the meeting room) would even call the distant participants “the phone” and say “Hello, phone, how are you ?” and stuff like that. It was a bit as if the phone was yet another participant speakers had to take into their hand in order to be heard and recorded. Quite funny. Having the phone close to the speaker is also a matter of discipline and habit for the meeting organizer.

- Distant participants like me would use the “mute” feature of  their local (soft-) phone so that they can’t be heard when not talking, so that there is less background noise in the conversation.

- I would have preferred to have at least one local participant available in a text-based chatroom (think IRC channel) or at least in some instant-messaging system. This would have allowed me to remind the phone has to be kept close to the current speaker and stuff like that without having to loudly say “Can’t hear you”. Unfortunately, the only IM-available participant was the main organizer who quickly forgot his screen and keyboard so that he could focus on the discussion going on.

- A 3-hours call required a lot of RAM for wireshark, even though the captured packets were being saved on the hard-drive ; when post-processing the packets, I had to split the session into 4 smaller parts so that wireshark would not crash when doing its audio extraction.

- When post-processing one of these smaller packet captures, wireshark would sometimes not detect the accurate nature of the packets : instead of seeing them as Real-Time Protocol (RTP) packets which they indeed were, it detected them a “OICQ” packets. So I had to force wireshark into considering them as RTP files (using its “Decode…” command).

- In order to have wireshark decode and save an audio file from the RTP streams, the command to be used is “RTP / Show all streams” from its “Statistics” menu. Then you use the “Analyze” button and then the “Save Payload” button. I had to select the “.raw” (vs. “.au”) format for the audio file because of the codec used by the VoIP phones.

- When saving the audio file, I decided to save distinct files for the forward (my voice, sent from my softphone to the audioconference service) and reversed stream (the meeting voices, sent from the audioconference service to my softphone). This allows distinct and finer audio postprocessing (the audio levels were different).

- In audacity, I chose to first normalize the audio tracks, then level them (it adjusts the audio level when the speaker changes or talks to far from the phone) then audio-compress them a bit. I would then merge the parts and tracks into a single mono audio file. Stereo does not make much sense in the case of a many-participants call but can be useful if you record a 2-participants conversation.

That’s it. Now I have to finish the audio-postprocessing of my MP3 and find some place on the Net where to upload it for the participants. What do you think ? Do you have some tricks to share on this topic ?

1 million de salles d’attentes… pour la recherche scientifique

Friday, March 13th, 2009

Hier soir, je tchattais avec mon pote Yann. Comme à notre habitude, on échange nos idées farfelues du moment. Cette fois-ci, c’est mon tour. Qu’en pensez-vous ?

(22:37:13) Sig: si les 1 million de salle d’attente qui existent dans le monde accueillaient chacune un vieux PC à bout de souffle pour faire des calculs pour la recherche scientifique
(22:37:35) Sig: alors on pourrait accélérer la découverte de remèdes contre les maladies type Alzheimer et une trentaine d’autres maladies.
(22:37:45) Yann: ok
(22:37:50) Sig: Rien qu’en France, il y a environ 100.000 salles d’attente
(22:38:15) Yann: et j’ai deja 1 PC a bout de souffle, pu ke 99 999 a trouver ;)
(22:38:21) Sig: Or j’ai 40 vieux PC stockés chez moi et chez ma grand-mère ainsi qu’un système logiciel pour les contrôler à distance via le Net
(22:38:33) Yann: Ok je capitule !
(22:38:34) Sig: j’ai pas d’écran mais yen a pas besoin pour la recherche scientifique
(22:38:42) Sig: :)
(22:38:49) Sig: et l’idée de salle d’attente, c’est de dire :
(22:39:06) Sig: vous voyez ce PC et la pile de tracts posée dessus, prenez-en un :
(22:39:36) Yann: de tract ?
(22:39:38) Sig: ” Emmenez moi (le tract) chez un autre médecin/dentiste/salle d’attente pour qu’il puisse demander, lui aussi, son PC de recherche médical en allant sur http://…”
(22:39:50) Yann: ok
(22:39:51) Sig: l’idée est d’utiliser la salle d’attente comme lieu de viralité
(22:40:02) Yann: ca marche bien ca deja !!!!!!
(22:40:08) Sig: oui (rhumes…)
(22:40:10) Sig: :)
(22:40:13) Yann: oui ;)
(22:40:28) Yann: (on n’a deja notre theme publicitaire ;o)  )
(22:40:41) Sig: ensuite, les tracts peuvent inviter les gens à donner des vieux PC au projet ou à participer à la distribution
(22:40:52) Sig: de vieux PC récupérés vers les nouvelles salels d’attente en demande.
(22:40:59) Yann: ok
(22:41:29) Sig: Enfin, dernier point, lorsque on peut récupérer des écrans, j’ajoute un logiciel sur le PC :
(22:41:50) Sig: pour que les gens qui passent en moyenne 35 minutes dans la salle d’attente mettent leur cerveau au service de la recherche scientifique
(22:42:03) Yann: ???
(22:42:18) Yann: je ne suis plus la !
(22:42:19) Sig: sur des projets sur le principe de galaxyzoo.org, clickworkers, foldit, stardust@home (tu iras voir galaxyzoo.org c’est super joli)
(22:42:27) Sig: le principe de galaxyzoo :
(22:42:48) Sig: on te montre une photo d’une galaxie jamais vue par l’être humain (tu es le premier car elle a été prise en photo par un téléscope robotisé)
(22:42:52) Sig: et tu as 2 boutons :
(22:43:02) Sig: bouton 1 : “elle tourne dans le sens des agiuilles d’une montre”
(22:43:08) Sig: bouton 2 : “elle tourne dans l’autre sens”
(22:43:30) Sig: des millions de clics permettent au labo d’astronomie d’Oxford de mieux connaître la création de l’univers
(22:43:38) Yann: comment ?
(22:43:42) Sig: ya pas mal d’autres projets qui fleurissent actuellement dans d’autres domaines scientifiques sur ce principe
(22:43:44) Sig: comment :
(22:43:54) Sig: certaines théories sur l’expansion de l’univers disent :
(22:44:08) Sig: “il devrait y avoir 50% de galaxies qui tournent comme-ci et 50% comme ça”
(22:44:20) Sig: et d’autres disent “non, 51% dans ce sens, et 49% dans l’autre sens”
(22:44:43) Sig: ce projet permet d’invalider les théories fausses et d’avancer dans notre compréhension du passé et de l’avenir du cosmos… c bo. :)
(22:44:52) Sig: il suffisait de compter :)
(22:45:05) Yann: oui, bien vu :)
(22:45:10) Yann: Mes comments :
(22:45:14) Sig: oui
(22:45:22) Yann: l’idee me plait !
(22:45:26) Sig: ok
(22:45:33) Yann: les pb ke j’anticipe :
(22:45:53) Yann: PC en reseau ds cabinet medical = pb deontologie potentiel
(22:46:03) Yann: du moins y aura des gens a penser ca
(22:46:29) Yann: ensuite, l’installation  = tres time consuming !!!!!!
(22:46:32) Sig: ok j’y avais pas pensé mais c’est une bonne remarque
(22:46:36) Sig: (pour le pb de sécurité/déontologie)
(22:46:45) Yann: et la maintenance aussi !
(22:47:00) Sig: pour l’install et la maintenance, non aucun pb :
(22:47:04) Sig: 100% automatisé !
(22:47:13) Yann: j’te sens ds l’exces d’optimisme la non ?
(22:47:24) Sig: et si le pb est trop grave pour être traité en automatique, il faut que quelqu’un (bénévole) vienne remplacer le PC par un autre
(22:47:47) Sig: non non j’utilise un logiciel fait pour gérer de manière automatique des milliers de PC dans des centres de recherche.
(22:47:56) Yann: tu ne va pas automatiser le pc qu’il faut physiquement deposer au sol ds 100 000 salles d’attente !!!!
(22:48:14) Sig: non le transport et le branchement restent à la charge des bénévoles
(22:48:26) Yann: ne néglige pas cette contrainte, elle estr forte….mais….
(22:48:29) Sig: oui
(22:48:39) Yann: C ds les obstacvle qu’on trouves d’autres idees
(22:49:07) Yann: Ca me parait hyper lourd a gerer (rien que l’aspect physique et maintenance sur place qd necessaire)
(22:49:14) Yann: par contre ca me donne 1 idee
(22:49:23) Yann: C tellement lourd comme contrainte
(22:49:33) Yann: qu’il faut 1 partenaire serieux !
(22:49:38) Yann: style la secu !!!!
(22:49:52) Yann: t’imagine en terme d’image !!!!!
(22:49:57) Sig: mmm… la sécu… pkoi pa
(22:50:12) Yann: ou autre organisme, type mutuelles…
(22:50:21) Yann: ou pfizer ou Rhone poulenc….
(22:50:28) Yann: le privé du cabinet medical koi !
(22:50:38) Sig: oui je pensais aux labos pharmaceutiques
(22:50:46) Yann: bingo
(22:50:54) Sig: dans le cadre d’un mécénat alors ?
(22:51:02) Yann: sauf que eux vont vouloir mettre le nez ds le soft
(22:51:05) Yann: (oui)
(22:51:12) Yann: afficher de la pub etc
(22:51:21) Yann: et la on a un pb de deontologie potentiel !
(22:51:30) Sig: ils ne peuvent pas afficher de la pub pour des produits c’est interdit dans les salles d’attente
(22:51:31) Yann: mais ca me parait faisable
(22:51:39) Yann: pffffff
(22:51:55) Sig: mais ils peuvent afficher de la communication sur leur entreprise (pas commercial mais “communication institutionnelle”)
(22:51:55) Yann: les pub de cigarettes aussi C interdit ds les kfé !
(22:52:10) Yann: C pareil !
(22:52:25) Sig: pas du point de vue du conseil de l’ordre, je pense.
(22:52:29) Yann: C juste le credit d’impot qui change ;)
(22:52:34) Sig: oui
(22:52:55) Yann: je suis ok avec toi : C moralement acceptable pr des mecs ds des bureaux
(22:53:25) Yann: mais C pareil, ds le meme but : vendre a la prolo de la salle d’attente du doliprane plutot que du generique paracetamol !
(22:53:32) Sig: yes
(22:53:46) Yann: je n’aime pas ca, mais j’suis lucide !
(22:54:03) Yann: bref : l’idee me parait bonne des le depart ;)
(22:54:12) Sig: ok :)
(22:54:31) Yann: autre “pb” : il faut travailler au moins 1 an a tps plein pr lancer un truc pareil !
(22:54:39) Yann: t’as 1 an devant toi toi ?
(22:54:49) Sig: je vois pas le besoin  de travailler un an dessus
(22:55:00) Sig: “yaka” trouver un médecin prêt à expérimenter
(22:55:07) Yann: les contacts, ajuster les idées etc ???
(22:55:36) Yann: C un projet a part entiere ton truc la !
(22:55:48) Yann: limite faut monter 1 asso
(22:55:57) Yann: dc statut a rediger etc
(22:56:07) Yann: j’arrive meme pas a faire mes cpte !!!
(22:56:08) Sig: fo voir comment ça se goupille mais, à la limite, ça pourrait se faire “à la mode open source”, avec peu de moyens et sans structure juridique
(22:56:20) Yann: la le pro C toi !
(22:56:24) Yann: je te fais confiance !
(22:56:31) Sig: en pratique, la question qui compte, c’est :
(22:57:02) Sig: est-ce que tu connais un heureux propriétaire de salle d’attente que tu pourrais convaincre d’accueillir un PC connecté à son ADSL pour la recherche scientifique ?
(22:57:19) Yann: reponse immediate : non !
(22:57:32) Yann: mais suis optimiste : j’peux trouver oui ;)
(22:57:38) Sig: :)
(22:57:59) Sig: de mon côté, je vais en causer avec notre pédiatre qui est très impliqué dans des assos
(22:58:16) Yann: j’vois mon doc fin mars (en pcipe si j’y pense)
(22:58:17) Sig: et sinon, j’essaierai avec une copine orthophoniste
(22:58:38) Yann: et moi je garde ca en tete, on connais tous forcement des docs !
(22:58:51) Sig: en attendant, fo que je te laisse pour aller contrôler la fin d’installation automatique de 2 PC qui tournent depuis tout à l’heure dans ma cuisine
(22:59:03) Yann: j’crois que la maman du copain de ma soeur est pediatre
(22:59:11) Sig: eh eh :)
(22:59:19) Sig: nous vivons dans un monde de salles d’attente !
(22:59:53) Yann: “si la maison du bonheur existait, la plus grande piece serait la salle d’attente”
(22:59:58) Yann: de PasDeMoi
(23:00:02) Sig: ok
(23:01:05) Yann: allé a +
(23:01:13) Sig: a+

Qu’en pensez-vous ? Vous connaissez une salle d’attente accueillante pour un de mes vieux PC ?

Le code du wecena est libre

Tuesday, March 3rd, 2009

“Vive le wecena libre !” comme qui dirait l’autre. Ce petit message pour signaler à ceux que cela intèresse que j’ai libéré le code qui me permet de faire tourner wecena.com. En d’autres termes, ce logiciel libre est désormais distribué (publiquement) sous licence GNU Affero General Public License v.3.

Le code en question constitue une suite de produits d’extension pour le système de gestion de contenu Web Plone. Certains de ces produits sont spécifiques au fonctionnement du wecena (les produits wecena_core et wecena_integration). Certains autres sont plus génériques et peuvent avoir leur utilité hors wecena. Je pense notamment à wecena_dynamicroles pour améliorer la flexibilité du système de sécurité de Plone et à wecena_ldapuser pour synchroniser de manière bidirectionnelle les utilisateurs Plone avec les entrées d’un annuaire LDAP.

Votre expertise python/Zope/Plone est plus que bienvenue si vous voulez vous amuser avec ces produits et filer un coup de main au passage !

How to get visual performance profiles from plone doctests ?

Thursday, February 5th, 2009

I am developping a couple of Plone 3.x products. They have some tests, including a huge functional doctest which takes a long time to run (about a couple of hours !) but covers some of my most interesting use cases. I wanted to use these tests in order to get some insights about possible performance bottlenecks and other optimization hot points in my code. The result of my effort was a very nice visual chart showing these bottlenecks and hotpoints.

[update: added another visualization package, see at the end of the post]

Here is how I had to proceed (note that I am more of a foolish and coward hacker than an expert and I decline any responsibility on the consequences of following my howto !) :

1. Give your python a suitable profiler

Plone 3.x requires zope 2.10 which in turn requires python 2.4. More recent versions are not supported AFAICS. Problem: python2.4 does not have a reliable performance profiling module. Its “hotshot” module is both slow (when loading statistics) and badly bugged : it crashes when you have it load some of the profiles it can generate. You have to add a better profiler to your python environment, namely cProfile (which is shipped with python 2.5).

I am a terrible sysadmin and I don’t really understand (and care about) how python manages its pathes and accesses its libraries. So I did this :

  1. download and unzip the source tarball of python 2.5 so that you get cProfile source code
  2. locate relevant files referring to lsprof (the old name of cProfile), using a grep -R lsprof * on the source directory
  3. I personnally located the following files (I leave cProfile test files apart) : Lib/cProfile.py Modules/_lsprof.c and Modules/rotatingtree.* (.c and .h)
  4. download and unzip the source tarball of python 2.4
  5. copy the located cProfile files from their python 2.5 location to the proper dirs into the source code of your fresh python 2.4
  6. update python 2.4 ’s setup.py file so that the line below is added just after the hoshot one : exts.append( Extension(’_lsprof’, ['_lsprof.c', 'rotatingtree.c']) )
  7. did I mention I am so bad at hacking things that I don’t even provide a patch for the operations above ?
  8. compile python 2.4 using a ./configure then make

At this point, you must have an executable python interpreter version 2.4 which includes cProfile. You can check by launching this python and trying a import cProfile which should not fail.

I replaced my system python2.4 by then doing a sudo make altinstall but I also had to manually tweak my system files so that this new python2.4 gets properly called (I am using ubuntu 8.10 intrepid, BTW) :

cd /usr/bin

sudo mv ./python2.4 ./python2.4.5

sudo ln -s /usr/local/bin/python2.4

Now, a plain command line call to python2.4 should give you an interpreter prompt which lets you import cProfile if you dare. I suffered some colateral damage here : the python prompt lost its ability to have previous lines copied at the prompt by pressing the Up/Down arrows. And I had to re-install reportlab from the source (some of my products depend on pisa which depends on reportlab). Anyone knows how to restore this Up/Down arrow capability ?

2. Recreate your buildout using this new python version

So that zope gets recompiled using your new python version :

rm -Rf parts bin develop-eggs

python2.4 bootstrap.py

bin/buildout

3. Patch zope testrunner so that it supports cProfile instead of only supporting hotshot

I got a bit confused because my buildout contains 2 zope testrunners. It took me some time to figure out which was which : the one which is used by the zope instance your buildout creates is the one which is shipped with zope 2.10 and is located at parts/zope2/lib/python/zope/testing/. The other one I have is in the zope.testing egg. I don’t know how and why I got such an egg. Anyway, this egg supports both hotshot and cProfile whereas zope 2.10 testrunner doesn’t. So I hacked the weaker/older zope 2.10 testrunner with some inspiration from zope.testing so that cProfile can be used when running tests. Here is the diff you can use for enhancing  parts/zope2/lib/python/zope/testing/testrunner.py. Oops, left version is the modified one, right version is the original one.

38,69d37
< before_tests_hooks = []
< after_tests_hooks = []
< available_profilers = {}
<
< try:
<     import cProfile
<     import pstats
< except ImportError:
<     pass
< else:
<     class CProfiler(object):
<         “”"cProfiler”"”
<         def __init__(self, filepath):
<             self.filepath = filepath
<             self.profiler = cProfile.Profile()
<             self.enable = self.profiler.enable
<             self.disable = self.profiler.disable
<
<         def finish(self):
<             self.profiler.dump_stats(self.filepath)
<
<         def loadStats(self, prof_glob):
<             stats = None
<             for file_name in glob.glob(prof_glob):
<                 if stats is None:
<                     stats = pstats.Stats(file_name)
<                 else:
<                     stats.add(file_name)
<             return stats
<
<     available_profilers['cProfile'] = CProfiler
<
75,98c43
<     pass
< else:
<     class HotshotProfiler(object):
<         “”"hotshot interface”"”
<
<         def __init__(self, filepath):
<             self.profiler = hotshot.Profile(filepath)
<             self.enable = self.profiler.start
<             self.disable = self.profiler.stop
<
<         def finish(self):
<             self.profiler.finish()
<
<         def loadStats(self, prof_glob):
<             stats = None
<             for file_name in glob.glob(prof_glob):
<                 loaded = hotshot.stats.load(file_name)
<                 if stats is None:
<                     stats = loaded
<                 else:
<                     stats.add(loaded)
<             return stats
<
<     available_profilers['hotshot'] = HotshotProfiler

>     hotshot = None
288c233
<     if len(available_profilers) == 0 and options.profile:

>     if hotshot is None and options.profile:
320,324c265,266
<         if available_profilers.has_key(’cProfile’): prof = available_profilers['cProfile'](file_path)
<         else: prof = available_profilers['hotshot'](file_path)
<         before_tests_hooks.append(prof.enable)
<         after_tests_hooks.append(prof.disable)
<

>         prof = hotshot.Profile(file_path)
>         prof.start()
335c277,278
<             prof.finish()

>             prof.stop()
>             prof.close()
342c285,292
<         stats=prof.loadStats(prof_glob)

>         stats = None
>         for file_name in glob.glob(prof_glob):
>             loaded = hotshot.stats.load(file_name)
>             if stats is None:
>                 stats = loaded
>             else:
>                 stats.add(loaded)
>
459d408
<                 [hook() for hook in before_tests_hooks]
461d409
<                 [hook() for hook in after_tests_hooks]
656,659c604
<     [hook() for hook in before_tests_hooks]
<     results = run_tests(options, tests, layer_name, failures, errors)
<     [hook() for hook in after_tests_hooks]
<     return results

>     return run_tests(options, tests, layer_name, failures, errors)

Oh, BTW, this diff also lets you filter out the profiling of the setup and teardown steps of your tests which are of poor value compared to actual tests. Thanks to Daniel Nouri for this.

At this point, you should have given your zope instance the capability of profiling tests using cProfile. You can check it by asking for a debug prompt from zope : bin/instance debug The prompt you get should allow you to safely import cProfile

4. Profile your test

Say you have a Products called Products.DearProduct with some tests. Profile them :

bin/instance test -s Products.DearProduct –profile

At this point, you should get a tests_profile.*.prof file saved in the current dir. It contains the performance profile cProfile generated, using the pstats format. You can manually load and analyze this data. Or have a limited GUI show you what it’s like. Or you can go for the nicer, more insightful version which follows.

5. Visualize and analyze the performance profile you generated

Thanks to Ingeniweb folks, I heard of gprof2dot and xdot. Download them (the scripts, not the folks). Use them to generate and display a very nice graph :

chmod 744 gprof2dot.py

chmod 744 xdot.py

./gprof2dot.py -f pstats -o profile.dot tests_profile.*.prof

./xdot.py profile.dot

Note the * you may replace with the ID of the profile generated above. Or you can use the fancy but dangerous one-liner below which runs the tests,  generates the profile, generates the corresponding graph, displays the results of tests and displays the graph for analysis :

rm -f tests_profile.*.prof && rm -f profile.pstats && rm -f profile.dot && bin/single-instance test -s Products.MyDearProduct –profile > /tmp/test.txt ; ./gprof2dot.py -f pstats -o profile.dot tests_profile.*.prof && less /tmp/test.txt ; ./xdot.py profile.dot

At this point, you should be starring at nice colored graph which represent the flow of your tests and the method which may be performance bottlenecks. And you should be hoping that it was worth the effort.

[Here starts the update]

After some contemplation moment, I tried to analyze the graph of my tests and did not feel extremely happy with this graph visualization. It indeed shows me that the slowlyness of functional doctest is mostly due to the testing framework (zope.testbrowser, etc.). This slowlyness “hides” the optimization opportunities of my code. And I don’t know how to exclude some products from the being profiled or from being present in the profile stats (I would have liked to filter out zope.testbrowser and other Plone-specific things). But, all hope is not lost, here comes kcachegrind:

sudo apt-get install kcachegrind

sudo easy-install pyprof2calltree

pyprof2calltree -o output.calltree.stats -i tests_profile.*.prof -k

Using kcachegrind with the help of pyprof2calltree, I was able to focus on my product methods and identify those methods which deserve some caching. Added some @memoize decorators and reran the profiled tests so that I could enjoy the performance improvement… Happy I am, happy thou shalt be.

What do you think ?

Wow, 10 millions de dollar pour rendre le monde meilleur

Thursday, September 25th, 2008

C’est Noël ? C’est la surenchère ? Nokia promet 150 000 dollars dans un concours d’idées d’applications innovantes et solidaires. Et voilà-t-y pas que Google en promet 10 millions, pour réaliser les cinq de vos projets qui sont les plus susceptibles de rendre le monde meilleur. De quoi être époustouflifié même quand on sait que la X-Prize foundation envisage des concours d’innovations avec des récompenses allant de 100 millions à 1 milliard de dollars ! Google est d’ailleurs un membre actif des concours de cette fondation.

Allez, avec un peu de chances, j’aurai peut-être le plaisir d’offrir un lot de consolation à quelques innovateurs solidaires français ? Quelques équivalents-temps plein d’ingénieurs et consultants informaticiens, gratuitement, pour votre projet d’intérêt général, ça vous tente ?

Au passage, je remercie Monsieur D., de Chambéry d’Albertville, qui a bien voulu me signaler cette initiative de Google que j’avais loupée. Monsieur D. est parfois timide alors il m’avait contacté par mail plutôt que via un commentaire sur ce blog. ;-)

150 000 dollars pour l’innovation technologique à vocation sociale ou environnementale

Wednesday, September 24th, 2008

Nokia lance un concours pour développeurs d’applications solidaires pour téléphones portables. 150 000 dollars seront offerts aux développeurs des applications mobiles qui seront les plus susceptibles de rendre le monde meilleur. N’oublions pas que les populations des pays du tiers-monde sont bien plus équipées en téléphones portables qu’en ordinateur, par exemple.

Alors, forcément, ça me donne envie d’en rajouter une couche. C’est pourquoi je propose aux candidats français de ce concours de bénéficier du wecena pour développer leur projet : je vous propose gratuitement les compétences de nombreux ingénieurs et consultants, au titre d’une forme innovante de mécénat, le wecena. Les conditions à remplir sont détaillées dans mon appel à projet. Dans le cas d’un concours comme celui de Nokia, cela veut avant tout dire qu’il faut déclarer en préfecture une association d’intérêt général en France pour porter le projet, ou s’associer à une association existante.

via WorldChanging

Rapid prototyping with microcontrollers ?

Monday, August 25th, 2008

I have no clue about micro-electronics and embedded systems. I am a Web application architect and developer, working with very high-level programming languages such as Python (or Perl or Java). I hardly remember assembly language from my childhood experiments with an Apple IIe and almost never touched C or C++. But I have been dreaming lately of rapid-prototyping some advanced non-Web application in an embedded system using my programming skills. So I thought I could share bits of my ignorance here. Please bear with me and give me some hints in order for me to best get out of darkness ! :)

Microcontrollers are now gaining capabilities that are comparable to microprocessors of early personal computers. The two most popular microcontroller (uC) series are Microchip PIC uCs and Atmel AVR uCs. For instance the PIC18F25J10-I/SO costs around 3 or 5 euros per unit at Radio Spares (I am in France: think RS in the UK or Allied Electronics in the USA). It has the following characteristics: 40 MHz, RS-232 capabilities (serial port), a “C compiler optimized architecture”, 48 kB of program memory (Flash mem) and around 4 or 5 kB of data memory (SRAM + EEPROM).

There are nice peripherals available, too. For instance this Texas Instrument CC2500 2.4GHz RF data transceiver (= transmitter + receiver) at around 2 to 3 euros per unit or current sensors approximately at the same price. In fact, periphals possibilities are limitless…

For free software hackers, there was a linux version for such chips : uCLinux. But is it still an active project ? I think I read that the comon linux kernel now includes everything that is required for it to run in embedded sytems. What about GNU utilities ? I know there are things like busybox on bigger but still embedded processors (phones). Anything equivalent on microcontrollers ?

There are simulators that will… let you pretend your desktop computer has a microcontroller inside, or sort of. :)

There is at least one C library for microcontrollers. C is considered as a “high-level programming language” in the embeddeds world ! That is to say that assembly language has been the norm. Some higher-levels languages can be used with microcontrollers, including some exotic-to-me Pascal-like languages like XPlo or PMP or Java-like but living dead things like Virgil and… what about my beloved Python ?

There are at least 2 projects aiming at allowing Python-programming on microcontrollers. pyastra is a “Python assembler translator” that can be used with some PIC12, PIC14 and PIC16 uCs. But it looks dead. Pymite looks sexier but not much more active :

PyMite is a flyweight Python interpreter written from scratch to execute on 8-bit and larger microcontrollers with resources as limited as 64 KiB of program memory (flash) and 4 KiB of RAM. PyMite supports a subset of the Python 2.5 syntax and can execute a subset of the Python 2.5 bytecodes. PyMite can also be compiled, tested and executed on a desktop computer.

At the moment, it seems like Python programming on microcontrollers is a dead end. Nothing worth investing time and efforts unless you want to also have to maintain a Python compiler… Same may be true for Java, not mentioning Perl. In fact, it seems to me that the object-oriented crowds are too far from microcontrollers applications to generate enough interest in initiatives such as Pymite, at the moment. Oh, and I am knowingly ignoring C++ which I did not investigate, having no experience in C++.

So what is left in terms of (open source) programming languages that would be of higher level than C ? The best guess I can make is Great Cow Basic, which is a free software Basic (procedural) language. Example programs look nice to me. It has been active recently. And it supports most of the chips I would consider experimenting with.

Next steps for me, I guess, would be to pick a PIC simulator and an IDE for Great Cow Basic (any eclipse plugin ?). Then I will probably have to figure out how a Basic program can be executed on a simulated PIC. And how a PIC simulator can be useful without all of the electronics that would surround it in any real setup. I’ll see that. When I have time to pursue my investigations and experiments in this micro-world.

And piclist is a great site for beginners.

Alitheia core de SQO-OSS pour mesurer la qualité du code

Monday, August 4th, 2008

Un projet de recherche financé par la commission européenne (SQO-OSS) distribue, sous licence open source bien entendu, un logiciel qui analyse la qualité du code source d’un logiciel. Ce logiciel s’appelle Alitheia.

Alitheia parcourt des dépôts de code du style subversion/CVS (et notamment ceux de sourceforge). Des plugins fournissent des mesures du code (nombre de lignes de code, nombre de lignes de commentaires, etc.). Des modules d’Alitheia effectuent des statistiques à partir de ces mesures afin d’estimer la qualité globale du produit analysé. Alitheia se présente soit sous forme d’une application Web, soit, bientôt, sous forme d’un plugin pour Eclipse.

L’intérêt pratique d’Alitheia me semble actuellement limité: il y a peu de mesures disponibles dans la version de démo en ligne, la version pour Eclipse n’est pas encore disponible, les mesures sont effectuées au niveau de chaque fichier source et ne semblent pas encore agrégées au niveau du projet en lui-même (on peut savoir combien de lignes de commentaires il y a dans tel fichier mais pas dans le projet complet). Actuellement, la fonction la plus amusante semble être la mesure de la “productivité” de chaque développeur.

A terme, ce logiciel me semble très prometteur. Son intérêt dépendra essentiellement de la richesse des plugins de mesure disponibles, de l’existence d’un site public permettant de comparer entre eux les projets phare de sourceforge et tigris par exemple, et de la capacité d’Alitheia à produire des indicateurs agrégés significatifs. En ce qui concerne les plugins de mesure, j’espère qu’on va non seulement avoir des plugins mesurant des caractéristiques du code mais aussi (voire même surtout), des plugins mesurant la qualité de la communauté du projet: fréquence et délai des réponses sur les mailing lists, fréquentation du canal IRC de support, nombre et qualité des plugins et modules additionnels, durée de vie d’une version, etc. A suivre !

(via Le Monde Informatique)

Appel à projets informatiques d’intérêt général

Monday, July 14th, 2008

Vous connaissez un projet informatique qui pourrait contribuer à rendre le monde meilleur ? A sauver la planète ? A créer une innovation Internet d’utilité publique ? Ou juste à faciliter la vie de votre association ? A faire avancer une grande cause ou une toute petite ? A faire avancer la science ? Alors répondez à cet appel car je pense pouvoir booster ce projet en recrutant pour lui des mécènes informatiques.

En effet, dans le cadre de ma nouvelle entreprise, je propose mes services professionnels à tout projet informatique d’intérêt général: je fournis (à coût zéro, cf plus bas) mes compétences en tant que directeur de projets informatiques innovants ainsi que l’accès aux compétences de très nombreux autres ingénieurs informaticiens, sur leur temps de travail. Vous voulez des compétences d’ingénieurs informaticiens pour rendre le monde meilleur ? En voila !

Notez que je ne place, a priori, aucune limitation de thème ou de domaine : lutte contre la pauvreté, recherche scientifique, défense de l’environnement, santé, handicap, protection de l’enfance, etc. peu importe du moment que ce projet va vraiment dans le sens de l’intérêt général et de l’utilité publique (cf. ci-dessous).

Les conditions à remplir

Pour que mon entreprise puisse intervenir, votre projet informatique doit absolument :

  • être “d’intérêt général”, c’est-à-dire être porté par un organisme ayant le droit, en France, d’émettre des reçus fiscaux en échange des dons reçus (mécénat)
  • ne pas être un tout petit projet: il doit nécessiter, de la part des mécènes, au moins 1 ingénieur à temps plein
  • être porté par une équipe déjà active : je peux fournir entre 2 fois et 5 fois le temps que vous passez déjà sur le projet, en tant que bénévoles ou salariés ; si vous ne travaillez pas déjà sur le projet, je ne peux rien faire (0 fois 2 égal 0 !)
  • être un projet qui en vaut vraiment la peine: avoir un véritable impact social, direct ou indirect, une utilité clairement mesurable et motivante, répondre à un défi de société à petite ou à grande échelle, être source, levier ou moteur de changement pour la société…
  • ne pas nécessiter de présence physique importante en dehors de la région parisienne (je démarre petit et près de chez moi, même si je suis un adepte du travail à distance et des “conf call”), bref être plutôt localisé près de Paris

Qu’est-ce qu’un projet informatique d’intérêt général ?

Un projet informatique est d’intérêt général si il est porté par un organisme bénéficiant du régime fiscal français du mécénat. Ah, ah… mystère, qu’est-ce que c’est que ce truc ? La loi française d’août 2003 sur le mécénat reste mal connue mais elle représente une source de revenus importante pour les organismes d’intérêt général. Plusieurs types d’organismes répondent à ce critère. Pour faire simple, il peut s’agir d’une association loi 1901 :

  • à but non lucratif : elle ne reverse pas de TVA, ne paye pas d’impôts sur les sociétés, a des administrateurs et un bureau bénévoles et désintéressés, ne vient pas concurrencer des entreprises commerciales ou alors elle le fait à des prix beaucoup plus bas que le marché et principalement pour un public défavorisé et sans “pratiques commerciales” (publicité, …) ; demandez l’avis d’un comptable si besoin
  • et dont l’objet est à caractère philanthropique, éducatif, social, humanitaire, sportif, familial, culturel, artistique, environnemental, culturel, littéraire, scientifique…
  • et dont les activités ne bénéficient pas à un cercle restreint de personnes (contrairement aux syndicats ou aux associations d’anciens élèves d’une école par exemple …)

Au besoin, une association loi 1901 peut être facilement créée pour porter ce projet (statuts et déclaration en préfecture) et réunir les conditions de l’intérêt général. Il n’y a pas de condition d’ancienneté ni de taille de l’association. Il n’y a pas non plus forcément besoin d’obtenir un agrément administratif (comme ce serait le cas pour les associations “reconnues d’utilité publique”, ce qui est une reconnaissance très difficile à obtenir de nos jours).

Pour en savoir plus sur la notion d’intérêt général, je vous invite à consulter le site mécénat du ministère de la culture ainsi que les explications de l’Association pour le Développement du Mécénat Industriel et Commercial (ADMICAL).

Comment je peux aider, en pratique ?

Si vous consacrez déjà du temps à votre projet, je peux donc démultiplier cet effort.

Exemple: avec 4 autres bénévoles, vous consacrez au moins, chacun, une journée par semaine à votre projet (soit un équivalent temps plein, 5 jours de travail par semaine), alors je peux vous fournir, en complément, l’équivalent de 2 ingénieurs à temps plein (10 jours de travail par semaine), voire plus si votre projet est très simple à gérer.

Cette aide prendra la forme de:

  • un accompagnement permanent par mon entreprise : au moins une demi-journée d’assistance et de conseil par semaine, en fonction du volume de votre projet ; plus un service de représentation et de suivi de votre projet auprès des entreprises mécènes,
  • des interventions individuelles d’un grand nombre (50, 100, 200…?) de professionnels de l’informatique, ingénieurs, techniciens ou consultants, pour des durées variables et parfois courtes (par exemple une semaine), sur leur temps de travail,
  • la possibilité de renforcer votre équipe bénévole par les contributions ultérieures de certains de ces intervenants sur leur temps libre (constitution éventuelle d’une communauté à la mode open source si votre projet s’y prête)
  • l’accès à un système d’information sécurisé sur le Web pour gérer votre projet, vos intervenants, vos relations avec les mécènes et automatiser la gestion de toute la paperasse administrative qui va avec (contrats, convention de mécénat, reçus fiscaux, …)

Comment ça marche ?

Je créé actuellement une entreprise à vocation sociale dont l’objectif est de fournir aux innovateurs sociaux les mêmes moyens informatiques que ceux dont disposent les entreprises les plus modernes. Mon activité s’appuie sur le mécénat de sociétés de services en informatique (SSII) qui s’engagent dans des démarches de “développement durable” (ou, plus exactement, de “responsabilité sociale de l’entreprise”). Elles souhaitent faire du mécénat de compétences en informatique par mon intermédiaire : faire don du temps de travail de leurs ingénieurs et consultants sous la forme d’une prestation de service gratuite gérée via le Web. J’appelle ça “faire du wecena” (Wecena, c’est le nom de ma boîte !).

Le financement de cette aide est indirectement assuré à 100% par l’Etat français, grâce à la loi sur le mécénat des entreprises. En effet, l’Etat accorde une réduction d’impôts importante à toute entreprise qui décide d’aider concrètement un organisme d’intérêt général (don d’argent, don en nature, don de compétences et temps de travail…). Les SSII mécènes que je rencontre sont prêtes à se lancer dans l’aventure en proposant à leurs ingénieurs de faire avancer votre projet pendant ces périodes de temps que l’on appelle l’”inter-contrat” (ou intercontrat ou “période de stand-by” ou …) : il s’agit de ces périodes de quelques jours à quelques mois qui commencent lorsque l’ingénieur termine un projet pour un client et n’est pas encore affecté à un autre projet pour un nouveau client.

Cela impose une contrainte importante dans la gestion de votre projet: les ingénieurs réalisant la prestation de service vont se relayer à un rythme très rapide, certains ne seront présents que 48H tandis que d’autres seront disponibles 2 ou 3 mois dans l’année. La durée moyenne d’intervention individuelle se situe quelque part entre une semaine et un mois (selon le métier de l’intervenant et l’état du marché de l’informatique, et aussi selon la politique du mécène). C’est le rôle de mon entreprise que de vous aider à gérer cette contrainte. Notez que cette contrainte a également quelques avantages : si votre projet est suffisament simple et “découpable” en petites tâches (à l’aide de méthodes et d’outils de gestion adaptées, que je vous fournis), vous aurez ainsi l’occasion de proposer votre cause à une multitude d’intervenants que vous pourrez recruter en autant de bénévoles potentiels une fois leur mission de wecena terminée. C’est par exemple le cas de projets portant sur de l’initiation à l’informatique, de l’animation d’atelier informatique auprès de personnes défavorisées, d’interventions multiples d’installation de PC ou de réseau local… Pour des projets plus complexes (développement, conseil, …), votre implication est plus importante et le wecena ne peut pas représenter plus de 2 fois le temps que vous y consacrez déjà.

Quelques exemples de projet

Pour vous aider à vous faire une idée du type de projet qui peuvent bénéficier du wecena, voici quelques exemples de projets que j’ai déjà présenté à des mécènes :

  • conception et réalisation d’un logiciel innovant pour faciliter l’utilisation du clavier et de la souris par des personnes ayant un handicap moteur
  • amélioration de l’infrastructure informatique d’une ONG travaillant dans la lutte contre l’exclusion: remplacement d’un parc de postes de travail, interventions d’administration système sur des serveurs de fichiers et d’application, …
  • déploiement d’un progiciel de reporting financier sur des prestations de services en mode projet pour une association recevant d’importantes subventions publiques
  • refonte d’applicatifs Web pour la gestion documentaire, la gestion des relations et contacts et la gestion des adhésions pour une association Internet dans le domaine de la famille et de la protection de l’enfance
  • création d’un blog par un écrivain public d’une ONG franco-africaine pour sensibiliser des étudiants français au problématiques du développement Nord-Sud
  • assistance à la webisation d’un système de gestion d’établissements de santé pour une association du secteur sanitaire et social
  • initiations informatiques et formation aux logiciels internes pour des bénévoles retraités d’une association humanitaire

Ce ne sont que quelques exemples pour vous donner le ton. Aucun de ces projets n’a encore démarré.

Avertissement

Mon entreprise en est encore à une phase de démarrage et d’expérimentation. Je ne peux actuellement vous garantir ni que votre projet en particulier sera sélectionné par un mécène (les projets les plus solides et les plus ambitieux auront plus de chances bien entendu) ni même de pouvoir démarrer mon accompagnement tout de suite. En effet, l’aide que je peux vous apporter est en soi un projet (créer une entreprise…) : j’y crois énormément puisque j’ai quitté mon employeur précédent pour me lancer dans cette aventure, et j’y consacre tout mon temps et mes compétences. Mais, ceci dit, démarrer ce genre d’entreprise sociale innovante prend du temps et représente aussi une part de risque, d’incertitude, bref d’aventure… Le premier projet que j’accompagnerai pourrait démarrer fin 2008 (si les étoiles s’alignent comme prévu) ou au plus tard début 2009 (si j’ai moins de chance). Les mécènes que je rencontre sont déjà sur le pied de guerre et ont déjà commencé à examiner les projets informatiques que je leur présente. Certains ont déjà exprimé leur préférence et se mettent en ordre de bataille… En croisant les doigts, j’espère qu’un premier projet pourrait démarrer peu après la rentrée scolaire 2008.

Pour participer à l’aventure…

Vous connaissez une équipe qui porte un projet informatique d’intérêt général et a besoin de temps d’informaticiens pour aller plus loin et plus vite ? Faites-lui suivre l’adresse de cet article !

Votre projet répond aux conditions présentées ci-dessus ?  Pour vous en assurer, posez la question via un commentaire ci-dessous ou contactez-moi directement par email à l’adresse suivante: projets (chez) wecena (point) com ou bien encore à mon adresse de blogueur: sig (chez) akasig (point) org. Le site Web de mon entreprise ne devrait pas ouvrir ses portes avant le démarrage du premier projet. En attendant, c’est ici que ça se passe. Vous avez des conseils à me donner, des avis ou des contacts à partager ou des suggestions à faire ? Ils seront bienvenus: je vous invite également à utiliser la fonction commentaires de ce blog.

eXtreme Consulting?

Friday, June 22nd, 2007

Can agile methods such as eXtreme Programming (XP) be applied to consulting activities? What could eXtreme Consulting (XC) mean? Do you need to analyze the whole big picture before starting the delivery of good recommendations?

In XP iterations, users tell user stories which are prioritized and then transformed by rotating pairs of programmers into tested features. These features enable new uses of technology.

In XC iterations, I guess there would be decision makers telling decision making stories. These stories would be prioritized and then transformed by rotating pairs of consultants into argued and accepted recommendations. These recommendations would enable new decisions.

What about the agility of decision makers themselves, people who are to lead changes in their scope of responsibility? Couldn’t they follow similar methods and benefit from eXtreme Change Making (XCM)? In XCM iterations, there would be change leaders telling change leadership stories. These stories would be prioritized and then transformed by rotating pairs of change makers into tested change commitments from stakeholders in the organization. These commitments would enable changes in the organization, its rules and processes.

Had you ever heard of XC or XCM before reading this? What do you think? Why would such things be of any interest?

Missions solidaires pour prestas en intercontrat

Friday, February 23rd, 2007

Christian, Bader, Jef et Jjay m’ont donné quelques pistes pour améliorer mon idée: comment convaincre des sociétés informatiques de s’investir dans des projets technologiques à vocation solidaire? Merci à tous les 4!
Un gros risque, c’est que ce genre de choses “terminent à la comm’” comme l’indique Christian. Les SSII n’ont probablement “aucune velléité de changer le monde”, en tout cas, ce n’est pas leur vocation. Leur préoccupation évidente semble être “le profit court terme”. Mais pourquoi les SSII n’emploient-elles pas leurs prestataires en inter-contrat à des projets profitables pour elles à plus long terme (projets internes, contribution open source, …) plutôt que de les laisser moisir dans un coin le temps qu’un commercial arrive à les recaser chez un client? D’une boîte à l’autre et d’une personne à l’autre, l’inter-contrat est vécu plus ou moins bien, avec des situations parfois cocasses. En tout cas, l’intercontrat est une source de problèmes pour les SSII et pour leurs employés.

D’un autre côté, il y a peut-être des leviers accessibles pour faire changer cette situation et, du même coup, répondre aux besoins technologiques des innovateurs sociaux.

La notion d’entrepreuriat social, ou d’ethique est très à la mode chez toutes les entreprises qui ont une médiocre image de ce côté là (ça inclue banques et SSII amha).

Que faire? Voici vos suggestions:

faire que les CLIENTS des SSII soient attentifs à ces démarches (dans leur processus de décision ), et comme par hasard tout se débloque

[Peut-être créer des] jeux-projets-concours [:] sélection des meilleurs projets et financement + aide logistique, ça peut marcher.

[De toute façon,] les idées ne peuvent pas venir de l’intérieur [et il faut que la solution permette d'] identifier une retombée financière à quelques mois

Ce n’est pas les SSII qu’il faut convaincre mais d’abord ceux qui travaille dans ces entreprises (de préférence d’une taille respectable à mon avis). S’ils sont motivés ils peuvent faire bouger leur management et toi tu peux les aider à trouver les arguments pour cela.

J’ai envie d’extraire de ces suggestions quelques éléments pour un cahier des charges : la solution doit…

  • apporter une carotte économique pour la SSII, du profit à court terme, peut-être en impliquant certains clients
  • s’appuyer à fond sur la motivation des employés, exploiter celle-ci par des formes d’animation adéquates
  • être économique viable (entreprise sociale, donc entreprise également)

Et si on achetait les prestataires en inter-contrats à leur SSII à un pourcentage symbolique de leur tarif journalier habituel? Cela fournirait l’incitation économique à leur SSII: “Du moment que je sais que je peux disposer de cet intercontrat dès que je le veux pour le mettre chez en client, pourquoi ne pas le vendre à 1% de son prix habituel à un client ‘entreprise sociale’. Si, en plus, ça redore un peu l’image de marque de la boîte et que ça motive certains employés, c’est ça de gagné en plus!”?

Et si ce montant symbolique était réuni par les employés motivés pour participer à l’opération et changer le monde à leur échelle? Pour 10 à 20 employés en mission (selon les périodes et les sociétés), il y en a, disons, 1 en intercontrat. Avec un abonnement/cotisation de quelques dizaines ou centaines d’euros par an et par personne, on réunit le montant nécessaire pour financer une mission solidaire. “Aujourd’hui, je suis chez un client. Mais demain, ça pourrait être moi en intercontrat. Alors, comme j’aimerais bien que certains de mes collègues et moi puissions avoir un véritable impact sur l’environnement/les plus pauvres/la démocratie/le développement des pays du Sud/la priorité de mon choix grâce à ce que l’on sait faire le mieux (la techno), j’achète avec eux le droit de participer à une telle mission lors de mon prochain intercontrat”.

Cette solution consisterait donc à créer un fournisseur de missions solidaires pour prestataires en intercontrat. Les clients sont des prestas qui veulent profiter d’un futur intercontrat pour essayer de changer le monde à leur échelle (plutôt que de se faire chier à éviter les patates et à traîner dans l’agence ou au siège). Les produits sont des missions à forte qualité sociale/environnementale pilotées par des pros du secteur, des gens de terrain qui peuvent vite faire sentir au presta les problèmes sociaux/environnementaux ou autres à traiter. Les autres fournisseurs, ce sont des SSII qui voient d’un bon oeil l’idée d’arrondir leurs fins de mois en vendant certains intercontrats sur un second marché, ultra-discount.

Comment répondre aux questions que ce genre de proposition pourrait soulever? Qu’est-ce qui donnerait suffisamment envie et confiance à un presta pour qu’il achète à l’avance, avec des collègues, son droit de participer à une mission technologique solidaire sur le terrain de son choix? Cette idée a sans doute un côté complètement délirant, mais qu’est-ce qu’on pourrait en faire de bien et d’un peu plus près de la réalité? Qu’est-ce que cela vous inspire? A votre tour!

Invention d’un système de coaching automatique sur téléphone mobile

Tuesday, November 1st, 2005

[Ceci est le résumé de l'une de mes réalisations professionnelles. Je m'en sers pour faire ma pub dans l'espoir de séduire de futurs partenaires. Plus d'infos à ce sujet dans le récit de mon parcours professionnel.]

En 2005, le projet de recherche informatique MobiLife, mené conjointement par 22 entreprises et universités européennes, dispose d’un logiciel pour téléphone mobile qui permet à un sportif de visualiser son contexte d’entraînement : rythme cardiaque, lieu, heure… En tant qu’ingénieur de recherche, je suis chargé d’inventer un système exploitant ce type de données pour offrir à l’utilisateur des recommandations personnalisées et dépendant du contexte. Je propose aux partenaires un scénario utilisateur qui est accepté puis j’en supervise l’implémentation. J’implémente une partie du système côté serveur (J2EE) et côté téléphone (J2ME). L’application devient ainsi capable d’apprendre les habitudes d’entraînement du sportif, bonnes ou mauvaises, de prédire ses prochains choix d’exercice, de les comparer à ce que recommenderait un entraîneur expert dans les mêmes conditions et, sur cette base, d’alerter le sportif par des petits clips videos personnalisés sur son téléphone : “Attention, il est tard et après 2 exercices de course sur le tapis roulant, vous avez habituellement tendance à trop forcer sur l’exercice suivant ; vous devriez plutôt passer sur le vélo pour un exercice de difficulté moyenne de 10 minutes“. Le système inventé est transposable dans d’innombrables situations de mobilité : coaching alimentaire, formation continue, gestes pour l’environnement, guides touristiques,… A l’occasion d’une journée portes ouvertes des laboratoires Motorola, j’organise la démonstration de cette application devant 40 journalistes et analystes européens.

Comparator

Sunday, July 24th, 2005

Comparator is a small Plone product I recently hacked for my pleasure. It’s called comparator until it gets a nicer name, if ever. I distribute it here under the GNU General Public License. It allows users to select any existing content type (object class) and to calculate a personnalized comparison of the instances of this class. For example, if you choose to compare “News Items”, then you select the news items properties you want to base your comparison upon (title, creation date, description, …). You give marks to any value of these properties (somewhat a tedious process at the moment but much room for improvement in the future, there). Comparator then let’s you give relative weights to these properties so that the given marks are processed and the compared instances are ranked globally.

It’s a kind of basic block for building a comparison framework, for building Plone applications that compare stuff (any kind of stuff that exists within your portal, including semantically agregated stuff). Let’s say that your Plone portal is full of descriptions of beers (with many details about all kinds of beers). Then adding a comparator to your portal will let your users give weights to every beer property and rank all the beers according to their personal tastes.

Comparator is based on Archetypes and was built from an UML diagram with ArchgenXML. Comparator fits well in my vision of semantic agregation. I hope you can see how. Comments welcome !

From OWL to Plone

Thursday, April 28th, 2005

I found a working path to transform an OWL ontology into a working Plone content-type. Here is my recipe :

  1. Choose any existing OWL ontology
  2. With Protege equipped with its OWL plugin, create a new project from your OWL file.
  3. Still within Protege, with the help of its UML plugin, convert your OWL-Protege project into a UML classes project. You get an XMI file.
  4. Load this XMI file into an UML project with Poseidon. Save this project under the .zuml Poseidon format.
  5. From poseidon, export your classes a new xmi file. It will be Plone-friendly.
  6. With a text editor, delete some accentuated characters that Poseidon might have added to your file (for example, the Frenchy Poseidon adds a badly accentuated “Modele sans titre” attribute into your XMI) because the next step won’t appreciate them
  7. python Archgenxml.py -o YourProduct yourprojectfile.xmi turns your XMI file into a valid Plone product. Requires Plone and Archetypes (see doc) latest stable version plus ArchgenXML head from the subversion repository.
  8. Launch your Plone instance and install YourProduct as a new product from your Plone control panel. Enjoy YourProduct !
  9. eventually populate it with an appropriate marshaller.

Now you are not far from using Plone as a semantic aggregator.

Web scraping with Python (part II)

Friday, March 11th, 2005

The first part of this article dealt with retrieving HTML pages from the web with the help of a mechanize-propelled web crawler. Now your HTML pieces are safely saved locally on your hard drive and you want to extract structured data from them. This is part 2, HTML parsing with Python. For this task, I adopted a slightly more imaginative approach than for my crawling hacks. I designed a data extraction technology based on HTML templates. Maybe this could be called “reverse-templating” (or something like template-based reverse-web-engineering).

You may be used with HTML templates for producing HTML pages. An HTML template plus structured data can be transformed into a set of HTML pages with the help of a proper templating engine. One famous technology for HTML templating is called Zope Page Templates (because this kind of templates is used within the Zope application server). ZPTs use a special set of additional HTML tags and attributes referred to by the “tal:” namespace. One advantage of ZPT (over competing technologies) is that ZPT are nicely rendered in WYSIWYG HTML editors. Thus web designers produce HTML mockups of the screens to be generated by the application. Web developpers insert tal: attributes into these HTML mockups so that the templating engine will know which parts of the HTML template have to be replaced by which pieces of data (usually pumped from a database). As an example, web designers will say <title>Camcorder XYZ</title> then web developpers will modify this into <title tal:content=”camcorder_name”>Camcorder XYZ</title> and the templating engine will further produce a <title>Camcorder Canon MV6iMC</title> when it processes the “MV6iMC” record in your database (it replaces the content of the title element with the value of the camcorder_name variable as it is retrieved from the current database record). This technology is used to merge structured data with HTML templates in order to produce Web pages.

I took inspiration from this technology to design parsing templates. The idea here is to reverse the use of HTML templates. In the parsing context, HTML templates are still produced by web developpers but the templating engine is replaced by a parsing engine (known as web_parser.py, see below for the code of this engine). This engine takes HTML pages (the ones you previously crawled and retrieved) plus ZPT-like HTML templates as input. It then outputs structured data. First your crawler saved <title>Camcorder Canon MV6iMC</title>. Then you wrote <title tal:content=”camcorder_name”>Camcorder XYZ</title> into a template file. Eventually the engine will output camcorder_name = “Camcorder Canon MV6iMC”.

In order to trigger the engine, you just have to write a small launch script that defines several setup variables such as :

  • the URL of your template file,
  • the list of URLs of the HTML files to be parsed,
  • whether you would like or not to pre-process these files with an HTML tidying library (this is useful when the engine complains about badly formed HTML),
  • an arbitrary keyword defining the domain of your parsing operation (may be the name of the web site your HTML files come from),
  • the charset these HTML files are made with (no automatic detection at the moment, sorry…)
  • the output format (csv-like file or semantic web document)
  • an optional separator character or string if ever you chose the csv-like output format

The easiest way to go is to copy and modify my example launch script (parser_dvspot.py) included in the ZIP distribution of this web_parser.

Let’s summarize the main steps to go through :

  1. install utidylib into your python installation
  2. copy and save my modified version of BeautifulSoup into your python libraries directory (usually …/Lib/site-packages)
  3. copy and save my engine (web_parser.py) into your local directory or into you python libraries directory
  4. choose a set of HTML files on your hard drive or directly on a web site,
  5. save one of these files as your template,
  6. edit this template file and insert the required pseudotal attributes (see below for pseudotal instructions, and see the example dvspot template template_dvspot.zpt),
  7. copy and edit my example launch script so that you define the proper setup variables in it (the example parser_dvspot.py contains more detailed instructions than above), save it as my_script.py
  8. launch your script with a python my_script.py > output_file.cowl (or python my_script.py > output_file.cowl)
  9. enjoy yourself and your fresh output_file.owl or output_file.csv (import it within Excel)
  10. give me some feedback about your reverse-templating experience (preferably as a comment on this blog)

This is just my first attempt at building such an engine and I don’t want to make confusion between real (and mature) tal attributes and my pseudo-tal instructions. So I adopted pseudotal as my main namespace. In some future, when the specification of these reverse-templating instructions are somewhat more stabilized (and if ever the “tal” guys agree), I might adopt tal as the namespace. Please also note that the engine is somewhat badly written : the code and internal is rather clumsy. There is much room for future improvement and refactoring.

The current version of this reverse-templating engine now supports the following template attributes/instructions (see source code for further updates and documentation) :

  • pseudotal:content gives the name of the variable that will contain the content of the current HTML element
  • pseudotal:replace gives the name of the variable that will contain the entire current HTML element
  • (NOT SUPPORTED YET) pseudotal:attrs gives the name of the variable that will contain the (specified?) attribute(s ?) of the current HTML element
  • pseudotal:condition is a list of arguments ; gives the condition(s) that has(ve) to be verified so that the parser is sure that current HTML element is the one looked after. This condition is constructed as a list after BeautifulSoup fetch arguments : a python dictionary giving detailed conditions on the HTML attributes of the current HTML element, some content to be found in the current HTML element, the scope of research for the current HTML element (recursive search or not)
  • pseudotal:from_anchor gives the name of the pseudotal:anchor that is used in order to build the relative path that leads to the current HTML element ; when no from_anchor is specified, the path used to position the current HTML element is calculted from the root of the HTML file
  • pseudotal:anchor specifies a name for the current HTML element ; this element can be used by a pseudotal:from_anchor tag as the starting point for building the path to the element specified by pseudotal:from_anchor ; usually used in conjunction with a pseudotal:condition ; the default anchor is the root of the HTML file.
  • pseudotal:option describes some optional behavior of the HTML parser ; is a list of constants ; contains NOTMANDATORY if the parser should not raise an error when the current element is not found (it does as default) ; contains FULL_CONTENT when data looked after is the whole content of the current HTML element (default is the last part of the content of the current HTML element, i.e. either the last HTML tags or the last string included in the current element)
  • pseudotal:is_id_part a special ‘id’ variable is automatically built for every parsed resource ; this id variable is made of several parts that are concatenated ; this pseudotal:is_id_part gives the index the current variable will be used at for building the id of the current resource ; usually used in conjunction with pseudotal:content, pseudotal:replace or pseudotal:attrs
  • (NOT SUPPORTED YET) pseudotal:repeat specifies the scope of the HTML tree that describes ONE resource (useful when several resources are described in one given HTML file such as in a list of items) ; the value of this tag gives the name of a class that will instantiate the parsed resource scope plus the name of a list containing all the parsed resource

The current version of the engine can output structured data either as a CSV-like output (tab-delimited for example) or as an RDF/OWL document (of Semantic-Web fame). Both formats can easily be imported and further processed with Excel. The RDF/OWL format gives you the ability to process it with all the powerful tools that are emerging along the Semantic Web effort. If you feel adventurous, you may thus import your RDF/OWL file into Stanford’s Protege semantic modeling tool (or into Eclipse with its SWEDE plugin) and further process your data with the help of a SWRL rules-based inference engine. The future Semantic Web Rules Language will help at further processing this output so that you can powerfully compare RDF data coming from distinct sources (web sites). In order to be more productive in terms of fancy buzz-words, let’s say that this reverse-templating technology is some sort of a web semantizer. It produces semantically-rich data out of flat web pages.

The current version of the engine makes an extensive use of BeautifulSoup. Maybe it should have been based on a more XMLish approach instead (using XML pathes ?). But it would have implied that the HTML templates and HTML files to be processed should then have been turned into XHTML. The problem is that I would then have relied on utidylib but this library breaks too much some mal-formed HTML pages so that they are not valuable anymore.

Current known limitation : there is currently no way to properly handle some situations where you need to make the difference between two similar anchors. In some cases, two HTML elements that you want to use as distinct anchors have in fact exactly the same attributes and content. This is not a problem as long as these two anchors are always positioned at the same place in all the HTML page that you will parse. But, as soon as one of the anchors is not mandatory or it is located after a non mandatory element, the engine can get lost and either confuse the two anchors or complain that one is missing. At the moment, I don’t know how to handle this kind of situation. Example : long lists of specifications with similar names where some specifications are optional (see canon camcorders as an example : difference between lcd number of pixels and viewfinder number of pixels). The worst case scenario would be when there is a flat list of HTML paragraphs. The engine will try to identify these risks and should output some warnings in this kind of situations.


Here are the contents of the ZIP distribution of this project (distributed under the General Public License) :

  • web_parser.py : this is the web parser engine.
  • parser_dvspot.py : this is an example launch script to be used if you want to parser HTML files coming from the dvspot.com web site.
  • template_dvspot.zpt : this is the example template file corresponding to the excellent dvspot.com site
  • BeautifulSoup.py : this is MY version of BeautifulSoup. Indeed, I had to modify Leonard Richardson’s official one and I couldn’t obtain any answer from him at the moment regarding my suggested modifications. I hope he will soon answer me and maybe include my modifications in the official version or help me overcoming my temptation to fork. My modifications are based on the official 1.2 release of beautifulsoup : I added “center” as a nestable tag and added the ability to match the content of an element with the help of wildcards. You should save this BeautifulSoup.py file into the “Lib\site-packages” folder of your python installation.
  • README.html is the file you are currently reading, also published on my blog.

Mesurer la qualité du Web tout en surfant

Thursday, March 3rd, 2005

La conformité aux standards ouverts définis dans le cadre du W3C est un élément important dans la qualité du Web tel qu’on le connaît. Pour ceux d’entre vous qui sont développeurs Web et souhaitent vérifier la conformité des pages qu’ils consultent, rien de plus simple : avec l’extension HTML Validator de Firefox, une petite icône en bas de Firefox vous indique si la page pose ou non problème. Mieux encore, l’extension vous indique comment corriger le problème si vous pouvez modifier cette page !

Web scraping with python (part 1 : crawling)

Wednesday, December 29th, 2004

Example One : I am looking for my next job. So I subscribe to many job sites in order to receive notifications by email of new job ads (example = Monster…). But I’d rather check these in my RSS aggregator instead of my mailbox. Or in some sort of aggregating Web platform. Thus, I would be able to do many filtering/sorting/ranking/comparison operations in order to navigate through these numerous job ads.

Example Two : I want to buy a digital camcorder. So I want to compare the available models. Such a comparison implies that I rank the most common models according to their characteristics. Unfortunately, the many sites providing reviews or comparisons of camcorders are not often comprehensive and they don’t offer me the capability of comparing them with respect to my way of ranking and weighting the camcorder features (example = dvspot). So I would prefer pumping all the technical stuff from these sites and manipulate this data locally on my computer. Unfortunately, this data is merged within HTML. And it may be complex to extract it automatically from all the presentation code.

These are common situations : interesting data spread all over the web and merged in HTML presentation code. How to consolidate this data so that you can analyze and process it with your own tools ? In some near future, I expect this data will be published so that it is directly processable by computers (this is what the Semantic Web is intending to do). For now, I was used to do it with Excel (importing Web data, then cleaning it and the like) and I must admit that Excel is fairly good at it. But I’d like some more automation for this process. I’d like some more scripting for this operation so that I don’t end with inventing complex Excel macros or formulas just to automate Web site crawling, HTML extraction and data cleaning. With such an itch to scratch, I tried to address this problem with python.

This series of messages introduces my current hacks that automate web sites crawling and data extraction from HTML pages. The current output of these scripts is a bunch of CSV files that can be further processed … in Excel. I wish I would output RDF instead of CSV. So there remains much room for further improvement (see RDF Web Scraper for a similar but approach). Anyway… Here is part One : how to crawl complex web sites with Python ?. The next part will deal with data extraction from the retrieved web pages, involving much HTML cleansing and parsing.

My crawlers are fully based on the John L. Lee’s mechanize framework for python. There are other tools available in Python. And several other approaches are available when you want to deal with automating the crawling of web sites. Note that you can also try to scrape the screens of legacy terminal-based applications with the help of python (this is called “screen scraping”). Some approaches of web crawling automation rely on recording the behaviour of a user equipped with a web browser and then reproduce this same behaviour in an automated session. That is an attractive and futuristic approach. But this implies that you find a way to guess what the intended automatic crawling behaviour will be from a simple example. In other words, with this approach, you have either to ask the user to click on every web link (all the job postings…) and this gives no value to the automation of the task. Or your system “guesses” what automatic behaviour is expected just by recording a sample of what a human agent would do. Too complex… So I preferred a more down-to-earth solution implying that you write simple crawling scripts “by hand”. (You may still be interested in automatically record user sessions in order to be more productive when producing your crawling scripts.) As a summary : my approach is fully based on mechanize so you may consider the following code as example of uses of mechanize in “real-world” situations.

For purpose of clarity, let’s first focus on the code part that is specific to your crawling session (to the site you want to crawl) . Let’s take the example of the dvspot.com site which you may try to crawl in order to download detailed description of camcorders :

    # Go to home page
    #
    b.open("http://www.dvspot.com/reviews/cameraList.php?listall=1&start=0")
    #
    # Navigate through the paginated list of cameras
    #
    next_page = 0
    while next_page == 0:
     #
     # Display and save details of every listed item
     #
     url = b.response.url
     next_element = 0
     while next_element >= 0:
      try:
       b.follow_link(url_regex=re.compile(r"cameraDetail"), nr=next_element)
       next_element = next_element + 1
       print save_response(b,"dvspot_camera_"+str(next_element))
       # go back to home page
       b.open(url)
       # if you crawled too many items, stop crawling
       if next_element*next_page > MAX_NR_OF_ITEMS_PER_SESSION:
          next_element = -1
          next_page = -1
      except LinkNotFoundError:
       # You certainly reached the last item in this page
       next_element = -1
    #
     try:
      b.open(url)
      b.follow_link(text_regex=re.compile(r"Next Page"), nr=0)
      print "processing Next Page"
     except LinkNotFoundError:
      # You reached the last page of the listing of items
      next_page = -1

You noticed that the structure of this code (conditional loops) depends on the organization of the site you are crawling (paginated results, …). You also have to specify the rule that will trigger “clicks” from your crawler. In the above example, your script first follows every link containing “cameraDetail” in its URL (url_regex). Then it follows every link containing “Next Page” in the hyperlink text (text_regex).

This kind of script is usually easy to design and write but it can become complex when the web site is improperly designed. There are two sources of difficulties. The first one is bad HTML. Bad HTML may crash the mechanize framework. This is the reason why you often have to pre-process the HTML either with the help of a HTML tidying library or with simple but string substitutions when your tidy library breaks the HTML too much (this may be the case when the web designer improperly decided to used nested HTML forms). Designing the proper HTML pre-processor for the Web site you want to crawl can be tricky since you may have to dive into the faulty HTML and the mechanize error tracebacks in order to identify the HTML mistakes and workaround them. I hope that future versions of mechanize would implement more robust HTML parsing capabilities. The ideal solution would be to integrate the Mozilla HTML parsing component but I guess this will be some hard work to do. Let’s cross our fingers.

Here are useful examples of pre-processors (as introduced by some other mechanize users and developpers) :

class TidyProcessor(BaseProcessor):
      def http_response(self, request, response):
          options = dict(output_xhtml=1,
                   add_xml_decl=1,
                   indent=1,
                   output_encoding='utf8',
                   input_encoding='latin1',
                   force_output=1
                   )
          r = tidy.parseString(response.read(), **options)
          return FakeResponse(response, str(r))
      https_response = http_response
#
class MyProcessor(BaseProcessor):
      def http_response(self, request, response):
          r = response.read()
          r = r.replace('"image""','"image"')
          r = r.replace('"','"')
          return FakeResponse(response, r)
      https_response = http_response
#
# Open a browser and optionally choose a customized HTML pre-processor
b = Browser()
b.add_handler(MyProcessor())

The second source of difficulties comes from non-RESTful sites. As an example the APEC site (a French Monster-like job site) is based on a proprietary web framework that implies that you cannot rely on links URLs to automate your browsing session. It took me some time to understand that, once loggin in, every time you click on a link, you are presented with a new frameset referring to the URLs that contain the interesting data you are looking for. And these URLs seem to be dependent on your session. No permalink, if you prefer. This makes the crawling process even more tricky. In order to deal with this source of difficulty when you write your crawling script, you have to open both your favorite text editor (to write the script) and your favorite web browser (Firefox of course !). One key knowledge is to know mechanize “find_link” capabilities. These capabilities are documented in _mechanize.py source code, in the find_link method doc strings. They are the arguments you will provide to b.follow_link in order to automate your crawler “clicks”. For more convenience, let me reproduce them here :

  • text: link text between link tags: <a href=”blah”>this bit</a> (as
    returned by pullparser.get_compressed_text(), ie. without tags but
    with opening tags “textified” as per the pullparser docs) must compare
    equal to this argument, if supplied
  • text_regex: link text between tag (as defined above) must match the
    regular expression object passed as this argument, if supplied
    name, name_regex: as for text and text_regex, but matched against the
    name HTML attribute of the link tag
  • url, url_regex: as for text and text_regex, but matched against the
    URL of the link tag (note this matches against Link.url, which is a
    relative or absolute URL according to how it was written in the HTML)
  • tag: element name of opening tag, eg. “a”
    predicate: a function taking a Link object as its single argument,
    returning a boolean result, indicating whether the links
  • nr: matches the nth link that matches all other criteria (default 0)

Links include anchors (a), image maps (area), and frames (frame,iframe).

Enough with explanations. Now comes the full code in order to automatically download camcorders descriptions from dvspot.com. I distribute this code here under the GPL (legally speaking, I don’t own the copyleft of this entire code since it is based on several snippets I gathered from the web and wwwsearch mailing list). Anyway, please copy-paste-taste !

from mechanize import Browser,LinkNotFoundError
from ClientCookie import BaseProcessor
from StringIO import StringIO
# import tidy
#
import sys
import re
from time import gmtime, strftime
#
# The following two line is specific to the site you want to crawl
# it provides some capabilities to your crawler for it to be able
# to understand the meaning of the data it is crawling ;
# as an example for knowing the age of the crawled resource
#
from datetime import date
# from my_parser import parsed_resource
#
"""
 Let's declare some customized pre-processors.
 These are useful when the HTML you are crawling through is not clean enough for mechanize.
 When you crawl through bad HTML, mechanize often raises errors.
 So either you tidy it with a strict tidy module (see TidyProcessor)
 or you tidy some errors you identified "by hand" (see MyProcessor).
 Note that because the tidy module is quite strict on HTML, it may change the whole
 structure of the page you are dealing with. As an example, in bad HTML, you may encounter
 nested forms or forms nested in tables or tables nested in forms. Tidying them may produce
 unintended results such as closing the form too early or making it empty. This is the reason
 you may have to use MyProcessor instead of TidyProcessor.
"""
#
class FakeResponse:
      def __init__(self, resp, nudata):
          self._resp = resp
          self._sio = StringIO(nudata)
#
      def __getattr__(self, name):
          try:
              return getattr(self._sio, name)
          except AttributeError:
              return getattr(self._resp, name)
#
class TidyProcessor(BaseProcessor):
      def http_response(self, request, response):
          options = dict(output_xhtml=1,
                   add_xml_decl=1,
                   indent=1,
                   output_encoding='utf8',
                   input_encoding='latin1',
                   force_output=1
                   )
          r = tidy.parseString(response.read(), **options)
          return FakeResponse(response, str(r))
      https_response = http_response
#
class MyProcessor(BaseProcessor):
      def http_response(self, request, response):
          r = response.read()
          r = r.replace('"image""','"image"')
          r = r.replace('"','"')
          return FakeResponse(response, r)
      https_response = http_response
#
# Open a browser and optionally choose a customized HTML pre-processor
b = Browser()
b.add_handler(MyProcessor())
#
""""
 Let's declare some utility methods that will enhance mechanize browsing capabilities
"""
#
def find(b,searchst):
    b.response.seek(0)
    lr = b.response.read()
    return re.search(searchst, lr, re.I)
#
def save_response(b,kw='file'):
    """Saves last response to timestamped file"""
    name = strftime("%Y%m%d%H%M%S_",gmtime())
    name = name + kw + '.html'
    f = open('./'+name,'w')
    b.response.seek(0)
    f.write(b.response.read())
    f.close
    return "Response saved as %s" % name
#
"""
Hereafter is the only (and somewhat big) script that is specific to the site you want to crawl.
"""
#
def dvspot_crawl():
    """
     Here starts the browsing session.
     For every move, I could have put as a comment an equivalent PBP command line.
     PBP is a nice scripting layer on top of mechanize.
     But it does not allow looping or conditional browsing.
     So I preferred scripting directly with mechanize instead of using PBP
     and then adding an additional layer of scripting on top of it.
    """
#
    MAX_NR_OF_ITEMS_PER_SESSION = 500
    #
    # Go to home page
    #
    b.open("http://www.dvspot.com/reviews/cameraList.php?listall=1&start=0")
    #
    # Navigate through the paginated list of cameras
    #
    next_page = 0
    while next_page == 0:
     #
     # Display and save details of every listed item
     #
     url = b.response.url
     next_element = 0
     while next_element >= 0:
      try:
       b.follow_link(url_regex=re.compile(r"cameraDetail"), nr=next_element)
       next_element = next_element + 1
       print save_response(b,"dvspot_camera_"+str(next_element))
       b.open(url)
       # if you crawled too many items, stop crawling
       if next_element*next_page > MAX_NR_OF_ITEMS_PER_SESSION:
          next_element = -1
          next_page = -1
      except LinkNotFoundError:
       # You reached the last item in this page
       next_element = -1
    #
     try:
      b.open(url)
      b.follow_link(text_regex=re.compile(r"Next Page"), nr=0)
      print "processing Next Page"
     except LinkNotFoundError:
      # You reached the last page of the listing of items
      next_page = -1
    #
    return
#
#
#
if __name__ == '__main__':
#
    """ Note that you may need to specify your proxy first.
    On windows, you do :
    set HTTP_PROXY=http://proxyname.bigcorp.com:8080
    """
    #
    dvspot_crawl()

In order to run this code, you will have to install mechanize 0.0.8a, pullparser 0.0.5b, clientcookie 0.4.19, clientform 0.0.16 and utidylib. I used Python 2.3.3. Latest clientcookie’s version was to be integrated into Python 2.4 I think. In order to install mechanize, pullparser, clientcookie and clientform, you just have to do the usual way :

python setup.py build
python setup.py install
python setup.py test

Last but not least : you should be aware that you may be breaking some terms of service from the website you are trying to crawl. Thanks to dvspot for providing such valuable camcorders data to us !

Next part will deal with processing the downloaded HTML pages and extract useful data from them.

Web scraping with Python

Friday, September 3rd, 2004

Here is a set of resources for scraping the web with the help of Python. The best solution seems to be Mechanize plus Beautiful Soup.

See also :

Off-topic : proxomitron looks like a nice (python-friendly ?) filtering proxy.