This article is part of the article series "Creating"
<- previous article next article ->

The making of, the Popurls for Pictures: buzziest picsThis is part one of a two part series on how I am going to develop, a like website for the buzziest pics on the net.

As you remember, a few weeks ago I created (now moved to and These sites were fun to make. I love to check them daily and people love them as well!

While I was creating the second site, digpicz, it struck me - why not create a single site similar to popurls which aggregates posts to pictures from many sources?

Let's get hands on it!

picurls - picture buzz, buzziest pics on the net

Technical Design of Picurls

Technically the website is very easy to create. It will use a bunch of Perl programs which periodically check for new posts on various social news and bookmarking sites, insert these posts into the database and create a small picture thumbnails for each post.

This project can now reuse components from diggpics and redditmedia. Digpicz and reddit media each had their own post/story extractor which scraped the content from these sites.

If you looked closely at these scripts, you would notice that a lot of code is almost identical in both of them:

Each site also used the same set of scripts for finding the "best" picture on the website, retrieving it and creating a thumbnail out of this pic. These scripts will also get reused.

The first version of the Picurls website is going to scrape contents from 9 sources:

I really don't want to duplicate the same code over and over again, creating an extractor program for each of the sites. I better write a more generic plugin-based data scraper which can easily be extended and reused (read more about it below). These digg and reddit extractors can now be turned into scraper plugins easily.

The data scraper program will output posts in a human readable format ready for input to a program which inserts the posts into a temporary picture database.

Once the posts are in the database, another program will run and give a few tries to extract a thumbnail for the post. If it succeeds it will move the post from the temporary picture table to real picture table.

The user interface of the site will be done in PHP and will use data from the real picture table. To minimize load on the server, the website pages will be cached. Designing a primitive caching system in PHP is very simple, but there are strong libraries already which do it for us. One of them is Smarty. Smarty is a template engine for PHP. More specifically, it facilitates a manageable way to separate application logic and content from its presentation. Not only that, it can easily be instructed to cache the pages.

Digg pics and redditmedia were completely pre-generated by a Perl program and the web server had to serve just regular HTML files. The sites had less functionality but they handled traffic well. It will be almost the same with picurls, where the Smarty will serve the cached HTML contents and only when a new picture of a new comment is added will the cache be flushed. This way I do not have to worry about server getting too loaded.

Using PHP as the server side language for the user interface of the website will make it a much more lively than redditmedia or digpicz. I want the new site to have comments, most viewed pics, most commented pics, search functionality, voting and more features later.

The first version of picurls will have comments but the other features will come later. Also I want to write it in a manner that the programs can be reused in other projects.

Designing the Generic Plugin-Based Data Scraper

The basic idea of the data scraper is to crawl websites and to extract the posts in a human readable output format. I want it to be easily extensible via plugins and be highly reusable. Also I want the scraper to have basic filtering capabilities to select just the posts which I am interested in.

There are two parts to the scraper - the scraper library and the scraper program which uses the library and makes it easier to scrape many sites at once.

The scraper library consists of the base class 'sites::scraper' and plugins for many various websites. For example, Digg's scraper plugin is 'sites::digg' (it inherits from sites::scraper).

The constructor of each plugin takes 4 optional arguments - pages, vars, patterns or pattern_file.

  • pages - integer, specifies how many pages to scrape in a single run,
  • vars - hashref, specifies parameters for the plugin,
  • patterns - hashref, specifies string regex patterns for filtering posts,
  • pattern_file - string, path to file containing patterns for filtering posts.

Here is a Perl one-liner example of scraper library usage (without scraper program). This example scrapes 2 most popular pages of stories from Digg's programming section, filtering just the posts matching 'php' (case insensitive):

perl -Msites::digg -we '$digg = sites::digg->new(pages => 2, patterns => { title => [ q/php/ ], desc => [ q/php/ ] }, vars => { popular => 1, topic => q/programming/ }); $digg->scrape_verbose'

In this example we scrape two pages of all popular digg posts (made to front page) in programming category (topic) which have 'php' in either title or description of the post.

Here is the output of the plugin:

comments: 27
container_name: Technology
container_short_name: technology
description: With WordPress 2.3 launching this week, a bunch of themes and plugins needed updating. If you're not that familiar with <strong>PHP</strong>, this might present a slight problem. Not to worry, though - we've collected together 20+ tools for you to discover the secrets of <strong>PHP</strong>.
human_time: 2007-09-26 18:18:02
id: 3587383
score: 921
status: popular
title: The <strong>PHP</strong> Toolbox: 20+ <strong>PHP</strong> Resources
topic_name: Programming
topic_short_name: programming
unix_time: 1190819882
user: ace77
user_profileviews: 17019
user_registrered: 1162332420
site: digg

comments: 171
container_name: Technology
container_short_name: technology
description: "Back in January 2005, I announced on the O'Reilly blog that I was going to completely scrap over 100,000 lines of messy <strong>PHP</strong> code in my existing CD Baby ( website, and rewrite the entire thing in Rails, from scratch."Great article.
human_time: 2007-09-23 06:47:38
id: 3548227
score: 1653
status: popular
title: 7 Reasons I Switched Back to <strong>PHP</strong> After 2 Years on Rails
topic_name: Programming
topic_short_name: programming
unix_time: 1190519258
user: Steaminx
user_profileviews: 14083
user_registrered: 1104849214
site: digg

Each story is represented as a paragraph of key: value pairs. In this case the scraper found 2 posts matching PHP.

Any program taking this output as input is free to choose parts of information they want to use.

It is guaranteed that each plugin produces output with at least 'title', 'url' and 'site' fields.

The date of the post is extracted, if available, is extracted by two fields 'unix_time' and 'human_time'.

In Picurls case, I am interested in 'title', 'url', 'unix_time' and 'site' fields.

To create a plugin, one must override just three methods from the base class:

  • site_name - method should return a unique site id which will be output in each post as 'site' field,
  • get_page_url - given a page number, the method should construct a URL to the page containing posts,
  • get_posts - given the content of the page located at last get_page_url call, the subroutine should return an array of hashrefs containing key => val pairs containing the post information

It's very difficult to document everything the library does. It would take a few pages of documentation to document this simple library. If you are more interested in it, please take a look at the sources.

Take a look at website scraper plugin to see how trivial it is to write a new plugin:
See generic plugin-based scraper ( scraper plugin) (downloaded: 7364 times)

Here is the base class of scraper library
See generic plugin-based scraper (base class) (downloaded: 6269 times)

The scraper program takes a bunch of command line arguments and calls each plugin in turn generating huge amount of output.

The program is called Running it without arguments prints its basic usage:

Usage: ./ <<strong>site</strong>[:<strong>M</strong>][:{<strong>var1=val1; var2=val2 ...</strong>}]> ... [/path/to/pattern_file]
Crawls given sites extracting entries matching optional patterns in pattern_file
Optional argument M specifies how many pages to crawl, default 1
Arguments (variables) for plugins can be passed via an optional { }

The arguments in { } get parsed and then get passed to constructor of site. Also a number of sites can be scraped at once.

For example, running the program with the following arguments:

./ reddit:2:{subreddit=science} stumbleupon:{tag=photography} picurls.txt

Would scrape two pages of and a page of StumbleUpon website tagged 'photography' and use filtering rules in the file 'picurls.txt'.

This is how the output of this program looks:

desc: Morning Glory at rest before another eruption, Yellow Stone National Park.
human_time: 2007-02-14 04:34:41
unix_time: 1171420481
site: stumbleupon

desc: Time for yur Bath
human_time: 2007-10-10 04:34:41
unix_time: 1191980081
site: stumbleupon

human_time: 2007-10-13 15:34:42
id: 2zq0v
score: 4
title: Sharpest image of Pluto ever taken
unix_time: 1192278882
user: clawoo
site: reddit

Here is the program itself:
See generic plugin-based scraper (scraper program) (downloaded: 5263 times)

Here is how the filter file picurls.txt for Picurls looks like:

# match picture urls
url: \.jpg$
url: \.gif$
url: \.png$

# match common patterns describing posts having pictures in them

photos? of
pics? of
images? of
pictures? of
comics? of
charts? of
graphs? of
grapics? of
(this|these|those) photos?
(this|these|those) pics?
(this|these|those) images?
photosets? (on|of)

# match domains containing just pics
url: xkcd\.com
url: flickr\.com
url: photobucket\.com
url: imageshack\.us
url: bestpicever\.com

The format of the file is the following:
[url: |title: |desc: ]regex_pattern

url:, title: and desc: are optional. They specify if the entry on a website should be matched against its url, title or description.

If neither url:, title: and desc: are specified, it defaults to matching pattern against title and description.

Update: I added another format field 'perl:' which allows to write a filter predicate as an anonymous Perl subroutine which gets called on each item scraped. A predicate is a function which returns a true or false for a given input. In our case, if the predicate returns true, the item gets accepted (and printed as output later), if false, then the next predicate (if any) is considered and the same rule applies.

Here is an example of filter file which defines a single predicate, which filters out most of the URLs which point to root location of the site (not likely to contain an interesting picture):

# Discard items which point to index pages
perl: sub {
    use URI;
    my $post = shift;

    my $uri = URI->new($post->{url});
    my $path = $uri->path;

    if (!length $path) { # empty path
        return 0;
    elsif ($path =~ m!^/+$!) { # just a slash '/'
        return 0;
    elsif ($path =~ m!^/(home|index)\.(php|html|htm|aspx?)$!i) { # some index files
        return 0;

    return 1;

And here is the whole scraper package with the scraper library, 9 plugins and the scraper program:

Download Generic Plugin-Based Website Scraper

All the scripts in a single .zip:
Download link: generic plugin-based scraper (whole package)
Downloaded: 772 times

The second part of the article will discuss the database design and the user interface of

Update: Click here to view Part II of the article.

Until next time!

peteris krumins interviewYesterday I was interviewed by Muhammad Saleem who's one of top Digg users. We discussed my programming background, why I created RedditMedia and DigPicz, where do I go from now, and would I ever sell digg pics to Digg!

This is a copy of original interview just in case Muhammad's website ever goes down.

Peter is 22 years old. He is studying physics and loves mathematics but his real passion is computer science. He has recently become famous for developing reddit media and digpicz.

Hi Peter. Thanks for taking out the time to answer some questions.

Let's start with some background.

Sure. I got into programming around 1996. It was hard to get Internet access at that time so I befriended a UNIX sysadmin who was like my teacher at that time. Anyway, from there, he helped me with various computer-related things and introduced me to Linux and programming.

My first experience with programming was creating an IRC client. It was fun exploring this protocol. Since then I have been programming both for fun and work in many various languages. At one point I even wrote an intrusion prevention system when i worked as an white-hat (ethical) hacker.

So how did you end up creating Reddit Media?

I have been an active Reddit user for a while. The content there is unarguably better than other social sites. When they added the programming subreddit, it became my number one source of information. As for why i created Reddit Media, it was mostly so that people would have an easy way to access all the media (pictures and videos) that is submitted to Reddit.

It was so easy to create it, that i just did it.

And how about diggpicz?

Well, as I'm sure you know, Digg users have been asking for a pictures section on the site for a long time. Digg developers just kept saying that they will create the section but haven't done it yet so I decided to do it for digg users. I have had so much programming experiences that this is easy for me and allows me to help such a large community with relatively little effort on my part.

It was just a few hours of work to reuse code that I had written for Reddit media to create Digg Picz.

So where do you go from here? It seems that Digg's official pictures section is coming. Is there any chance that they will seek help from you or would you consider working for/with them?

Well, even when Digg releases their own version, I won't feel that my efforts are wasted. Creating the site was fun and I enjoyed helping thousands of users. Again, the site took only 7 hours to make. That said, I doubt that they will use my site, because I wrote it entirely in Perl and optimized it for a shared hosting server, meaning that all the pages are pre-generated and there is no interaction with database in real time. Digg runs PHP, so it would be a complete re-write. My intention was never build-to-flip.

Working for Digg would be cool, but I'm applying for MIT this november and if I get accepted then I'll put all the effort in studying there and not working. If i don't get in, then I will definitely consider working for Digg.

Now that you have created a version of the site for Reddit and a version for Digg and seen how successful both of them have become, have you thought about releasing a Pligg-like CMS to let people create their own media sites?

Yes, I have thought about it. First I would like to finish (same idea as but focused on pictures), which is written in Perl again. In the upcoming version of you'll be able to choose from a variety of sources, which ones you want to see pictures from.

I'm launching picurls this Sunday!

And you are funding all these projects out of your own pocket?

Yes, I am funding all of this out of my own pocket. Having a sponsor would be cool. A sponsored dedicated Linux server wouldn't hurt. They go for a couple hundred month.

Thanks for your time and I hope somebody will generously gift you a Linux server.

digpicz digg’s missing picture sectionI am completely amazed by the amount of traffic and emails I have received after launching

Digpicz received an incredible amount of 100'000 visitors during the first 20 hours! I launched it at 3am (my local time) and it got submitted to by Ilker Yoldas from TheThinkingBlog soon after, and it made to the front page of Digg two hours later.

According to by midnight it had been visited by 100'727 unique visitors. During two days it has been online (September 2 and September 3) 130'848 uniques have made 265'836 page requests.

digpicz, digg’s missing picture section, statcounter traffic stats

Since I was running it on a shared hosting server ($9.95/monthly at Dreamhost), I had foreseen that there might be problems with dynamically generating page on each request (for example, taking data from the database and creating HTML output using PHP or Perl) and all the pages on the website were simple pre-generated HTML documents. Once a new picture was added only the index.html (default page) was regenerated.

Using this technique helped a shared server with 1000 users (wc -l /etc/passwd) survive!

Soon after got posted to Digg, the story was picked up by TechCrunch, Mashable, FranticIndustries (which was first to blog about it :)) and many other sites.

Here is a picture from Google Analytics web statistics displaying top referrals (September 2 data only):

digpicz, digg’s missing picture section, google analytics referral statistics

It was not that nice with this blog. Since I posted how the site was made and made full source code of website generator available, the blog entry got posted to Digg itself as well.

I use Wordpress blog platform for this blog and it is not really designed with handling slashdot like effects (digg effect, for example) in mind. If no optimizations are done, traffic spike usually just bring the server to down to hell. With all the plugins I use on this blog, Wordpress makes like 40 SQL queries for each served page and then runs the whole content through filters and hooks and whatnot.

I did not expect the site to get Dugg that soon and had not made any optimizations to the blog.

The post made it to Digg's front page in 7 hours and the traffic brought the whole shared hosting server to knees. The blog stopped responding and I had to do something because I was losing many, many potential new readers and subscribers.

I tried installing Wp-Cache 2 plugin on my local development server with an idea to upload it via FTP to shared hosting but the plugin didn't want to work. I have no idea why and I didn't have time to debug the problem. I had to find another solution.

I had set up my blog to use permalink link structure and I remembered that the mod_rewrite directives (ps. here is an excellent mod_rewrite cheat sheet) in .htaccess file, which sets up the link structure, avoided rewriting links if an existing file or directory was requested.

There two lines in the .htaccess generated by Wordpress saved my blog:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

The story Digg linked to was /blog/designing-digg-picture-website/. I quickly created this directory on the server. Now the second RewriteCond rule started working and I instantly noticed the load dropping from 350 to a very low value. Then I created a stripped version of original article and placed it as an index.html file in the newly created directory. The stripped version looked like this. That's it, the load had dropped, the pages were being served, I was happy and readers were happy as well. :)

According to Statcounter my blog received 36'389 unique visitors during these two days:

catonmat statcounter traffic during launching digpicz

And the feed subscriber count (at FeedBurner) increased from 104 to 311 (During September 2):

catonmat feedburner subscribers after launching digpicz

I can't wait to see how many blog subscribers I will have once the data for Tuesday is updated!

I can tell you a little secret now. You know, right? If you don't, then it's a website which aggregates all the best buzz around the net from sources like digg, reddit,, newsvine and many others.

I bought a nicely named domain last week and I am working on a picture aggregation website which finds all the latest posts on all the social websites and displays them on a single page. :)

Expect this website to be out by the end of the week, presumably Sunday. I will probably write a two-part article on how this baby was created, how much time it took me and I will release the full source code as usual.

Until next time!

digpicz: diggs missing picture sectionRemember, I launched Reddit Media: intelligent fun online last week (read how it was made)?

I have been getting emails that it would be a wise idea to launch a Digg media website. Yeah! Why not?
Since Digg already has a video section there is not much point in duplicating it. The new site could just be digg for pictures.

Update 2008.07.30: I received this PDF, which said that I was abusing Digg's trademarks! So I closed the site. You may visit to see how it looked like. I also zipped up the contents of the site and you may download the whole site!

I don't want to use word 'digg' in the domain name because people warned me that the trademark owner could take the domain away from me. I'll just go with a single letter g as "dig" and pictures, to make it shorter picz. So the domain I bought is

Update: The site has been launched, visit digg's missing picture section. Time taken to launch the site: ~7 hours.


Reusing the Reddit Media Generator Suite

I released full source code of the reddit media website (reddit media website generator suite (.zip)). It can now be totally reused with minor modifications to suit the digg for pictures website.

Only the following modifications need to be made:

  • A new extractor (data miner) has to be written which goes through all the stories on digg and finds ones with pic/pics/images/etc. words in titles or descriptions (In reddit generator suite it was the program (in /scripts directory in .zip file)). Digg, as opposite to Reddit, provides a public API to access its stories. I will use this API to go through all the stories and create the initial database of pictures and further monitor digg's front page. This program will be called
  • SQLite database structure has to be changed to include a link to Digg's story, story's description, a link to the user's avatar.
  • The generate_feed function in static HTML page generator ( has to be updated to create a digpicz rss feed.
  • HTML template files in /templates directory (in the .zip file) need to be updated to give the site more digg-like look.

That's it! A few hours of work and we have a digg for pictures website running!

Digpicz Technical Design

Let's create the data miner first. As I mentioned it's called, and it is a Perl script which uses Digg public API.

First, we need to get familiar with Digg API. Skimming over Basic API Concepts page we find just a few imporant points:

Next, to make our data miner get the stories, let's look at Summary of API Features. It mentions List Stories endpoint which "Fetches a list of stories from Digg." This is exactly what we want!

We are interested only in stories which made it to the front page, the API documentation tells us we should issue a GET /stories/popular request to

I typed the following address in my web browser and got a nice XML response with 10 latest stories:

The documentation also lists count and offset arguments which control number of stories to retrieve and offset in complete story list.

So the general algorithm is clear, start at offset=0, loop until we go through all the stories, parse each bucket of stories and extract stories with pics in them.

We want to use the simplest Perl's library possible to parse XML. There is a great one from CPAN which is perfect for this job. It's called XML::Simple. It provides an XMLin function which given an XML string returns a reference to a parsed hash data structure. Easy as 3.141592!

This script prints out picture stories which made it to the front page in human readable format. Each story is printed as a paragraph:

title: story title
type: story type
desc: story description
url: story url
digg_url: url to original story on digg
category: digg category of the story
short_category: short digg cateogry name
user: name of the user who posted the story
user_pic: url to user pic
date: date story appeared on digg YYYY-MM-DD HH:MM:SS
<new line>

The script has one constant ITEMS_PER_REQUEST which defined how many stories (items) to get per API request. Currently it's set to 15 which is stories per one Digg page.

The script takes an optional argument which specifies how many requests to make. On each request, story offset is advanced by ITEMS_PER_REQUEST. Specifying no argument goes through all the stories which appeared on Digg.

For example, to print out current picture posts which are currently on the front page of Digg, we could use command:

./ 1

Here is a sample of real output of this command:

$ ./ 1
title: 13 Dumbest Drivers in the World [PICS]
type: pictures
desc: Think of this like an even funnier Darwin awards, but for dumbass driving (and with images).
category: Offbeat News
short_category: offbeat_news
user: suxmonkey
date: 2007-09-02 14:00:06

This input is then fed into script which inserts this data into SQLite database.

Then is ran which generates the static HTML contents.
Please refer to the original post of the reddit media website generator to find more details.

Summing it up, only one new script had to be written and some minor changes to existing scripts had to be made to generate the new website.

Here is this new script
digg extractor (perl script, digg picture website generator)

Click to visit the site!

Here are all the scripts packed together with basic documentation:

Download Digg's Picture Website Generator Scripts

All the scripts in a single .zip:
Download link: digg picture website generator suite (.zip)
Downloaded: 3306 times

For newcomers, digg is a democratic social news website where users decide its contents.

From their faq:

What is Digg?

Digg is a place for people to discover and share content from anywhere on the web. From the biggest online destinations to the most obscure blog, Digg surfaces the best stuff as voted on by our users. You won’t find editors at Digg — we’re here to provide a place where people can collectively determine the value of content and we’re changing the way people consume information online.

How do we do this? Everything on Digg — from news to videos to images to Podcasts — is submitted by our community (that would be you). Once something is submitted, other people see it and Digg what they like best. If your submission rocks and receives enough Diggs, it is promoted to the front page for the millions of our visitors to see.

john resig post icon jquery library designOne of my upcoming web projects uses the AJAX technology and jQuery. I had watched a dozen of video lectures on JavaScript before and thought that I have seen them all. Today I came across John Resig's website and found that he just had been at Google and gave a video lecture on Best Practices in JavaScript Library Design.

John Resig is a JavaScript Evangelist, working for the Mozilla Corporation, and the author of the book 'Pro JavaScript Techniques.' He's also the creator and lead developer of the jQuery JavaScript library and the co-designer of the FUEL JavaScript library (included in Firefox 3).

This talk explores all the techniques used to build a robust, reusable, cross-platform JavaScript Library. We'll look at how to write a solid JavaScript API, show you how to use functional programming to create contained, concise, code, and delve deep into common cross browser issues that you'll have to solve in order to have a successful library.

Here is the video:

And here are the slides:

Things that caught my attention in video:

  • (01:49) jQuery was released on Jan. 2006 and it's main focus is on DOM traversal.
  • (05:39) Similar objects should have the same method and property names so there was minimal learning curve.
  • (07:16) Fear adding methods to the API. You should keep the API as small as possible.
  • (11:38) jQuery 1.1 removed reduced size by 47% by removing unnecessary methods, breaking compatibility with jQuery 1.0. A plugin for 1.1 was released as a separate package to provide the old 1.0 interface.
  • (14:10) Look for common patterns in the API and reduce it to its code.
  • (15:33) Be consistent within your API, stick to a naming scheme and argument positioning.
  • (17:11) Evolution of a JavaScript coder:
    • Everything is a reference!
    • You can do OO code!
    • Huh, so that's how Object Prototypes work!
    • Thank God for closures!
  • (21:20) In JavaScript 1.7 there is a let statement which declares variables local to a block.
  • (22:43) If you wrap your entire library in (function() { ... library code ... })() the code will never mess other library code.
  • (24:10) Some namespacing questions:
    • (24:17) Can my code coexist with other random code on the site?
    • (24:50) Can my code coexist with other copies of my own library?
    • (25:16) Can my code be embedded inside another namespace?
  • (25:42) Never extend native objects, ever!
  • (26:39) A JavaScript library should: first, work cross browser; second, have functionality.
  • (32:09) You can tweak your Object constructor to make Constructor() work the same as new Constructor().
  • (34:37) There are three ways to extend jQuery, you can add methods, selectors and animations.
  • (36:37) Message passing from one component to another is best done via custom events.
  • (37:45) Quirksmode is a fantastic resource which explains where specific bugs exist in the browsers.
  • (38:53) DOM Events and DOM Traversal problems are solved in depth, many others, such as getting an attribute and getting the computer style still require hard work.
  • (41:09) In Safari 2 the getComputedStyle is null if it's called on an element with display: none or on an element which is within an element with display: none. Safari 3 implemented the interface but they just return undefined.
  • (45:08) Use structured format for documentation. What's nice about it is that it can be converted to other formats and given to users.
  • (48:16) Let your users help you by putting out documentation in a Wiki.
  • (49:36) Don't trust any library that doesn't have a test suite.

Here is the QA:

  • (52:40) Is jQuery more or less targeted on FireFox and wouldn't actually be reasonable to use, say, on a cellphone?
  • (53:29) How do you filter noise in community?
  • (54:30) Is jQuery going to get multiple build sets?
  • (55:05) Will there ever be time when library development like this is not necessary anymore? Or do you think that the ecosystem of libraries is good for advancing state of the art?
  • (56:34) How do you compare jQuery to something like Google Web Toolkit
  • (57:12) What's the largest project jQuery is used in, in terms of size and development team, and code base.

Have fun learning better JavaScript!