Best Images on Reddit As Your Desktop Background – Automatically

I’m on Reddit more than I would care to admit. One of my favorite parts of the website is the subreddit EarthPorn. Despite having the word “porn” in its title there is nothing obscene. It is simply a collection of high resolution photographs of some of the coolest places on Earth. I found myself occasionally setting a particularly awesome image from the website as my desktop background for a while.

Photo from EarthPorn

 Example of one of the awesome images on EarthPorn. Credit to /u/xeno_sapien.

 Even though OS X makes this pretty easy easy, I figured I could do better. What I ended up writing was a short Python script that will automatically pull down the top rated images from EarthPorn and place them in a folder. I have my Desktop settings change the desktop background to an image in that folder and switch every hour. The script runs at startup so new images are pulled down each day. When everything in place this gives me a completely new desktop background every hour!

The Script

The script itself is pretty simple, less than 100 lines. It uses urllib, a default library for Python that helps fetch data from the web.

The first thing in the script is a delay (2 minutes) to give the computer time to establish an internet connection. I don’t check if there is an active connection before proceeding, but I probably should. The next thing I do is delete the old images from the images folder so the folder will just contain the most recent images about to be pulled down.

time.sleep(120)

for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except Exception, e:
print e

Note: I’m having a bit of trouble formatting the whitespace in these code snippets. Of course, this code would have to be properly spaced in order to run in Python.

Python connects to a page in Reddit’s EarthPorn that displays the top 50 images of the day. Then urllib scans the page looking for image links. Currently I only look for JPG images hosted on the image sharing website Imgur. This does leave out some images like those hosted on Flickr or formatted in PNG or the like, but it gets most of the images.

urlString = "http://www.reddit.com/r/EarthPorn/top/?sort=top&t=day"
htmlSource = urllib.urlopen(urlString).read().decode("iso-8859-1")
urlList = re.findall("http://i.imgur.com/\w+.jpg", htmlSource)

Interestingly enough, findall will return two links to each image. I think this is just the way the Reddit page is set up. When I go to grab images, I simply use every other link in urlList. Each image is saved with the date and an index starting with 0.


for index in range(0,numUrls,2):
url = urlList[index]
fileName = "img/" + time.strftime("%m") + "_" + time.strftime("%d") +           "_" + "%d.jpg" %imgName
imgName += 1

image=urllib.URLopener()
image.retrieve(imgUrl,fileName)

The Automation

There are many ways to get the script to run automatically at startup but since I am using OS X I decided to use Automator, a utility to automate workflows. I created a new workflow that simply runs the Python script. I then exported the workflow as an application. Under System Preferences -> Users & Groups -> My Account ->Login Items I added the new application. Now every time I login the workflow runs and grabs new images.

I went into my Desktop & Screensaver settings and added the folder that Python pulls the images into. I then set up the desktop background to change every hour to keep the images it displays fresh and new!

There are a lot of ways that I can improve this script. If there is no internet connection the script will just delete all your images and fail to pull new ones. Sometimes (though not usually) the images posted to EarthPorn are not of desktop quality. I would like to be able to check the resolution of the images and delete the ones that will look bad when set as my background. I could either use Python Imaging Library to do this. Alternatively, EarthPorn requires that the resolution of each image is posted so I could get more creative with the website parsing and filter the results by resolution as well.

Look for a new update on this script with a bit more functionality soon! The current version is available on GitHub.

 

 

 

 

GNU Radio: Online Processing with MATLAB

Previously I talked about using MATLAB as a tool to read and process data from GNU Radio to help debug a flow-graph offline. If we can do some signal processing in MATLAB after GNU Radio has run, would it be possible to do so while GNU Radio is running? The answer is yes, we can move our processing from GNU Radio to MATLAB at almost any part of a flow-graph.

We’ll use a special file type called a FIFO which is able to be accessed by multiple programs to read and write data. GNU Radio will push data to the FIFO and MATLAB will read that data. In this example I will use my RTL-SDR software-defined radio to receive data, lowpass filter, take the magnitude, and pass the samples to MATLAB for further processing.

RTL-SDR Flow Graph

To direct data to the FIFO in GNU Radio we use a regular file sink and enter the path to where my FIFO will be located.I’m using my Keyless Entry Decoder (more detail on this to come in another post) as an example so I’ll call the file keyless_mag_fifo.

Then we hit the Generate button in GRC, but not the Execute button. This will generate a Python file. By default it will be named top_block.py but we can change that by editing the ID field in the Options block in the flow graph. I’ll name my flow graph keyless_live.

Then we’ll create a shell script, in this example run_keyless_demo.sh. This script will create the FIFO and run the flow graph to start streaming samples to it. The script consists of just a few lines.

clear
sudo rm keyless_mag_fifo
mkfifo keyless_mag_fifo
python keyless_live.py

The script will need root privileges to create the FIFO so we will run the script with

sudo sh run_keyless_demo.sh

Now we just need to pull the data to MATLAB. I’ll use similar code to that which was discussed in previous posts. First we open the FIFO. This is done once

fi = fopen('keyless_mag_fifo','rb');

Then we will write a loop of some sort to pull a certain number of samples out of the FIFO and process them. This line sits inside a while(1) loop

raw = fread(fi,buffer_len,'float');

I’ll need to correctly handle the data type of the samples inside the buffer. In this case they are floats. My buffer length is adjustable. I’ll also check that the function filled the vector raw with the number of samples I asked for.

The most important caveat concerning this process is that the shell script must be running before the above commands are executed in MATLAB. For some reason reading from a buffer that samples aren’t being streamed to will make MATLAB lock up quite unforgivingly. Make sure that you run the shell script then the MATLAB script to ensure all the code plays nice with each other.

In a future post I’ll use this style of processing to decode an On-Off Keying modulated signal from my car’s Keyless Entry remote.

 

GNU Radio: Some More Tools for Offline Processing In MATLAB

In my last post I talked about how data can be stored and read in MATLAB for analysis. The only downside is that these data files do not include any information about timing relative to other blocks. GNU Radio has a built-in functionality with stream tags to keep track of timing information. This can be useful for working with packetized data, but currently there isn’t any way to save those tags along with data to look at later. I’ve been working on a few blocks that might be able to help with this.

Bursty Data & Stream Tags

Originally GNU Radio was great for continuous streaming of samples, but lacked the ability to pass ancillary information like meta data, packet lengths, and the like that would help with decoding bursty data sent in packets. However, in recent years there has been quite a bit of work done to improve this.

One of the features that has helped extend the project’s functionality is Stream Tags. These stream tags operate as a separate data stream to pass information along to blocks downstream in the flow graph. These tags are associated with a certain sample in the data stream and that timing relation is preserved as the tags propagate through the remaining blocks. For instance, there are several blocks in GNU Radio that expect the first sample of a packet to have a tag containing the length of the packet. The block can then do its processing based on packet length.

Stream Tags are Polymorphic Types, a data type that can be used as a general container for data, be it vectors, strings, or any number of data formats such as ints and floats. Each tag has a specific format that contains several parts:

  1.      Offset:          The data stream sample that the tag is associated with
  2.      Key:              A PMT symbol that contains an identifier for the tag
  3.      Value:           A PMT representation of the data the tag is passing
  4.      Source ID:    A PMT symbol representing the block that created the tag (optional)

Saving Tags To File

In my last post I went through using file sinks to process data offline using software such as MATLAB. Currently, the file sinks don’t save tags along with that data. However, such information such as the timing and value of tags might be useful for debugging. For example, if you have a tag denoting the start of each packet you may wish to have that timing information available in MATLAB.

To do this I wrote a fairly simple block “Tag to Byte”. For a parameter it asks for the key associated with a given tag, which in this example is “packet_len”. It can be inserted anywhere into a stream, just change the IO Type parameter to match the input data type. The Tag to Byte block can be followed by a file sink.

Tag To Byte

 

Tag to Byte Block In A Flowgraph

 

The block searches the stream for a tag matching the key. When it finds one it outputs a ‘1’ for that sample only. For any samples that don’t have a tag it outputs a ‘0’. This way the timing between tags is preserved as it is written to file. The file length will be the same as a file containing the data from the same point in the flow graph and the tags will be at the correct offset. The extra timing information from the tags can be used in processing data offline.

Tag and Data

 

Plotting Data and Tags in MATLAB

 

Adding Tags From A File

There also is some utility in being able to add tags anywhere in a data stream. GNU Radio has some functionality for this already. There is a stream to tagged stream block that will add tags at evenly spaced intervals. This can be useful for data that is evenly spaced. However if the tags need to correspond to data that is unevenly spaced, such as simulated irregular bursty transmissions we need another tool to do so.

A block I’ve written called “Add Tag at Offset” takes care of this. It can be inserted anywhere in a data stream and will insert tags into the stream. As parameters it will ask for the key to be associated with the tags and the value to insert. The last parameter is the offset for the tags, and this can be a vector of any length.

Add Tag at Offset

Using Add Tag at Offset In A Flow Graph

 

Every time the block reaches a sample with the same offset as is in its offset vector it will add a tag to that sample. All samples are passed through so the block does not interrupt the data flow.

This can be useful if we wish to take a block that uses tags in a complex flow graph and examine its performance by itself. We can load data from a file and add tags anywhere in the input stream. From the block’s perspective it seems as if it is still in the overall flow graph.

Both of these blocks and a few more that are useful for working with stream tags are available on GitHub.

What’s Next

There are a few obvious improvements to make to these tools that will be coming soon. It would be nice if the Add Tag at Offset block was able to add tags of different values instead of writing the same value each time. Its current operation might be okay if you were say passing the length of packets to the next block but less useful if you were using the tag to carry information that changes from packet to packet (an estimate of the packet’s carrier frequency offset, for example). A future improvement would be to have this block read the tag values from a vector as well.

It would also be nice if Tag to Byte would pass the value of the tags along to a file sink instead of just a ‘1’ to represent the presence of a tag. A new block with the working title “Tag Extractor” is being developed that will do just that. It will take some doing to cover all stream data types and tag data types, but I’m working on it. The first version of this (only for complex streams and complex-valued tags) is also available on GitHub.

 

GNU Radio: Tools for Offline Processing With MATLAB

Some Background

The GNU Radio project is pretty awesome.

My research focusses on wireless communications. The concept of radio receiver incredibly simple: use an antenna to receive a signal through the air and process that signal to extract the useful information (voice, data, etc). A transmitter is the same idea, in reverse order. The challenging part is the signal processing turn radio waves into information you care about.

When doing work in signal processing for radio communications it is very valuable to be able to test out your ideas with real radios transmitting over the air. In the not-to-distant past this would mean fabricating a new circuit board for every new design. The concept behind software-defined radio is to replace the signal processing done by the fixed hardware with signal processing done digitally. With a software-defined radio we can change the radio just by changing code and test out many new radio designs without having to build new hardware each time.

GNU Radio provides an excellent framework for experimenting signal processing for communication. A receiver or transmitter design in GNU Radio is made up of many blocks each performing one specific function (modulation, encoding, scaling, etc). Each block, written in C++ or Python, takes in data through an input port, processes it, and outputs it to an output port. GNU Radio provides the framework to glue the inputs and outputs together to form a chain of blocks to accomplish a task. This collection of connected blocks is called a flow graph. It even comes with a Simulink-style GUI where connections are shown graphically.

An Example Flowgraph What A Flow Graph in GNU Radio Companion Looks Like

 

With a flow graph implementing the signal processing necessary for, let’s say, an FM radio receiver, you can connect a software-defined radio to your PC and process the data from raw signal to recovered audio.

GNU Radio also gives users the ability to save data at any point in the flow graph to a binary file using file sinks and file sources. The resulting files can be read after the flow graph has run and are useful tools for debugging complicated flow graphs.

Connecting A File Sink Connecting A File Sink

 

Working With File Sinks

The file sink block uses stdio to write raw samples to a file. By default, during this process a certain number of samples will be buffered before being written to file. The number of samples varies by operating system. If there is only a short amount of data going into that file sink you may find the file to be empty after the flow graph is stopped. For this case, we can use the “unbuffered” option. This bypasses the buffering operation and writes all samples directly to file.

Another thing to note is that GNU Radio companion uses absolute file paths. So be sure to change the paths if you move your flow graph to another directory or machine.

There are several ways that data can be represented in GNU Radio. These data types can be selected in the file sink block and must match the data type of the samples that are streaming to it. The data types used are:

Complex 32 bit floating point for both I and 32 Q
Float 32 bit single precision floating point
Integer 32 bit signed integer
Short 16 bit signed integer
Byte 8 bit signed integer

 

Reading Binary Files in MATLAB

Once data has been written to a file there are several ways we can examine it. A file source can be used to read back the file into another GNU Radio flow graph. We could also use Python to read and analyze the data. While it’s not free, MATLAB can be a particularly useful tool and one which most engineers are rather familiar with.

Raw data files can be read into MATLAB quite easily with a few lines of code:

f = fopen(filename, 'rb');
v = fread(f,count);
fclose(f);

The first line tells MATLAB to open the file given by filename as read-only with Big-Endian encoding. The file identifier is stored in the variable f. The last line closes the file.

The MATALB function fread does the work of pulling data out of the file and into the array v. We give it the file identifier and the number of items to read (or tell it to read the file until empty). By default, MATLAB will read the file assuming the data type is an 8-bit integer. To read different file types we will need to add an extra parameter. For example, to read floats from a file we will use

v = fread (f, count, 'float');

For the case of complex numbers the I and Q samples are interleaved. The data file will contain the I for sample 1, the Q for sample 1, the I for sample 2, etc. The read_complex_binary.m file distributed with GNU Radio shows how to take care of this

t = fread (f, [2, count], 'float');
v = t(1,:) + t(2,:)*i;
[r, c] = size (v);
v = reshape (v, c, r);

We will read the data two floats at a time. Then convert the two floats to one complex number. That will then be reshaped into one complex vector.

It is convenient to create a function that does the file read operation for each data type. Several of these files come with GNU Radio such as read_float_binary.m and read_complex_binary.m. I’ve written functions that do the same for all the other data types used in GNU Radio. They are available to download from GitHub.

Writing Binary Files From MATLAB

We can also write data from MATLAB to a file and play that file back in GNU Radio using a file source. We’ll use a similar set of commands.

f = fopen (filename, 'wb');
v = fwrite (f, data);
fclose (f);

We’ll open a file specified by filename, this time making it writable. We’ll write the vector data into that file using MATLAB’s fwrite command. The variable v will show the number of elements in data that were successfully written to file.

We will need to give fwrite the same parameters to deal with different data types as in fread. For example, to write a vector of floats to file we will use

v = fwrite (f, data, 'float');

As with the read functions, there are several MATLAB files distributed with GNU Radio to handle writing to files from MATLAB. I’ve added functions to handle other data types which are also available in the GitHub repository.