Python-скрипт для отправления музыки на Last.fm из лог-файла.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/python
########## config parameters ###############
# location of log file which is provided by your music player
log_file = "/media/disk/Transfer/mplog.txt"
# encoding of the log file
# usually WINDOWS-1251 on windows systems (e.g. Windows Mobile)
# See 'man iconv' for other encodings
log_file_enc = "WINDOWS-1251"
# temp location where converted log file is stored
temp_file = "/tmp/mplog_converted.txt"
# your rhythmbox audioscrobbler queue file.
rhythmbox_queue_file = "/home/goldan/.gnome2/rhythmbox/audioscrobbler.queue"
# your last.fm personal page
lastfm_page = "http://www.last.fm/user/Goldan"
# your timezone shift counting from GMT.
# If you're in Russia, don't forget summer time. Negative values allowed.
timezone_shift = 4
# draw detailed table (a sort of rating) with information what you have
# listened? (0 - no, 1 - yes)
draw_table = 0
############ end of config parameters ###########
# convert log file to UTF-8 temp file
import commands
try:
if commands.getstatusoutput('touch ' + temp_file)[0]: raise OSError # clear temp file
if commands.getstatusoutput('iconv -f ' + log_file_enc + ' -t UTF-8 -o ' + temp_file + ' ' + log_file)[0]: raise OSError # convert log file to unicode temp file
if commands.getstatusoutput('rm -fr ' + log_file)[0]: raise OSError # remove log_file
except OSError: # if faced problems, gracefully quit
print "An error occured when opening and converting log file. Please ensure it exists and you have enough permissions to operate on log and temp files."
quit()
# read temp file
try:
f = open(temp_file) # now open temp file for reading
except IOError:
print "Temp file " + temp_file + " cannot be opened. Please ensure it exists and you have enough permissions to read it."
quit()
data = f.read()
f.close()
# remove temp file
import os
try:
os.remove(temp_file) # remove temp file
except OSError:
print "Temp file " + temp_file + " wasn't removed."
# process input data
data = data.split("\r\n")
data = [elem for elem in data if len(elem) > 0]
import re
elemPattern = re.compile(r'''
^(\d{2})-(\d{2})-(\d{4})\ # date: day-month-year + whitespace
(\d{1,2}):(\d{2}):(\d{2})\ # time: hours:minutes:seconds + whitespace
(.*)\ -\ (.*)\ -\ (.*)$ # meta: artist - title - album
''', re.VERBOSE)
record_count = 0
def smart_str (a):
'''Adds a leading 0 to a number from 1 to 9'''
if a < 0 or a > 9: return a
return "0"+str(a)
class Record:
'''Represents a record - a fact of song listened'''
def __init__ (self,data):
self.day = data[0]
self.month = data[1]
self.year = data[2]
self.hour = data[3]
self.minute = data[4]
self.second = data[5]
self.artist = data[6]
self.title = data[7]
self.album = data[8]
self.i = globals()["record_count"]
globals()["record_count"] += 1
self.correct_timezone(timezone_shift)
def correct_timezone (self,shift):
'''correct timezone of dates of records'''
hour = int(self.hour)
day = int(self.day)
month = int(self.month)
year = int(self.year)
hour -= shift
if (hour >= 0):
self.hour = str(hour)
return
hour += 24
self.hour = str(hour)
day -= 1
if (day > 0):
self.day = smart_str(day)
return
if (month-1 in [1,3,5,7,8,10,12]): day += 31
else: day += 30
self.day = smart_str(day)
month -= 1
if (month > 0):
self.month = smart_str(month)
return
month += 12
self.month = smart_str(month)
year -= 1
self.year = str(year)
# actually create Records array
records = [Record(elemPattern.search(elem).groups()) for elem in data]
# remove short tracks, ignoring days change
def long_record(elem):
'''returns 1 if the track is considered long and thus good for scrobbling (if it's length was more than 1 minute). Otherwise returns 0'''
i = elem.i
if (i == len(records)-1): return 1
if (records[i].day == records[i+1].day and records[i].month == records[i+1].month and records[i].year == records[i+1].year):
if (int(records[i+1].hour) - int(records[i].hour) > 1): return 1
if (int(records[i+1].hour) - int(records[i].hour) == 1):
if (int(records[i+1].minute)+60 - int(records[i].minute) > 1): return 1
if (int(records[i+1].second) >= int(records[i].second)): return 1
return 0
if (int(records[i+1].minute) - int(records[i].minute) > 1): return 1
if (int(records[i+1].minute) - int(records[i].minute) == 1):
if (int(records[i+1].second) >= int(records[i].second)): return 1
return 0
return 1
records = filter (long_record, records)
class Song:
'''represents a song belonging to artist'''
def __init__(self,rec):
self.day = rec.day
self.month = rec.month
self.year = rec.year
self.hour = rec.hour
self.minute = rec.minute
self.second = rec.second
self.title = rec.title
self.artist = rec.artist
self.album = rec.album
self.count = 1
class Artist:
def __init__(self,rec):
self.name = rec.artist
self.songs = [Song(rec)]
self.count = 1
artists = []
# table generation (a sort of rating)
def gen_table():
for rec in records:
artist_flag = 0
for artist in artists:
if (rec.artist == artist.name):
artist.count += 1
song_flag = 0
for song in artist.songs:
if (rec.title == song.title):
song.count += 1
song_flag = 1
if (not song_flag):
artist.songs.append(Song(rec))
artist_flag = 1
if (not artist_flag):
artists.append(Artist(rec))
def compare_media(media1, media2):
if (media1.count < media2.count): return 1
if (media1.count > media2.count): return -1
return 0
artists.sort(compare_media)
for artist in artists: artist.songs.sort(compare_media)
print "Artists:"
for artist in artists:
print artist.name, artist.count
print "------------------------\n-----------------\n---------------"
total = 0
for artist in artists:
print artist.name,artist.count,":"
for song in artist.songs:
print "\t",song.title, song.count
total += song.count
print "Total: ", total
if draw_table:
gen_table()
# Scrobbling section
# verify current state of the site
def check_site():
'''downloads your last.fm personal page and checks how much tracks you have listened.'''
page = commands.getoutput('wget ' + lastfm_page + ' -O -')
pattern = re.compile('Tracks played:\W*<\/strong>\W*<span class=\"nowrap\">(\d+),(\d+)<\/span><\/span>')
nums = pattern.search(page).groups()
num = ''
for elem in nums: num = num + str(elem)
num = int(num)
return num
old_num = check_site()
# update rhythmbox audioscrobbler file
try:
f = open(rhythmbox_queue_file,"a")
except IOError:
print "Couldn't open you rhythmbox queue file: " + rhythmbox_queue_file + ". Please ensure it exists and you have enough permissions to read and write to it."
quit()
from PyQt4 import QtCore
def convert(str):
'''convert special characters before scrobbling'''
str = re.sub( "\&", "%26", str )
str = re.sub( "\/", "%2F", str )
str = re.sub( "\;", "%3B", str )
str = re.sub( "\+", "%2B", str )
str = re.sub( "\#", "%23", str )
return str
#return QtCore.QUrl.toPercentEncoding(str)
# generate information for scrobbling and write it to queue file
for rec in records:
f.write("a=%s&t=%s&b=%s&m=&l=240&i=%s%s%s%s%s%s%s%s%s%s%s\n" % (convert(rec.artist),convert(rec.title),convert(rec.album),rec.year,"%2D",rec.month,"%2D",rec.day,"%20",rec.hour,"%3A",rec.minute,"%3A",rec.second))
f.close()
print len(records),"songs were queued for scrobbling"
# kill and start rhythmbox to start scrobbling to site
commands.getoutput('killall -q rhythmbox')
temp = os.system('rhythmbox &')
# Scrobbling to site and verifying
print "Scrobbling... Your current song count is " + str(old_num) + "."
import time
for i in range(1,10+len(records)):
time.sleep(10)
new_num = check_site()
if new_num-old_num == len(records):
print str(len(records)) + ' songs were successfully scrobbled! Your new song count is ' + str(new_num) + '.'
break
elif new_num-old_num > 0:
print "Scrobbling processing... " + str(new_num-old_num) + " scrobbled. " + str(len(records)-(new_num-old_num)) + " remaining."
elif new_num == old_num:
print "Waiting for the start of scrobbling..."