Skip to content

Instantly share code, notes, and snippets.

@serkanaltuntas
Created June 29, 2014 15:29
Show Gist options
  • Save serkanaltuntas/3ceac92653bdc33aecc8 to your computer and use it in GitHub Desktop.
Save serkanaltuntas/3ceac92653bdc33aecc8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from subprocess import call, STDOUT
import Queue
import threading
import string
import locale
import os
import glob
import codecs
import sys
import time
import unicodedata
import shutil
try:
import requests
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
import youtube_dl
except ImportError, e:
print "Lütfen aşağıdaki bağımlılıklarını kurun!"
print
print "- requests"
print "- google-api-python-client"
print "- youtube-dl"
print "- oauth2client"
print "- urllib3"
current_directory = os.path.abspath( os.path.dirname(__file__) )
if os.name == 'nt':
locale.setlocale(locale.LC_ALL, 'turkish')
else:
locale.setlocale(locale.LC_ALL, 'tr_TR')
for i in ('flv' , 'mp3'):
shutil.rmtree(i)
os.mkdir(i)
tracks = []
urls = []
DEVELOPER_KEY = "YOUTUBE_DATA_API_KEY"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def parse_json(url):
r = requests.get(url)
if r.status_code == 200:
j = r.json()
for track in j['tracks']['data']:
artist = track['artist']['name']
if artist == None:
tracks.append(u"{0}".format(track['title']))
else:
tracks.append(u"{0} - {1}".format(artist,track['title']))
# Bu fonksiyon neredeyse https://developers.google.com/youtube/v3/code_samples/python buradan
def youtube_search(qterm):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
# Call the search.list method to retrieve results matching the specified
# query term.
search_response = youtube.search().list(
q=qterm,
part="id,snippet",
maxResults=1
).execute()
# Add each result to the appropriate list, and then display the lists of
# matching videos, channels, and playlists.
item = search_response.get("items",[])
if item == []:
return None
else:
url = unicode("http://www.youtube.com/watch?v=%s" % item[0]["id"]["videoId"])
return url
#
def _youtube_search(q, d):
q.put(youtube_search(d))
def download_file(u):
yt = youtube_dl.YoutubeDL({'outtmpl' : '%(id)s', 'format' : 'flv', 'quiet' : True, 'no-progress' : True})
yt.add_default_info_extractors()
result = yt.extract_info(u, download=False)
all_unicode = ''.join(unichr(x) for x in xrange(65536))
valid_chars = '-_.() 0123456789' + ''.join(c for c in all_unicode if unicodedata.category(c)=="Lu" or unicodedata.category(c)=="Ll")
title = ''.join(c for c in unicode(result['title']) if c in valid_chars)
filename = u"flv/{0}.flv".format(title)
try:
r = requests.get(result['url'], stream=True)
file_path = os.path.join(current_directory, filename.encode('utf8'))
with codecs.open(file_path, 'wb+') as f:
for chunk in r.iter_content(chunk_size=32*1024):
if chunk:
f.write(chunk)
f.flush()
print u"Dosya indirildi: {0}".format(result['title'])
return filename.encode('utf8')
except requests.ConnectionError, e:
print u"İnternet bağlantınızda bir sorun var, belki bu hatayı çözmenize yardımcı olabilir: %s" % e
def _download_file(q, url):
q.put(download_file(url))
if os.name == "posix":
ffmpeg_binary = "ffmpeg"
ffmpeg_binary = os.path.join(current_directory, ffmpeg_binary)
elif os.name == "nt":
ffmpeg_binary = "ffmpeg.exe"
ffmpeg_binary = os.path.join(current_directory, ffmpeg_binary)
def _convert_file(filen):
filen = file.split('/')[1]
name = filen.split('.flv')[0]
filen = os.path.join(current_directory, 'flv/' + filen)
out = os.path.join(current_directory, 'mp3/' + name + '.mp3')
call([ffmpeg_binary, "-i", filen, "-f", "mp3", "-ab", "192000", "-vn", out])
def convert_file(q, f):
q.put(_convert_file(f))
if __name__ == '__main__':
print "#=============================================#"
print "# #"
print "# Deezer Playlist to MP3 Player #"
print "# Yusuf Tuğrul Kocaman #"
print "# #"
print "#---------------------------------------------#"
print "# #"
print "# Çalma listesi ID'sini girmeniz yeterlidir. #"
print "# Albümlerde çalışmaz. #"
print "# #"
print "#---------------------------------------------#"
print "# #"
print "# twitter : kulturlupenguen #"
print "# facebook : yusuftugrul.kocaman.1 #"
print "# github : kulturlupenguen #"
print "# blog : penguencik.com #"
print "# #"
print "#---------------------------------------------#"
print
print
print
time.sleep(3)
id = input("Deezer Playlist ID: ")
playlist = "http://api.deezer.com/playlist/%d" % id
parse_json(playlist)
print
songs = Queue.Queue()
for song in tracks:
t = threading.Thread(target=_youtube_search, args=(songs, song)).start()
data = songs.get()
if data != None:
print u"YouTube URL'sine dönüştürüldü: %s --> %s" % (song, data)
urls.append(data)
else:
print u"YouTube URL'sine dönüştürülemedi: %s --> %s" % (song, data)
time.sleep(0.1)
download_list = Queue.Queue()
files = []
for url in urls:
t = threading.Thread(target=_download_file, args=(download_list, url))
t.start()
time.sleep(0.1)
files.append(download_list.get())
print "\n"
converts = Queue.Queue()
for file in files:
t = threading.Thread(target=convert_file, args=(converts, file))
t.start()
print "\n"
time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment