We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

import-jamendo.py 11.9 KB
Newer Older
1 2 3
#!/usr/bin/env python

import xml.etree.cElementTree as ElementTree
4
import sys, gzip, time, httplib
5
import psycopg2 as ordbms
6

7 8
JAMENDO_MIRROR = "gigue.rrbone.net"

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
genremap = {
	0 : "Blues",
	1 : "Classic Rock",
	2 : "Country",
	3 : "Dance",
	4 : "Disco",
	5 : "Funk",
	6 : "Grunge",
	7 : "Hip-Hop",
	8 : "Jazz",
	9 : "Metal",
	10 : "New Age",
	11 : "Oldies",
	12 : "Other",
	13 : "Pop",
	14 : "R&B",
	15 : "Rap",
	16 : "Reggae",
	17 : "Rock",
	18 : "Techno",
	19 : "Industrial",
	20 : "Alternative",
	21 : "Ska",
	22 : "Death Metal",
	23 : "Pranks",
	24 : "Soundtrack",
	25 : "Euro-Techno",
	26 : "Ambient",
	27 : "Trip-Hop",
	28 : "Vocal",
	29 : "Jazz+Funk",
	30 : "Fusion",
	31 : "Trance",
	32 : "Classical",
	33 : "Instrumental",
	34 : "Acid",
	35 : "House",
	36 : "Game",
	37 : "Sound Clip",
	38 : "Gospel",
	39 : "Noise",
	40 : "Alternative Rock",
	41 : "Bass",
	42 : "Soul",
	43 : "Punk",
	44 : "Space",
	45 : "Meditative",
	46 : "Instrumental Pop",
	47 : "Instrumental Rock",
	48 : "Ethnic",
	49 : "Gothic",
	50 : "Darkwave",
	51 : "Techno-Industrial",
	52 : "Electronic",
	53 : "Pop-Folk",
	54 : "Eurodance",
	55 : "Dream",
	56 : "Southern Rock",
	57 : "Comedy",
	58 : "Cult",
	59 : "Gangsta",
	60 : "Top 40",
	61 : "Christian Rap",
	62 : "Pop/Funk",
	63 : "Jungle",
	64 : "Native American",
	65 : "Cabaret",
	66 : "New Wave",
	67 : "Psychadelic",
	68 : "Rave",
	69 : "Showtunes",
	70 : "Trailer",
	71 : "Lo-Fi",
	72 : "Tribal",
	73 : "Acid Punk",
	74 : "Acid Jazz",
	75 : "Polka",
	76 : "Retro",
	77 : "Musical",
	78 : "Rock & Roll",
	79 : "Hard Rock",
	80 : "Folk",
	81 : "Folk-Rock",
	82 : "National Folk",
	83 : "Swing",
	84 : "Fast Fusion",
	85 : "Bebop",
	86 : "Latin",
	87 : "Revival",
	88 : "Celtic",
	89 : "Bluegrass",
	90 : "Avantgarde",
	91 : "Gothic Rock",
	92 : "Progressive Rock",
	93 : "Psychedelic Rock",
	94 : "Symphonic Rock",
	95 : "Slow Rock",
	96 : "Big Band",
	97 : "Chorus",
	98 : "Easy Listening",
	99 : "Acoustic",
	100 : "Humour",
	101 : "Speech",
	102 : "Chanson",
	103 : "Opera",
	104 : "Chamber Music",
	105 : "Sonata",
	106 : "Symphony",
	107 : "Booty Bass",
	108 : "Primus",
	109 : "Porn Groove",
	110 : "Satire",
	111 : "Slow Jam",
	112 : "Club",
	113 : "Tango",
	114 : "Samba",
	115 : "Folklore",
	116 : "Ballad",
	117 : "Power Ballad",
	118 : "Rhythmic Soul",
	119 : "Freestyle",
	120 : "Duet",
	121 : "Punk Rock",
	122 : "Drum Solo",
	123 : "A capella",
	124 : "Euro-House",
	125 : "Dance Hall",
}

class JamendoImport:

140 141
	def __init__(self, username='librefm', database='librefm', updates=False):
		self.conn = ordbms.connect ("dbname='%s' user='%s'" % (database, username))
142
		self.perform_updates = updates
143 144 145 146 147 148 149 150 151
		self.cursor = self.conn.cursor ()


	def parse(self, dump):
		for event, elem in ElementTree.iterparse(dump):
			if elem.tag == "artist":
				artist = self.proc_artist(elem)

				if self.artist_exists(artist["name"]):
152 153 154 155 156 157 158
					if self.perform_updates:
						try:
							self.cursor.execute("UPDATE Artist SET image_small = %s, homepage = %s, mbid = %s WHERE name = %s", (artist["image"], artist["url"], artist["mbid"], artist["name"]))
							self.conn.commit()
						except Exception,  e:
							self.conn.rollback()
							print 'ua', e
159 160
				else:
					try:
clint's avatar
clint committed
161
						self.cursor.execute("INSERT INTO Artist (name, image_small, mbid, homepage)  VALUES (%s, %s, %s, %s)", (artist["name"], artist["image"], artist["mbid"], artist["url"]))
162
						self.conn.commit()
163
					except Exception,  e:
164
						self.conn.rollback()
clint's avatar
clint committed
165
						print 'ia', e
166

167
				any_streamable_tracks = 0
168 169
				for album in artist["albums"]:
					if self.album_exists(artist["name"], album["name"]):
170 171 172 173 174 175 176 177 178
						if self.perform_updates:
							try:
								self.cursor.execute("UPDATE Album SET albumurl = %s, image = %s, artwork_license = %s, mbid = %s, releasedate = %s, downloadurl = %s WHERE name = %s AND artist_name = %s", 
										(album["url"], album["image"], album["license_artwork"], album["mbid"], album["releasedate"], album["downloadurl"],
										album["name"], artist["name"]))
								self.conn.commit()
							except Exception,  e:
								self.conn.rollback()
								print 'ub', e
179 180
					else:
						try:
181
							self.cursor.execute("INSERT INTO Album (name, artist_name, albumurl, image, artwork_license, mbid, releasedate, downloadurl) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
182
									(album["name"], artist["name"], album["url"], album["image"], album["license_artwork"], album["mbid"], album["releasedate"], album["downloadurl"]))
183
							self.conn.commit()
184
						except Exception,  e:
185
							self.conn.rollback()
clint's avatar
clint committed
186
							print 'ib', e
187 188 189 190 191 192

					for tag in album["tags"]:
						if not self.tag_exists(tag, artist["name"], album["name"]):
							try:
								self.cursor.execute("INSERT INTO Tags (tag, artist, album) VALUES (%s, %s, %s)",
										(tag, artist["name"], album["name"]))
193
								self.conn.commit()
194
							except Exception,  e:
195
								self.conn.rollback()
clint's avatar
clint committed
196
								print 'ig', e
197 198

					for track in album["tracks"]:
199

200
						if self.free_license(track["license"]) and self.is_in_mirror(track["id"]):
201
							streamable = 1
202
							any_streamable_tracks = 1
203 204
						else:
							streamable = 0
205

clint's avatar
clint committed
206 207 208
						try:
							duration = int(track["duration"])
						except:
clint's avatar
clint committed
209
							duration = None
clint's avatar
clint committed
210

clint's avatar
clint committed
211 212 213
						otherid = "jm:"

						try:
clint's avatar
clint committed
214
							otherid += str(int(track["id"]))
clint's avatar
clint committed
215
						except:
clint's avatar
clint committed
216
							otherid += "unknown"
clint's avatar
clint committed
217

218
						if self.track_exists(artist["name"], album["name"], track["name"]):
219 220 221 222 223 224
							try:
								self.cursor.execute("UPDATE Track SET downloadurl = %s, streamurl = %s, mbid = %s, license = %s, duration = %s, otherid = %s, streamable = %s WHERE name = %s AND artist_name = %s AND album_name = %s", (track["downloadurl"], track["streamurl"], track["mbid"], track["license"], duration, otherid, streamable, track["name"], artist["name"], album["name"]))
								self.conn.commit()
							except Exception,  e:
								self.conn.rollback()
								print 'ut', e
225 226
						else:
							try:
clint's avatar
clint committed
227
								self.cursor.execute("INSERT INTO Track (name, artist_name, album_name, mbid, downloadurl, streamurl, license, duration, otherid, streamable) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (track["name"], artist["name"], album["name"], track["mbid"], track["downloadurl"], track["streamurl"], track["license"], duration, otherid, streamable))
228
								self.conn.commit()
229
							except Exception,  e:
230
								self.conn.rollback()
clint's avatar
clint committed
231
								print 'it', e
232 233 234 235 236 237

						for tag in track["tags"]:
							if not self.tag_exists(tag, artist["name"], album["name"], track["name"]):
								try:
									self.cursor.execute("INSERT INTO Tags (tag, artist, album, track) VALUES (%s, %s, %s, %s)",
											(tag, artist["name"], album["name"], track["name"]))
238
									self.conn.commit()
239
								except Exception,  e:
240
									self.conn.rollback()
clint's avatar
clint committed
241
									print 'ig2', e
242 243


244 245 246 247 248 249 250 251 252
				if any_streamable_tracks:
					try:
						self.cursor.execute("UPDATE Artist SET streamable = 1 WHERE name = %s", (artist["name"],))
						self.conn.commit()
					except Exception,  e:
						self.conn.rollback()
						print 'ua', e


253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278




	def close(self):
		self.cursor.close()
		self.conn.commit()
		self.conn.close()

	def proc_artist(self, elem):
		artist = {}	
		artist["albums"] = []
		artist["image"] = None

		for artist_e in elem.getchildren():

			if artist_e.tag == "name":
				artist["name"] = artist_e.text
			
			if artist_e.tag == "id":
				artist["id"] = int(artist_e.text)
			
			if artist_e.tag == "image":
				artist["image"] = artist_e.text
			
			if artist_e.tag == "mbgid":
clint's avatar
PEP8?  
clint committed
279
				if artist_e.text is None or len(artist_e.text) == 36:
280 281 282
					artist["mbid"] = artist_e.text
				else:
					print "Artist mbgid wrong length (%d): %s" % (len(artist_e.text),artist_e.text)
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

			if artist_e.tag == "url":
				artist["url"] = artist_e.text

			if artist_e.tag == "Albums":
				for album_e in artist_e.getchildren():
					artist["albums"].append(self.proc_album(album_e))

		return artist


	def proc_album(self, elem):
	
		album = {}
		album["tracks"] = []
		album["tags"] = []
		album["name"] = None
	
		for album_e in elem.getchildren():
		
			if album_e.tag == "name":
				album["name"] = album_e.text
		
			if album_e.tag == "id":
				album["id"] = int(album_e.text)
				album["url"] = "jamendo://album/%d" % album["id"]
				album["downloadurl"] = "jamendo://album/download/%d" % album["id"]
				album["image"] = "jamendo://album/art/%d" % album["id"]
		
			if album_e.tag == "id3genre":
				genre = genremap[int(album_e.text)]
				album["tags"].append(genre)
		
			if album_e.tag == "mbgid":
clint's avatar
PEP8?  
clint committed
317
				if album_e.text is None or len(album_e.text) == 36:
318 319 320
					album["mbid"] = album_e.text
				else:
					print "Album mbgid wrong length (%d): %s" % (len(album_e.text),album_e.text)
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
			
			if album_e.tag == "license_artwork":
				album["license_artwork"] = album_e.text

			if album_e.tag == "releasedate":
				album["releasedate"] = time.mktime(time.strptime(album_e.text, "%Y-%m-%dT%H:%M:%S+01:00"))
		
			if album_e.tag == "Tracks":
				for track_e in album_e.getchildren():
					album["tracks"].append(self.proc_track(track_e))

		return album


	def proc_track(self, elem):
		track = {} 
		track["tags"] = []
		track["mbid"] = None
		track["downloadurl"] = None

		for track_e in elem.getchildren():
		
			if track_e.tag == "id":
				track["id"] = int(track_e.text)
				track["streamurl"] = "jamendo://track/stream/%d" % track["id"]

			if track_e.tag == "name":
				track["name"] = track_e.text

			if track_e.tag == "id3genre":
				genre = genremap[int(track_e.text)]
				track["tags"].append(genre)

			if track_e.tag == "license":
				track["license"] = track_e.text

clint's avatar
clint committed
357 358
			if track_e.tag == "duration":
				track["duration"] = track_e.text
359

360
			if track_e.tag == "mbgid":
clint's avatar
PEP8?  
clint committed
361
				if track_e.text is None or len(track_e.text) == 36:
362 363 364 365
					track["mbid"] = track_e.text
				else:
					print "Track mbgid wrong length (%d): %s" % (len(track_e.text),track_e.text)

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
			if track_e.tag == "Tags":
				for tag_e in track_e.getchildren():
					track["tags"].append(self.proc_tag(tag_e))

		return track


	def proc_tag(self, elem):
		for track_e in elem.getchildren():
			if track_e.tag == "idstr":
				return track_e.text


	def artist_exists(self, artist):
		try:
			self.cursor.execute("SELECT name FROM Artist WHERE name = %s ", (artist,))
			return self.cursor.rowcount != 0
		except:
			return False

	def album_exists(self, artist, album):
		try:
			self.cursor.execute("SELECT name FROM Album WHERE artist_name = %s AND name = %s", (artist, album))
			return self.cursor.rowcount != 0
		except:
			return False

	def track_exists(self, artist, album, track):
		try:
clint's avatar
clint committed
395
			self.cursor.execute("SELECT name FROM Track WHERE artist_name = %s AND album_name = %s AND name = %s", (artist, album, track))
396 397 398 399 400 401 402
			return self.cursor.rowcount != 0
		except:
			return False


	def tag_exists(self, tag, artist, album, track=None):
		try:
clint's avatar
clint committed
403 404 405
			if track:
				self.cursor.execute("SELECT tag FROM Tags WHERE tag = %s AND artist = %s AND album = %s AND track = %s", (tag, artist, album, track))
			else:
406
				self.cursor.execute("SELECT tag FROM Tags WHERE tag = %s AND artist = %s AND album = %s AND track = ''", (tag, artist, album))
407 408 409 410
			return self.cursor.rowcount != 0
		except:
			return False

411 412
	def free_license(self, license):
		return ("http://creativecommons.org/licenses/by-sa" in license or "http://creativecommons.org/licenses/by/" in license or "http://artlibre.org/licence.php/lal.html" in license)
413

414 415 416 417 418 419 420 421 422 423 424 425
	def is_in_mirror(self, id):
		try:
			trackfile = "/" + str(id) + ".ogg2"
			connection = httplib.HTTPConnection(JAMENDO_MIRROR)
			connection.request("HEAD", trackfile)
			response = connection.getresponse()
			connection.close()
		except:
			return False
		else:
			return response.status == 200 and response.getheader('Content-Type') == 'audio/ogg'

426 427
if __name__ == "__main__":

428
	if len(sys.argv) != 2 and len(sys.argv) != 4:
429
		print "Usage: import-jamendo.py <database dump>"
430 431
		print "or"
		print "import-jamendo.py <database dump> <username> <database>"
432 433 434 435 436 437
		sys.exit(1)

	if sys.argv[1][-2:] == "gz":
		dump = gzip.open(sys.argv[1], "r")
	else:
		dump = open(sys.argv[1], "r")
438 439 440 441 442

	if len(sys.argv) == 2:
		importer = JamendoImport()
	else:
		importer = JamendoImport(sys.argv[2], sys.argv[3])
443 444
	importer.parse(dump)
	importer.close()