Exemplo n.º 1
0
def verify_song(tweetid,txid,song):
    try:
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth)
        tweet = api.get_status(sys.argv[1])
        if txid in tweet.text:
            if findtxid(txid)[0]["response"][0]["publisher-data"]["alexandria-publisher"]["name"].lower() in tweet.text.lower():
                if 0==sum(1 for x in acoustid.match("Hcspu7zG",song)):
                    print '{"authdata":[{"foundtxid":"True"},{"foundname":"False"},{"verified":"'+str(tweet.user.verified)+'"},{"songmatch":"NotFound"}]}'
                else:
                    for score, recording_id, title, artist in acoustid.match("Hcspu7zG",song):
                        if artist.decode("utf-8").lower() in tweet.text.lower():
                            print '{"authdata":[{"foundtxid":"True"},{"foundname":"True"},{"verified":"'+str(tweet.user.verified)+'"},{"songmatch":"True"}]}'
                            break
                        else:
                            print '{"authdata":[{"foundtxid":"True"},{"foundname":"True"},{"verified":"'+str(tweet.user.verified)+'"},{"songmatch:"False"}]}'
                            break
            else:
                print '{"authdata":[{"foundtxid":"True"},{"foundname":"False"},{"verified":"'+str(tweet.user.verified)+'"},{"songfound":"False"}]}'
        else:
            print '{"authdata":[{"foundtxid":"False"},{"foundname":"False"},{"verified":"'+str(tweet.user.verified)+'"},{"songfound":"False"}]}'

    except Exception,e1:
        print e1
Exemplo n.º 2
0
def match_albums(files):
	res = []
	rel_all = None
	for f in files:
		t = acoustid.match(config.ACOUSTID_APIKEY, f, 'recordingids', parse=False)
		cur = []
		cur_rels = set()
		for i in t['results']:
			if 'recordings' in i:
				for j in i['recordings']:
					if 'id' in j:
						tmp = mb_get_recording(j['id'])
						if tmp is not None:
							cur.append(tmp)
		for i in cur:
			for j in i['releases']:
				cur_rels.add(j['id'])
		res.append(cur)
		if rel_all is None:
			rel_all = cur_rels
		else:
			rel_all &= cur_rels
	resa = []
	for i in rel_all:
		tmp = mb_get_release(i)
		if tmp is not None:
			resa.append(tmp)
	return resa, res
Exemplo n.º 3
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.NoBackendError:
        print("chromaprint library/tool not found", file=sys.stderr)
        sys.exit(1)
    except acoustid.FingerprintGenerationError:
        print("fingerprint could not be calculated", file=sys.stderr)
        sys.exit(1)
    except acoustid.WebServiceError as exc:
        print("web service request failed:", exc.message, file=sys.stderr)
        sys.exit(1)

    first = True
    for score, rid, title, artist in results:
        if first:
            first = False
        else:
            print()
        if sys.argv[2] == 'artist':
            print(artist)
        if sys.argv[2] == 'title':
            print(title)
        #print_('%s - %s' % (artist, title))
        #print_('http://musicbrainz.org/recording/%s' % rid)
        break
        print_('Score: %i%%' % (int(score * 100)))
Exemplo n.º 4
0
def fetch_acoust_id(filename):
    """
    Accepts an absolute or relative file system path as `filename`.

    This function will use the `fpcalc` executable installed on the system to
    generate an acoustic fingerprint, send that fingerprint to the AcoustID
    service (which MusicBrainz) uses on the backend, and yield back a generated
    tuple datatype.

    The yielded generator of tuples is the returned value.
    """

    try:
        results = acoustid.match(API_KEY,
                                 filename,
                                 force_fpcalc=True,
                                 parse=True)
    except acoustid.NoBackendError:
        print("!!!!!!!!!! chromaprint library/tool not found", file=sys.stderr)
        sys.exit(1)
    except acoustid.FingerprintGenerationError:
        print(f"!!!!!!!!!! fingerprint could not be calculated ({filename})",
              file=sys.stderr)
        sys.exit(1)
    except acoustid.WebServiceError as exc:
        print("!!!!!!!!!! web service request failed:",
              exc.message,
              file=sys.stderr)
        sys.exit(1)

    return results
Exemplo n.º 5
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.NoBackendError:
        print("chromaprint library/tool not found", file=sys.stderr)
        sys.exit(1)
    except acoustid.FingerprintGenerationError:
        print("fingerprint could not be calculated", file=sys.stderr)
        sys.exit(1)
    except acoustid.WebServiceError as exc:
        print("web service request failed:", exc.message, file=sys.stderr)
        sys.exit(1)

    row = 1

    # print(list(results))

    for score, rid, title, artist in results:
        if row > 1:
            break

        row = row + 1

        #cmd = "id3v2 --artist=\"" + artist + "\" --song=\"" + title + "\" " + filename
        print('"%s","%s"' % (artist, title))
Exemplo n.º 6
0
    def get_aid(self, file):
        
        data = acoustid.match(AC_API_KEY, file.path)
        
        res = []
        i = 0
        for d in data:
            selected = False
            if i == 0:
                selected = True
            t = {
                 'score': d[0],
                 'id': d[1],
                 'selected': selected,
                 }
            res.append(t)
            i += 1
            

        
        print
        print '### ACOUSTID LOOKUP ###'
        
        print res
        
        print
        print
            
        return res
Exemplo n.º 7
0
    def get_aid(self, file):

        data = acoustid.match(AC_API_KEY, file.path)

        res = []
        i = 0
        for d in data:
            selected = False
            if i == 0:
                selected = True
            t = {
                'score': d[0],
                'id': d[1],
                'selected': selected,
            }
            res.append(t)
            i += 1

        print
        print '### ACOUSTID LOOKUP ###'

        print res

        print
        print

        return res
Exemplo n.º 8
0
def fingerprint(url, acoustid_api_key):
    '''Fingerprint a youtube video'''
    path = None
    try:
        yt = YouTube(url)
        stream = yt.streams.filter(
            only_audio=True).order_by('abr').asc().first()
        with tqdm(total=stream.filesize,
                  desc="Downloading music",
                  disable=config.quiet,
                  leave=False) as pbar:

            def show_progress_bar(stream, chunk, bytes_remaining):
                del stream, bytes_remaining
                pbar.update(len(chunk))

            yt.register_on_progress_callback(show_progress_bar)
            path = stream.download()
        fps = acoustid.match(acoustid_api_key, path)
        for fp in fps:
            print(fp)
            break
    except acoustid.WebServiceError as e:
        logger.error(e)
    finally:
        if path:
            os.remove(path)
Exemplo n.º 9
0
    def get_aid(self, file):

        log = logging.getLogger('importer.process.get_aid')
        log.info('Lookup acoustid for: %s' % (file.path))

        data = acoustid.match(AC_API_KEY, file.path)
        
        res = []
        i = 0
        for d in data:
            selected = False
            if i == 0:
                selected = True
            t = {
                 'score': d[0],
                 'id': d[1],
                 'selected': selected,
                 }

            log.info('acoustid: got result - score: %s | mb id: %s' % (d[0], d[1]))
            if i < 5:
                res.append(t)
            i += 1

        return res
Exemplo n.º 10
0
    def aidmatch(self):
        try:
            results = acoustid.match(self.api_key, self.filename)
        except acoustid.NoBackendError:
            print("chromaprint library/tool not found", file=sys.stderr)
            sys.exit(1)
        except acoustid.FingerprintGenerationError:
            print("fingerprint could not be calculated", file=sys.stderr)
            sys.exit(1)
        except acoustid.WebServiceError as exc:
            print("web service request failed:", exc.message, file=sys.stderr)
            sys.exit(1)

        for score, rid, title, artist in results:
            url = "https://musicbrainz.org/ws/2/recording/{0}?inc=aliases%2Bartist-credits%2Breleases".format(
                rid)
            response = urllib.request.urlopen(url)
            data = response.read()  # a `bytes` object
            text = data.decode(
                'utf-8')  # a `str`; this step can't be used if data is binary
            basename = ntpath.basename(self.filename)
            XML_FILE = pkg_resources.resource_filename(
                'titanium_rhythm',
                os.path.join('song_info', basename[:-4] + '.xml'))
            with open(XML_FILE, 'w') as f:
                print(text, file=f)
Exemplo n.º 11
0
    def get_aid(self, file):

        print "### GET AID START"
        

        log = logging.getLogger('importer.process.get_aid')
        log.info('Lookup acoustid for: %s' % (file.path))
        
        
        data = acoustid.match(AC_API_KEY, file.path)
        
        res = []
        i = 0
        for d in data:
            selected = False
            if i == 0:
                selected = True
            t = {
                 'score': d[0],
                 'id': d[1],
                 'selected': selected,
                 }

            log.info('got result - score: %s | mb_id: %s' % (d[0], d[1]))
            res.append(t)
            i += 1

        print "### GET AID END"

        print '** RES:'
        print res
        print

        return res
Exemplo n.º 12
0
def fingerprint(url, acoustid_api_key):
    yt_path = "intermediate.mp3"
    ydl_opts = {
        'format':
        'bestaudio/best',
        'quiet':
        True,
        'no_warnings':
        True,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
        'outtmpl':
        yt_path,
    }
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.extract_info(url, download=True)
            yt_ids = acoustid.match(acoustid_api_key, yt_path)
            for _, recording_id, _, _ in yt_ids:
                print(recording_id)
                break
    except youtube_dl.utils.DownloadError as e:
        logger.error(e)
    except acoustid.WebServiceError as e:
        logger.error(e)
Exemplo n.º 13
0
def acoustid_search():
    util.print_message('Analyzing audio fingerprint...')
    try:
        search = list(
            acoustid.match(conf.ACOUSTID_API_KEY,
                           conf.YOUTUBE_DL_OPTS['outtmpl']))
    except acoustid.NoBackendError:
        util.print_message('ERROR: Chromaprint library/tool not found.',
                           color='red',
                           exit=True)
    except acoustid.FingerprintGenerationError:
        util.print_message('ERROR: Audio fingerprint could not be calculated.',
                           color='red',
                           exit=True)
    except acoustid.WebServiceError as exc:
        util.print_message('ERROR: Web service request failed: {}.' \
                           .format(exc.message), color='red', exit=True)
    except Exception as ecx:
        util.print_message('ERROR: {}'.format(ecx.args[1]),
                           color='red',
                           exit=True)
    if len(search) == 0:
        util.print_message(
            'Failed to find a match for your track in the '
            'MusicBrainz database.',
            color='red',
            exit=True)
    return get_first_valid_encoding(sorted(search, reverse=True))
Exemplo n.º 14
0
    def get_aid(self, file):
        

        log = logging.getLogger('importer.process.get_aid')
        log.info('Lookup acoustid for: %s' % (file.path))
        
        
        data = acoustid.match(AC_API_KEY, file.path)
        
        res = []
        i = 0
        for d in data:
            selected = False
            if i == 0:
                selected = True
            t = {
                 'score': d[0],
                 'id': d[1],
                 'selected': selected,
                 }

            log.info('got result - score: %s | mb_id: %s' % (d[0], d[1]))
            res.append(t)
            i += 1

        return res
Exemplo n.º 15
0
 def get_aid(self, file):
     
     data = acoustid.match(AC_API_KEY, file.path)
     
     res = []
     
     for d in data:
         t = {
              'score': d[0],
              'id': d[1],
              }
         res.append(t)
         
     return res
         
         
     """
     http://musicbrainz.org/ws/2/recording/3ba40ab9-fcfa-450c-8318-e0de8247948c?inc=artist-credits%2Breleases
     """
     
     #r = requests.get('http://musicbrainz.org/ws/2/recording/3ba40ab9-fcfa-450c-8318-e0de8247948c?inc=artist-credits%2Breleases')
     
     #print r.text
     
     #tree = ET.fromstring(r.text)
     
     
     #print tree
     #print pesterfish.to_pesterfish(tree)
     
     
     
     
     
Exemplo n.º 16
0
 def fingerprint(self, api_key: str) -> str:
     ids = acoustid.match(api_key, self.path)
     for score, recording_id, title, artist in ids:
         logger.info(f"{self} score : {score} | recording_id : {recording_id} | title : {title} | artist : {artist}")
         return str(recording_id)
     logger.info(f'{self} : fingerprint cannot be detected')
     return ''
def get_file_details(files):  # get details from acoustid, with acoustid.match
    artists = []
    titles = []
    for score, recording_id, title, artist in match(api_key, files):
        artists.append(artist)
        titles.append(title)

    return artists, titles
Exemplo n.º 18
0
 def _topresult(self,
                filename):  # Use acoustID Webservice for basic information
     results = acoustid.match(self.acoustid_apikey, filename)
     try:
         for score, recording_id, title, artist in results:
             return (title, artist, score)
     except TypeError:  # If we could not identify a match with MusicBrains
         return None
Exemplo n.º 19
0
def get_musicbrainz_id(musicfile: MusicFile):
    score_cache = 0

    for score, recording_id, title, artist in acoustid.match(
            apikey, musicfile.file_path):
        if score > score_cache:
            musicfile.musicbrainz_id = recording_id
            score_cache = score
Exemplo n.º 20
0
 def fingerprint(self, api_key):
     import acoustid
     ids = acoustid.match(api_key, self.path)
     for score, recording_id, title, artist in ids:
         logger.info(
             "score : %s | recording_id : %s | title : %s | artist : %s",
             score, recording_id, title, artist)
         return recording_id
     return None
Exemplo n.º 21
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.FingerprintGenerationError:
        print >> sys.stderr, "fingerprint could not be calculated"
        sys.exit(1)
    except acoustid.WebServiceError, exc:
        print >> sys.stderr, "web service request failed:", exc.message
        sys.exit(1)
Exemplo n.º 22
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.FingerprintGenerationError:
        print >>sys.stderr, "fingerprint could not be calculated"
        sys.exit(1)
    except acoustid.WebServiceError, exc:
        print >>sys.stderr, "web service request failed:", exc.message
        sys.exit(1)
Exemplo n.º 23
0
def find(path, acoustid_api_key):
    f = File(path)
    yt_path = f"{f.artist} - {f.title}.mp3"
    try:
        file_id = f.fingerprint(acoustid_api_key)
        print(
            f'Searching for artist {f.artist} and title {f.title} and duration {humanize.naturaltime(f.duration)}'
        )
        ydl_opts = {
            'format':
            'bestaudio/best',
            'quiet':
            True,
            'cachedir':
            False,
            'no_warnings':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
            'outtmpl':
            yt_path,
        }
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            infos = ydl.extract_info(f"ytsearch1:'{f.artist} {f.title}'",
                                     download=True)
            url = None
            for entry in infos['entries']:
                url = entry['webpage_url']
                break

            yt_ids = acoustid.match(acoustid_api_key, yt_path)
            yt_id = None
            for _, recording_id, _, _ in yt_ids:
                yt_id = recording_id
                break
            if file_id == yt_id:
                print(f'Found: fingerprint {file_id} | url {url}')
            else:
                print(
                    f'Not exactly found: fingerprint file: {file_id} | yt: {yt_id} | url {url}'
                )
                print(f'Based only on duration, maybe: {url}')
    except acoustid.WebServiceError as e:
        logger.error(e)
    except youtube_dl.utils.DownloadError as e:
        logger.error(e)
    finally:
        try:
            if yt_path:
                os.remove(yt_path)
        except OSError:
            logger.warning(f"File not found: {yt_path}")
Exemplo n.º 24
0
def aidmatch(filename, callback):
    results = iter(())
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.NoBackendError:
        print("chromaprint library/tool not found") 
    except acoustid.FingerprintGenerationError:
        print("fingerprint could not be calculated")
    except acoustid.WebServiceError as exc:
        print("web service request failed:")

    callback(results)
Exemplo n.º 25
0
 def initializeOnlineMetadata(self):
     """
     Fills up fpresults with online metadata so it can be later used.
     """
     try:
         self.fpresults = list(acoustid.match(api_key, self.path))
     except acoustid.NoBackendError:
         logger(paths['log'], "ERROR: chromaprint library/tool not found")
     except acoustid.FingerprintGenerationError:
         logger(paths['log'], "ERROR: fingerprint could not be calculated")
     except acoustid.WebServiceError as exc:
         logger(paths['log'], ("ERROR: web service request failed: %s" % exc.message))
Exemplo n.º 26
0
def acoustid_match(path, metadata=None):
    """Gets metadata for a file from Acoustid. Returns a recording ID
    and a list of release IDs if a match is found; otherwise, returns
    None.
    """
    try:
        res = acoustid.match(API_KEY, path, meta='recordings releases',
                             parse=False)
    except acoustid.AcoustidError, exc:
        log.debug('fingerprint matching %s failed: %s' % 
                  (repr(path), str(exc)))
        return None
Exemplo n.º 27
0
 def _identify(self, overwrite):
     if overwrite:
         possibilities = list(acoustid.match(ACOUSTID_KEY, self.path))
         if len(possibilities) == 0:
             self._get_info_from_metadata()
         else:
             score, mbid, title, artist = possibilities[0]
             self.title = xtitle(title)
             self.artist = xtitle(artist)
             self.mbid = mbid
     if not self._get_info_from_metadata(verbose=False):
         self._identify(True)
Exemplo n.º 28
0
    def getFingerprintedData(self, path):
        if "acoustid" not in sys.modules:
            return False

        finalDict = {
            "artist": [],
            "title": [],
            "musicbrainz_releasetrackid": [],
            "Artist": None,
            "Title": None,
            "Release Track ID (MB)": None,
        }

        artistCompare = []
        artistList = []
        resultList = acoustid.match(self.clientId, path, parse=False)

        if resultList and "status" in resultList:
            if resultList["status"] == "ok":
                for item in resultList["results"]:
                    if "recordings" in item:
                        for i, result in enumerate(item["recordings"]):
                            if "artists" in result:
                                for artist in result["artists"]:
                                    artistList.append(artist["name"])
                                artistCompare.append(', '.join(artistList))
                                artistList.clear()
                                if i == 10:
                                    break

        potentialArtist = self.mostCommon(artistCompare)

        #choosing the most frequent result in top 10
        joinWord = ", "
        for item in resultList["results"]:
            if "recordings" in item:
                for result in item["recordings"]:
                    if "artists" in result:
                        for artist in result["artists"]:
                            artistList.append(artist["name"])
                            if "joinphrase" in artist:
                                joinWord = artist["joinphrase"]
                        if ', '.join(artistList) == potentialArtist:
                            finalDict["Artist"] = joinWord.join(artistList)
                            finalDict["Title"] = result["title"]
                            finalDict["Release Track ID (MB)"] = result["id"]
                            finalDict["artist"].append(' '.join(artistList))
                            finalDict["title"].append(result["title"])
                            finalDict["musicbrainz_releasetrackid"].append(
                                result["id"])
                            return finalDict
                        artistList.clear()
        return False
Exemplo n.º 29
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.NoBackendError:
        print("chromaprint library/tool not found")
    except acoustid.FingerprintGenerationError:
        print("fingerprint could not be calculated")
    except acoustid.WebServiceError as exc:
        print("web service request failed:", exc.message)
    else:
        for score, rid, title, artist in results:
            return rid
Exemplo n.º 30
0
def acoustid_match(path, metadata=None):
    """Gets metadata for a file from Acoustid. Returns a recording ID
    and a list of release IDs if a match is found; otherwise, returns
    None.
    """
    try:
        res = acoustid.match(API_KEY,
                             path,
                             meta='recordings releases',
                             parse=False)
    except acoustid.FingerprintGenerationError, exc:
        log.error('fingerprinting of %s failed: %s' % (repr(path), str(exc)))
        return None
Exemplo n.º 31
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.NoBackendError:
        print "chromaprint library/tool not found"
        sys.exit(1)
    except acoustid.FingerprintGenerationError:
        print "fingerprint could not be calculated"
        sys.exit(1)
    except acoustid.WebServiceError as exc:
        print "web service request failed:", exc.message
        sys.exit(1)
    return results
Exemplo n.º 32
0
def fingerprint(thefile):
    attempt = 0
    success = False
    while not success and attempt < RETRIES:
        try:
            matches = acoustid.match(config.ACOUSTID_KEY, thefile)
            success = True
        except acoustid.WebServiceError as e:
            time.sleep(1)
            attempt += 1

    if success:
        return list(matches)
    return []
Exemplo n.º 33
0
def augment_with_musicbrainz_metadata(song):
    meta = 'recordings releases'
    try:
        data = acoustid.match(config.acoustid_api_key,
                              song.path,
                              meta=meta,
                              parse=False)
        if data.get('status') != 'ok':
            raise WebServiceError("status not ok")
        if not isinstance(data.get('results'), list):
            raise WebServiceError("invalid results")
        song.mb_metadata = data['results']
        L.debug(f"Augmented {song} with MusicBrainz metadata")
    except WebServiceError as e:
        L.exception("Failed to fetch MusicBrainz metadata")
Exemplo n.º 34
0
def get_song_info(file_path, title, artist, album, link):
    album = 'Youtube' if album is None else album
    if not title or not artist:
        match = acoustid.match(acoustid_api_key, file_path)
        try:
            result = match.next()
            artist = result[3] if artist is None else artist
            title = result[2] if title is None else title
        except:
            print("Unable to match via AcoustID! Falling back to video title")
            artist = 'Unknown' if artist is None else artist
            title = get_youtube_title(link) if title is None else title
    vprint("Found song info:\n" + "    Artist: %s\n" % artist +
           "    Title: %s\n" % title + "    Album: %s" % album)
    return [title, artist, album]
Exemplo n.º 35
0
    def get_aid(self, file):

        data = acoustid.match(AC_API_KEY, file.path)

        res = []

        for d in data:
            t = {
                'score': d[0],
                'id': d[1],
            }
            res.append(t)

        return res
        """
Exemplo n.º 36
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.NoBackendError:
        print("chromaprint library/tool not found", file=sys.stderr)
        sys.exit(1)
    except acoustid.FingerprintGenerationError:
        print("fingerprint could not be calculated", file=sys.stderr)
        sys.exit(1)
    except acoustid.WebServiceError as exc:
        print("web service request failed:", exc.message, file=sys.stderr)
        sys.exit(1)
    #print(results)
    #first = True
    for score, rid, title, artist in results:
        return artist, title
Exemplo n.º 37
0
def find(path, acoustid_api_key, youtube_api_key):
    '''Search a youtube link with artist and title'''
    f = File(path)
    try:
        file_id = f.fingerprint(acoustid_api_key)
        print(
            f'Searching for artist {f.artist} and title {f.title} and duration {format_timespan(f.duration)}'
        )
        urls = youtube.search(youtube_api_key, f.artist, f.title, f.duration)
        for url in urls:
            yt_path = None
            try:
                yt = YouTube(url)
                for stream in yt.streams.filter(only_audio=True):
                    with tqdm(total=stream.filesize,
                              desc=f"Testing {url}",
                              disable=config.quiet,
                              leave=False) as pbar:

                        def show_progress_bar(stream, chunk, bytes_remaining):
                            del stream, bytes_remaining
                            pbar.update(len(chunk))  # pylint: disable=cell-var-from-loop

                        yt.register_on_progress_callback(show_progress_bar)
                        yt_path = stream.download()
                        break
                yt_ids = acoustid.match(acoustid_api_key, yt_path)
                yt_id = None
                for _, recording_id, _, _ in yt_ids:
                    yt_id = recording_id
                    break
                if file_id == yt_id:
                    print(f'Found: fingerprint {file_id} | url {url}')
                    break
                if yt_id is not None:
                    print(
                        f'Not exactly found: fingerprint file: {file_id} | yt: {yt_id} | url {url}'
                    )
                    break
                print(f'Based only on duration, maybe: {url}')
            except VideoUnavailable:
                pass
            finally:
                if yt_path:
                    os.remove(yt_path)
    except acoustid.WebServiceError as e:
        logger.error(e)
Exemplo n.º 38
0
def get_song_info(file_path, title, artist, album, link):
    album = 'Youtube' if album is None else album
    if not title or not artist:
        match = acoustid.match(acoustid_api_key, file_path)
        try:
            result = match.next()
            artist = result[3] if artist is None else artist
            title = result[2] if title is None else title
        except:
            print("Unable to match via AcoustID! Falling back to video title")
            artist = 'Unknown' if artist is None else artist
            title = get_youtube_title(link) if title is None else title
    vprint("Found song info:\n" +
           "    Artist: %s\n" % artist +
           "    Title: %s\n" % title +
           "    Album: %s" % album)
    return [title, artist, album]
Exemplo n.º 39
0
    def get_aid(self, file):

        log.info('lookup acoustid for: %s' % (file.path))

        try:

            data = acoustid.match(AC_API_KEY, file.path)

            res = []
            i = 0
            for d in data:
                selected = False
                if i == 0:
                    selected = True
                t = {
                    'score': d[0],
                    'id': d[1],
                    'selected': selected,
                }

                if i < LIMIT_AID_RESULTS:
                    log.debug(
                        'acoustid: got result (loop: %s) - score: %s | mb id: %s'
                        % (i, d[0], d[1]))
                    if i < 1:
                        res.append(t)
                    else:
                        # only append further releases if score is high enough
                        if float(d[0]) > AID_MIN_SCORE:
                            res.append(t)
                        else:
                            log.debug(
                                'skipping acoustid, score %s < %s (AID_MIN_SCORE)'
                                % (float(d[0]), AID_MIN_SCORE))

                else:
                    pass
                    #log.debug('skipping acoustid, we have %s of them' % i)
                i += 1

            log.info('got %s possible matches via acoustid' % len(res))

            return res

        except:
            return None
Exemplo n.º 40
0
    def get_aid(self, file):

        log.info('lookup acoustid for: %s' % (file.path))

        try:

            data = acoustid.match(AC_API_KEY, file.path)

            res = []
            i = 0
            for d in data:
                selected = False
                if i == 0:
                    selected = True
                t = {
                     'score': d[0],
                     'id': d[1],
                     'selected': selected,
                     }


                if i < LIMIT_AID_RESULTS:
                    log.debug('acoustid: got result (loop: %s) - score: %s | mb id: %s' % (i, d[0], d[1]))
                    if i < 1:
                        res.append(t)
                    else:
                        # only append further releases if score is high enough
                        if float(d[0]) > AID_MIN_SCORE:
                            res.append(t)
                        else:
                            log.debug('skipping acoustid, score %s < %s (AID_MIN_SCORE)' % (float(d[0]), AID_MIN_SCORE))

                else:
                    pass
                    #log.debug('skipping acoustid, we have %s of them' % i)
                i += 1

            log.info('got %s possible matches via acoustid' % len(res))


            return res

        except:
            return None
Exemplo n.º 41
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.FingerprintGenerationError:
        print >>sys.stderr, "fingerprint could not be calculated"
        sys.exit(1)
    except acoustid.WebServiceError:
        print >>sys.stderr, "web service request failed"
        sys.exit(1)

    first = True
    for score, rid, title, artist in results:
        if first:
            first = False
        else:
            print
        print '%s - %s' % (artist, title)
        print 'http://musicbrainz.org/recording/%s' % rid
        print 'Score: %i%%' % (int(score * 100))
Exemplo n.º 42
0
 def guess_sound(self):
     if 'title' in self and 'artist' in self:
         logging.debug("We already have title and artist for this one")
         return
     logging.debug(self.path)
     logging.debug(ACOUSTID_KEY)
     try:
         match = acoustid.match(ACOUSTID_KEY, self.path)
     except:
         return
     for score, recording_id, title, artist in match:
         if score > 0.99:
             #we are quite sure this result match
             logging.debug("Match Found score:%s, title:%s, artist:%s",
             score, title, artist)
             self['title'] = title
             self['artist'] = artist
         else:
             #the result are not sure enough
             logging.debug("The result doesn't seems sure enough.")
Exemplo n.º 43
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.NoBackendError:
        print("chromaprint library/tool not found", file=sys.stderr)
        sys.exit(1)
    except acoustid.FingerprintGenerationError:
        print("fingerprint could not be calculated 1", file=sys.stderr)
        sys.exit(1)
    except acoustid.WebServiceError as exc:
        print("web service request failed:", exc.message, file=sys.stderr)
        sys.exit(1)

    final_results=[]

    first = True
    for score, rid, title, artist in results:
        if first:
            first = False
        else:
            pass
        t1= artist 
        t2= title
        t3= rid
        t4= int(score * 100)

        final_results.append([t1, t2, t3, t4])
        #print('%s - %s' % (artist, title))
        #print('http://musicbrainz.org/recording/%s' % rid)
        #print('Score: %i%%' % (int(score * 100)))

    print(final_results)

    score_sheet = []
    highest_score = final_results[0][3]

    for elt in final_results:
        if elt[3] == highest_score:
            score_sheet.append(elt)

    return score_sheet 
Exemplo n.º 44
0
def match_song(duration, filename):
    """return artist and title of song in filename"""
    
    if FP_SERVICE == "acoustid":
        try:
            results = acoustid.match(ACOUSTID_API_KEY, filename)
        except:
            return (None, None)
        try:
            score, recording_id, title, artist = results.next()
            return Song(artist=artist, title=title)
        except:
            return (None, None)
    elif FP_SERVICE == "echonest":
        try:
            results = ensong.identify(filename,
                codegen_duration=duration, codegen_start=0)
            song = results[0]
            return Song(artist=song.artist_name, title=song.title)
        except:
            return (None, None)
    return (None, None)
Exemplo n.º 45
0
def aidmatch(filename):
    try:
        results = acoustid.match(API_KEY, filename)
    except acoustid.NoBackendError:
        print("chromaprint library/tool not found", file=sys.stderr)
        sys.exit(1)
    except acoustid.FingerprintGenerationError:
        print("fingerprint could not be calculated", file=sys.stderr)
        sys.exit(1)
    except acoustid.WebServiceError as exc:
        print("web service request failed:", exc.message, file=sys.stderr)
        sys.exit(1)

    first = True
    for score, rid, title, artist in results:
        if first:
            first = False
        else:
            print()
        print_('%s - %s' % (artist, title))
        print_('http://musicbrainz.org/recording/%s' % rid)
        print_('Score: %i%%' % (int(score * 100)))
Exemplo n.º 46
0
def find(path, acoustid_apikey):
    '''Search a youtube link with artist and title'''
    f = File(path)
    file_id = f.fingerprint(acoustid_apikey)

    print('Searching for artist {} and title {} and duration {}'.format(f.artist, f.title, format_timespan(f.duration)))
    urls = youtube.search(f.artist, f.title, f.duration)
    for url in urls:
        yt_path = None
        try:
            yt = YouTube(url)
            for stream in yt.streams.all():
                with tqdm(total=stream.filesize, desc="Testing {}".format(url), disable=config.quiet, leave=False) as pbar:
                    def show_progress_bar(stream, chunk, file_handle, bytes_remaining):
                        pbar.update(len(chunk))
                    yt.register_on_progress_callback(show_progress_bar)
                    yt_path = stream.download()
                    break
            yt_ids = acoustid.match(acoustid_apikey, yt_path)
            yt_id = None
            for _, recording_id, _, _ in yt_ids:
                yt_id = recording_id
                break
            if file_id == yt_id:
                print('Found: fingerprint {} | url {}'.format(file_id, url))
                break
            elif yt_id is not None:
                print('Not exactly found: fingerprint file: {} | yt: {} | url {}'.format(file_id, yt_id, url))
                break
            else:
                print('Based only on duration, maybe: {}'.format(url))
            # break
        except VideoUnavailable:
            pass
        finally:
            if yt_path:
                os.remove(yt_path)
Exemplo n.º 47
0
def return_meta(path):
        mbid = None
        title = None
        info=list(acoustid.match('MZMS6Rw8O0', path))
        if ((len(info) != 0) and (len(info[0]) != 0)):
                mbid=info[0][1]
                title=info[0][2]
                artist=info[0][3]
        album = None
        position = None
        urlhead = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=a0a2dc22c307a2dd5b69051883706a65&mbid="
        urltail = "&format=json"
        if mbid is None:
                return [None, None, None, None]
        json = (requests.get(urlhead + mbid + urltail)).json()	
        if json.get('error'):
                return [artist, None, title, None]
        if ("track" not in json.keys()):
                album = None
                position=None
                return [artist,album,title,position]
        if("album" not in json["track"].keys()):
                album = None
                position=None
                return [artist,album,title,position]
        if("title" not in json["track"]["album"].keys()):
                album = None
        else:
                album = json["track"]["album"]["title"]
        if("@attr" not in json["track"]["album"].keys()):
                position = None
        elif("position" not in json["track"]["album"]['@attr'].keys()):
                position = None
        else:
                position = json["track"]["album"]['@attr']['position']
        return [artist,album,title,position]
Exemplo n.º 48
0
def ProcessFile(track, status, br):

    def del_temp():
        print '[Deleting other candidates]'
        for item in glob.glob('[1-9]*.mp3'):
            print '  ...%s' % item.split()[0]
            os.remove(item)
        print 'Done.'
        return True

    id3tags = (track[0], # Track Number
               track[1], # Song Name
               status['artist'], # Artist
               status['album'], # Album Name
               status['year'], # Year
               status['tag'], # Artist Tag
               '' # Comment
              )
    filename = sysname.sub('', '[%s] %s - %s.mp3' % (track[0], status['artist'], track[1]))

    del_temp()

    if os.path.exists(filename):
        print 'File already exists, skipping..'
        return True

    links = get_links(status['artist'], track[1], int(track[2]), br, status['listsize'], status['timerange'])

    if not links: return None

    download_threads = []
    rated_files = []
    file_index = 1

    for item in links:
        download_file = u'%d %s' % (file_index, filename)
        download_threads.append(threading.Thread(target = downloadFile, args=(item[3], download_file)))
        file_index += 1

    print '[...Downloading Candidate Files...]'
    map(lambda x: x.start(), download_threads)
    map(lambda x: x.join(), download_threads)
    print '[Done]\n'

    for mp3_file in glob.glob('[1-9]*.mp3'):
        deleteTag(mp3_file)
        acousticId = list(acoustid.match('FDaQARn2', mp3_file.encode("UTF-8")))
        print acousticId
        if acousticId:
            rated_files.append([mp3_file, acousticId[0][0] * 100.0, acousticId[0][3], acousticId[0][2], item[1]])
        else:
            os.remove(mp3_file)

    if rated_files:
        print rated_files
        for file in rated_files:
            prefix = file[0].split()[0]
            if file[1] >= status['score']:
                os.rename(file[0], filename)
                writeTag(filename, id3tags)
                del_temp()
                return True

        file = sorted(rated_files, key = lambda x: x[1])[::-1][0]

        os.rename(file[0], filename)
        writeTag(filename, id3tags)
        del_temp()
        return True
    else: print 'Something really bad happened!'
Exemplo n.º 49
0
 def fingerprint(api_key, self):
     import acoustid
     ids = acoustid.match(api_key, self.path)
     for _, recording_id, _, _ in ids:
         return recording_id
     return None
Exemplo n.º 50
0
# Download Chromaprint dymaic libriary or command line tool (fpcac): https://acoustid.org/chromaprint
# If using fpcalc command line tool, add the Chromaprint fcalc.exe location to the path, or change FPCALC_ENVVAR to the install location (C:\python\lib\site-packages)
# Download and install pyacoustid Python Bindings: pip install pyacoustid
# An audio decoder is needed, such as FFmeg, GStreamer with PyGObject, MAD with pymad

import acoustid

apikey = "8GXrGT5g"

metatags = ["recordings", "recordingids", "releases", "releaseids", "releasegroups", "releasegroupids", "tracks", "compress", "usermeta", "sources"]

path = r"C:\Users\Sean O'Connor\Downloads\MP4 test\MP3s\Rootbeer - Under Control - Copy.mp3"

for meta in metatags:
    print(acoustid.match(apikey, path, meta=meta, parse=False))
Exemplo n.º 51
-30
def fingerprint(url, acoustid_apikey):
    '''Fingerprint a youtube video'''
    yt = YouTube(url)
    stream = yt.streams.filter(progressive=True).order_by('abr').asc().first()
    with tqdm(total=stream.filesize, desc="Downloading music", disable=config.quiet, leave=False) as pbar:
        def show_progress_bar(stream, chunk, file_handle, bytes_remaining):
            pbar.update(len(chunk))
        yt.register_on_progress_callback(show_progress_bar)
        path = stream.download()
    fps = acoustid.match(acoustid_apikey, path)
    for fp in fps:
        print(fp)
        break