Perl script monitors visitor statistics for YouTube movies

Chart Stormers

Article from Issue 171/2015
Author(s):

Hobby YouTuber Mike Schilli is interested in whether his videos go viral. What better way to check skyrocketing viewer numbers than letting a Perl script analyze the daily trends and watch for unexpected upswings?

When a hardware hacker like myself faces a seemingly unsolvable mechanical problem – for example, when a gadget resists warranty-invalidating opening – you can typically find a solution on YouTube. And, if you need to use a less-than-intuitive program like GIMP, you will typically find an expert screencast on YouTube to help you solve complex problems, even as a newbie.

Dreamship

When I recently managed to use GIMP's Scissor Select tool successfully, I decided to create a screencast. Then, I waited for this masterpiece of movie magic to hit the charts on YouTube. I initially set monthly reminder dates in Evernote to check the number of views by hand at regular intervals. However, that got old pretty quickly, so thanks to the CPAN WebService::GData::YouTube module, I managed to fully automate the process.

For this to happen, the YAML file in Listing 1 lists the IDs of the movies to monitor [1]. I simply extracted the hex numbers from my videos' YouTube URLs. For example, the _Cxu3-UP0G8 string for the GIMP video was simply cut and pasted from the URL line in the browser displayed in Figure 1.

Listing 1

youtube-watch.yml

01 -
02   name: GIMP - Scissors Select Tool
03   id: _Cxu3-UP0G8
04 -
05   name: How to fix Acura/Honda not starting in hot weather
06   id: ssYpyXjGw9g
07 -
08   name: Flip it: Record Messages and play them Backwards
09   id: LdSTIa2Tx4o
10 -
11   name: Scored a goal at Garfield Square
12   id: bvOvnyJTyss
Figure 1: The amateur director of this YouTube screencast would like to know how his viewer numbers are developing (297 views so far).

The script in Listing 2 uses the CPAN YAML module to walk through the entries in the YAML file; it passes the movie ID to the get_video_by_id() method in the WebService::GData::YouTube package on every iteration. The method in turn contacts the YouTube API server and receives a mess of metadata about the movie. Below the _feed key, the script finds the yt$statistics entry with the value for ViewCount – you guessed it, the number of times the movie was requested by interested viewers.

Listing 2

youtube-viewcounts

01 #!/usr/local/bin/perl -w
02 use strict;
03 use WebService::GData::YouTube qw();
04 use YAML qw( LoadFile );
05 use Json qw( to_json );
06
07 my @result = ();
08 my $videos =
09   LoadFile( "youtube-watch.yml" );
10 my $yt = WebService::GData::YouTube->new();
11
12 for my $video ( @$videos ) {
13
14   my $meta =
15     $yt->get_video_by_id( $video->{ id } );
16
17   $video->{ count } = $meta->{ _feed }->
18     { 'yt$statistics' }->{ viewCount };
19
20   push @result, $video;
21 }
22
23 print to_json( \@result,
24     { pretty => 1, canonical => 1 } );

Lines 23 and 24 quickly convert the output, with some help from the CPAN JSON module, to a machine-readable format; this allows for easier post-processing by a script like Listing 3. They set the pretty option to make the output easier for human consumers to understand and canonical to sort the hash keys alphabetically, which would otherwise be in random order in Perl. In the resulting array (@result), each element contains the name (movie title), count (the view count added by line 17), and id (the unique YouTube ID of the movie).

Listing 3

viewcounts-todb

01 #!/usr/local/bin/perl -w
02 use strict;
03 use DBD::SQLite;
04 use Json qw( from_json );
05 use DBI;
06 my $dbh = DBI->connect(
07   "dbi:SQLite:dbname=viewcounts.db",
08   "", "", { RaiseError => 1} );
09
10 my $data = from_json( join '', <STDIN> );
11
12 for my $video ( @$data ) {
13   my $sth = $dbh->prepare(
14     "INSERT INTO
15      views(video_id,views,queried)
16      VALUES(?,?,CURRENT_TIMESTAMP)" );
17   $sth->execute( $video->{ id },
18                  $video->{ count } );
19 }

Figure 2 shows the output from the script and reveals that my previously little-known sideline as a car mechanic working on 20-year-old Honda engines is one of the highlights of my oeuvre with no fewer than 56,000 views, whereas the GIMP screencast has a miserly 297 views to date.

Figure 2: The JSON output from Listing 2 with requests per movie as retrieved from YouTube.

Daily Tests

If you run Listing 1 once a day as a cronjob, the next logical thing to do is to archive and later evaluate the data. For this, Listing 3 employs a SQLite mini-database that stores its data in a single file but still supports SQL queries.

The database schema generated in Listing 4 contains fields for every movie's YouTube ID (video_id), the number of views (views) and the date stamp of the query (queried). The command

Listing 4

viewcounts.sql

1 CREATE TABLE views (
2   video_id TEXT,
3   views    INTEGER,
4   queried  DATE
5 );
sqlite3 viewcounts.db <viewcounts.sql

tells SQLite to create a database in the new viewcounts.db file. Listing 3 can then fire as a second stage in the command pipe

youtube-viewcounts | viewcounts-todb

to receive the JSON data generated by Listing 2 and create a database record for each array entry.

The script fills the table's date field for each new entry in line 16 of Listing 3 with CURRENT_TIMESTAMP; SQLite replaces this in the database with the current date and time. This step gives you a database entry with a time stamp for each monitored movie and day, and you can easily retrieve the entries sorted by time.

Based on the database entries shown in Figure 3, Listing 5 now tries to find out whether the viewer figures are continually increasing or possibly skyrocketing. In this case, I want the script to alert me.

Listing 5

hit-detect

01 #!/usr/local/bin/perl -w
02 use strict;
03 use DBI;
04 use DBD::SQLite;
05 use Statistics::LineFit;
06 use YAML qw( LoadFile );
07 use Json qw( to_json );
08
09 my $dbh = DBI->connect(
10   "dbi:SQLite:dbname=viewcounts.db",
11   "", "", { RaiseError => 1} );
12
13 my $videos =
14   LoadFile( "youtube-watch.yml" );
15
16 for my $video ( @$videos ) {
17   my $sth = $dbh->prepare(
18     "SELECT views from views
19      WHERE video_id = ? ORDER BY
20      queried ASC" );
21   $sth->execute( $video->{ id } );
22
23   my @xvalues = ();
24   my @yvalues = ();
25
26   my $x = 1;
27   while ( my @row =
28           $sth->fetchrow_array ) {
29     push @xvalues, $x;
30     push @yvalues, $row[0];
31     $x++;
32   }
33
34   my $last_x = pop @xvalues;
35   my $last_y = pop @yvalues;
36
37   my $fit = Statistics::LineFit->new();
38   $fit->setData (\@xvalues, \@yvalues) or
39     die "Invalid data";
40
41   my ($intercept, $slope) =
42     $fit->coefficients();
43
44   my $y_predicted = $intercept +
45                     $last_x * $slope;
46
47   if( abs( $last_y - $y_predicted ) >
48                              3 * $slope ) {
49     print
50     "Hooray, $video->{ name } is a hit!\n";
51   }
52 }
Figure 3: The script stores the daily view figures in the SQLite database.

Hit or Miss?

How do you define skyrocketing, though? For a movie with 30,000 views, which increases by about 10 views a day, these 10 hits don't mean much. However, if you have a less successful movie that remains undiscovered for a long time, and then suddenly has 10 views, you might like to be notified.

Because I recently read an excellent book titled Machine Learning with R [2], which explains all kinds of statistical methods, I had the idea of determining unusual jumps in the viewing figures by means of linear regression [3]. This involves the CPAN Statistics::LineFit module used by Listing 5 trying to make a straight line out of flatlining or continually increasing historic viewing figures (Figure 4). The x axis denotes time from left to right, and the y axis represents the number of views for the current measuring point.

Figure 4: Listing 5 detects a hit if the latest value (blue dot on far right) exceeds the forecast value by far.

It doesn't matter that the straight line doesn't hit each measuring point precisely (in fact, it's not even possible in most cases), as long as the linear regression keeps the unavoidable errors to a minimum. The problem was solved by scientists back in the dark ages, and the CPAN module simply implements the algorithm to compute the a and b parameters from the linear formula y = b+ax. The b parameter expresses the y value at the origin of the x axis (intercept), and the a parameter gives you the gradient of the linear approximation (slope).

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Downloading Web Video

    With the right tools, you can store YouTube movies on your hard disk and view them when Internet access is unsatisfactory or unavailable.

  • YouTube Players

    YouTube offers more than just funny kitten movies; you will also find more than 60 million music videos. With a native YouTube client for Linux, you can use this online jukebox as conveniently as your local music collection.

  • Movgrab

    Video portals such as YouTube or Vimeo offer a wealth of curious and entertaining short films. If you want to enjoy them offline, a small tool called Movgrab can help.

  • Legal Video Downloads: YouTube goes Offline

    Until now, watching YouTube videos offline has been an awkward business, possible only with Firefox plugins or similar contraptions. Now, with the help of Creative Commons licenses, this could soon change.

  • Minitube: Slimline YouTube Client

    Anyone wanting to watch just a short video on YouTube probably won't need Minitube, for those that want more, it's a must-have app.

comments powered by Disqus

Direct Download

Read full article as PDF:

Price $2.95

News

njobs Europe
What:
Where:
Country:
Njobs Netherlands Njobs Deutschland Njobs United Kingdom Njobs Italia Njobs France Njobs Espana Njobs Poland
Njobs Austria Njobs Denmark Njobs Belgium Njobs Czech Republic Njobs Mexico Njobs India Njobs Colombia