Saturday, December 8, 2012

How to get Artist from a Youtube Video in Ruby

I've not seen a good answer for this so far, but I discovered one, and I think you'll agree it's quite clever! I considered making this into a gem, but it's so simple, one is not required.

First, use whatever youtube gem you want to grab the title of the youtube video.

Second, get this gem: https://github.com/wiseleyb/google_custom_search_api

Follow instructions there on how to setup your Google Custom Search account and a Custom Search Engine(CSE) that searches all websites. Put the gem into your app as per their instructions, get it working.

Then use this code:

query = video_title
first_entry = "no artist found"

results = GoogleCustomSearchApi.search(query)
results.items.each do |item|
  if item["htmlSnippet"] and m = item["htmlSnippet"].match(/by.*<b>([\w\s]*)<\/b>/)
    first_entry = m[1]
   end
end

first_entry has your artist after you run this. What it does is it scans every Google result snippet for the html "by ...some more useless words... <b>BandName</b>. There is almost ALWAYS a page on the search results that has this pattern, and we isolate the band name by using the fact these pages ALWAYS turn band names into links going to pages about them.

I've tried these videos and gotten it to work:

Shakira - Give it up to me
Linkin park - in the end
Imagine Dragons - it's time

etc. It relies on the fact too that most youtube videos include the band name in the title. The problem is for us coders that it's not often very standard, sometimes it will be linkin park in the end, or in the end - linkin park, or linkin park "in the end", etc. Instead of trying to puzzle it out, let Google do it!

Hope this helped you, certainly helped me.