lolamontes69

Ch2 Ex5-Programming Collective Intelligence

May 28th, 2013
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.52 KB | None | 0 0
  1. """ Now recommends albums from artists """
  2. import os as os
  3. import urllib
  4. import json                        # we are after all importing json
  5. from time import sleep
  6. from recommendations import *
  7.  
  8. def sim_tanimoto(prefs, p1, p2):
  9.     Na = Nb = Nc = 0.0
  10.     # count elements
  11.     for item in prefs[p1]:
  12.         Na += 1.0
  13.         if item in prefs[p2]: Nc += 1.0
  14.     for item in prefs[p2]:
  15.         Nb += 1.0
  16.     # calculate tanimoto score
  17.     num = Nc
  18.     den = (Na + Nb) - Nc
  19.     r = float(num/den)
  20.     return r
  21.    
  22. def user_getTopArtists(username):
  23.     global banddic, api_key
  24.     urlstart = "http://ws.audioscrobbler.com/2.0/?method=user.gettopartists&user="
  25.     urllimit = "&limit="
  26.     urlpage = "&page="
  27.     urlend = "&api_key="+api_key+"&format=json"
  28.     url = urlstart
  29.  
  30.     def download_it(url):
  31.         global banddic
  32.         dic = {}
  33.         conn = urllib.urlopen(url)
  34.         for line in conn:              # comes as a unicode string
  35.             dic = json.loads(line)     # load json into dic
  36.         for f in range(len(dic['topartists']['artist'])):
  37.             bandname = dic['topartists']['artist'][f]['name']
  38.             rank = dic['topartists']['artist'][f]['@attr']['rank']
  39.             # Give scores to each users top ten ranked artists
  40.             if int(rank) == 1: score = 10
  41.             elif int(rank) == 2 : score = 9
  42.             elif int(rank) == 3: score = 8
  43.             elif int(rank) == 4 : score = 7
  44.             elif int(rank) == 5: score = 6
  45.             elif int(rank) == 6 : score = 5
  46.             elif int(rank) == 7: score = 4
  47.             elif int(rank) == 8 : score = 3
  48.             elif int(rank) == 9: score = 2
  49.             elif int(rank) == 10 : score = 1
  50.             else: score = 0
  51.             try:
  52.                 if score > 0:
  53.                     if username not in banddic:
  54.                         banddic[username] = {}
  55.                         banddic[username][bandname] = score
  56.                     else:
  57.                         banddic[username][bandname] = score
  58.                 else: pass
  59.             except: pass
  60.     url += username
  61.     url += urlend
  62.     download_it(url)
  63.  
  64. def artist_getTopAlbums(artist):
  65.     global api_key
  66.     urlstart = "http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist="
  67.     urlend = "&api_key="+api_key+"&format=json"
  68.     url = urlstart
  69.  
  70.     def download_it(url):
  71.         global resultdic
  72.         dic = {}
  73.         try:
  74.             conn = urllib.urlopen(url)
  75.             for line in conn:              # comes as a unicode string
  76.                 dic = json.loads(line)     # load json into dic
  77.             count1 = 0
  78.             print "Recommended albums by",artist
  79.             for a in range(len(dic['topalbums']['album'])):
  80.                 albumname = dic['topalbums']['album'][a]['name']
  81.                 rank = dic['topalbums']['album'][a]['@attr']['rank']
  82.                 print rank,":",albumname
  83.                 count1 += 1
  84.                 if count1 == 5: break
  85.         except: pass
  86.         print "------------------"
  87.     url += artist
  88.     url += urlend
  89.     download_it(url)
  90.  
  91. def artist_gettopfans():
  92.     global firstband
  93.     ch = """
  94. ###############################################################
  95. #      artist.getTopFans                                      #
  96. #                                                             #
  97. ###############################################################
  98. Enter name of Artist : """
  99.  
  100.     global api_key
  101.     urlstart = "http://ws.audioscrobbler.com/2.0/?method=artist.gettopfans&artist="
  102.     urlend = "&autocorrect=1&api_key="+api_key+"&format=json"
  103.     url = urlstart
  104.     os.system('clear')
  105.     def download_it(url):
  106.         dic = {}
  107.         conn = urllib.urlopen(url)
  108.         print "\nProcessing recommendations from..."
  109.         for line in conn:              # comes as a unicode string
  110.             dic = json.loads(line)     # load json into dic
  111.             try:
  112.                 count2 = 0
  113.                 for f in range(len(dic['topfans']['user'])):
  114.                     print dic['topfans']['user'][f]['name']
  115.                     username = dic['topfans']['user'][f]['name']
  116.                     user_getTopArtists(username)
  117.                     count2 += 1
  118.                     if count2 == 21: break
  119.                     sleep(0.7)
  120.                 return True
  121.             except: return False
  122.     os.system('clear')
  123.     firstband = raw_input(ch)
  124.     url += firstband
  125.     url += urlend
  126.     frog = download_it(url)
  127.     return int(frog)
  128.  
  129. def main():
  130.     global banddic, firstband
  131.     bruce = int(artist_gettopfans())
  132.     while bruce == False:
  133.         bruce = int(artist_gettopfans())
  134.  
  135.     dict1 = {}
  136.     high = 0
  137.     # Compare banddic and add to dict1
  138.     for a in banddic:
  139.         for b in banddic:
  140.             if b != a:
  141.                 crit1 = str(a)
  142.                 crit2 = str(b)
  143.                 tani = sim_tanimoto(banddic, crit1, crit2)
  144.                 if tani not in dict1:
  145.                     dict1[tani] = [crit1, crit2]
  146.  
  147.     # Find high score and print results
  148.     for a in dict1:
  149.         if a > high: high = a
  150.     os.system('clear')
  151.     print "\nThe two most similar Last-fm users who are fans of",firstband,"are;\n    ",dict1[high][0],"and",dict1[high][1]
  152.     print "with a Tanimoto_similarity Score of",high
  153.  
  154.     criti1 = str(dict1[high][0])
  155.     criti2 = str(dict1[high][1])
  156.  
  157.     minidic = {}
  158.     for a in banddic[criti1]:
  159.         try:
  160.             a2 = ((banddic[criti1][a])+(banddic[criti2][a]))/2.0
  161.             if a2 not in minidic:
  162.                 minidic[a2] = [a]
  163.             else: minidic[a2].append(a)
  164.         except: pass
  165.     a3 = minidic.keys()
  166.     a3.sort()
  167.     a3.reverse()
  168.     print "\nAnd they recommend\n------------------"
  169.     for a in a3:
  170.         for b in range (len(minidic[a])):
  171.             artist = minidic[a][b]
  172.             print "---",minidic[a][b],a,"---"
  173.             artist_getTopAlbums(artist)
  174.     d = raw_input('Press <enter> to continue')
  175.  
  176. lola = """
  177. ########################################################################
  178. #     _          _        __   ___  _      ____                  _     #
  179. #    | |    ___ | | __ _ / /_ / _ \( )__  | __ )  __ _ _ __   __| |    #
  180. #    | |   / _ \| |/ _  |  _ \ (_) |/ __| |  _ \ / _  | '_ \ / _  |    #
  181. #    | |__| (_) | | (_| | (_) \__, |\__ \ | |_) | (_| | | | | (_| |    #
  182. #  __|_____\___/|_|\__,_|\___/  /_/ |___/ |____/ \__,_|_| |_|\__,_|    #
  183. # |  _ \ ___  ___ ___  _ __ ___  _ __ ___   ___ _ __   __| | ___ _ __  #
  184. # | |_) / _ \/ __/ _ \| '_   _ \| '_   _ \ / _ \ '_ \ / _  |/ _ \ '__| #
  185. # |  _ <  __/ (_| (_) | | | | | | | | | | |  __/ | | | (_| |  __/ |    #
  186. # |_| \_\___|\___\___/|_| |_| |_|_| |_| |_|\___|_| |_|\__,_|\___|_|    #
  187. #                                                                      #
  188. # This application recommends bands for you to listen to based upon    #
  189. # the listening habits of Last-fm users. Just enter the name of a band #
  190. # and the application will get a recommended band from two fans of     #
  191. # band who have the most similar tastes, according to their Tanimoto   #
  192. # similarity score. It is pretty simple to use.                        #
  193. ########################################################################
  194. """
  195. os.system('clear')
  196. api_key = str(raw_input('Please enter your Last-fm api_key >'))
  197. os.system('clear')
  198. d = ""
  199. while (d != "q") or (d != "Q"):
  200.     os.system('clear')
  201.     firstband = ""
  202.     banddic = {}
  203.     print lola
  204.     d = str(raw_input('Press <enter> to start or enter <q> to quit > '))
  205.     if d != "q":
  206.         main()
  207.     else: break
Advertisement
Add Comment
Please, Sign In to add comment