Пример #1
0
def findCurrentRoute(latitude, longitude, direction):
    """
    Find current route by current location and direction
    """
    input = request.get_json()
    currentCoordinate = Track(latitude, longitude, 0)

    mycursor.execute("SELECT * FROM route")
    routeList = mycursor.fetchall()

    minDistance = float("inf")
    pivotCooridnate = Track(0, 0, 0)
    pivotDirection = 0
    # loop in all available routes
    for route in routeList:
        fixedPoint = Track(route[1], route[2], route[4])
        distance = fixedPoint.findDistance(currentCoordinate)
        # find the route with minimum distance to current location
        if distance < minDistance:
            minDistance = distance
            pivotCooridnate = fixedPoint
            pivotDirection = route[3]
    angleDifference = findAcuteAngle(direction, pivotDirection)
    # if route direction also whithin current direction
    if angleDifference <= 90:
        selectedRoute = pivotCooridnate.track_id
    else:
        # if route direction opposite the the current direction
        selectedRoute = findReverseRoute(pivotCooridnate.track_id)
    print('Selected current route: ' + str(selectedRoute))
    return selectedRoute
Пример #2
0
 def from_file(cls, file_path: str) -> 'TracksList':
     """Import tracks from file."""
     tracks = []
     with open(file_path, 'r', encoding='utf8') as file:
         for line in file.readlines():
             tracks.append(Track.from_string(line.strip()))
     return cls(tracks=tracks)
Пример #3
0
 def fetch(self, ids):
     assert type(ids) is list
     if not ids: return []
     result = self.client.videos().list(
         part='id,snippet,contentDetails,statistics',
         id=','.join(ids)).execute()
     tracks = []
     for item in result.get('items', []):
         try:
             track = Track(
                 provider=YoutubeController.PROVIDER,
                 contentId=item['id'],
                 accountId=item['snippet']['channelId'],
                 accountName=item['snippet']['channelTitle'],
                 title=item['snippet']['title'],
                 description=item['snippet']['description'],
                 playbackCount=int(item['statistics']['viewCount']),
                 likesCount=int(item['statistics']['likeCount']),
                 duration=isodate.parse_duration(
                     item['contentDetails']['duration']).seconds * 1000,
                 thumbnailSmall=item['snippet']['thumbnails'].get(
                     'default', {'url': ''})['url'],
                 thumbnailMedium=item['snippet']['thumbnails'].get(
                     'medium', {'url': ''})['url'],
                 thumbnailLarge=item['snippet']['thumbnails'].get(
                     'standard', {'url': ''})['url'],
             )
         except (KeyError, ValueError) as e:
             print(e)
             continue
         tracks.append(track)
     return tracks
Пример #4
0
    def get_tracks(self) -> TracksList:
        """Get all tracks of current user."""
        tracks = []
        offset = 0

        pb = tqdm(desc='Export tracks')
        while tqdm:
            resp = self.api.audio.get(
                count=100,
                offset=offset,
            )

            items = resp['items']
            total = resp['count']
            pb.total = total

            if not items:
                break

            offset += len(items)

            for item in items:
                tracks.append(Track(
                    artist=item.get('artist'),
                    title=item.get('title'),
                ))
                pb.update()

            time.sleep(0.34)

        pb.close()
        return TracksList(tracks)
Пример #5
0
 def parse_result(self, result):
     tracks = []
     for item in result['collection']:
         try:
             track = Track(
                 provider=SoundcloudController.PROVIDER,
                 contentId=str(item['id']),
                 accountId=str(item['user']['id']),
                 accountName=item['user']['username'],
                 title=item['title'],
                 description=item['description'],
                 playbackCount=int(item['playback_count']),
                 likesCount=int(item['likes_count']),
                 duration=int(item['duration']),
                 thumbnailSmall=self.get_thumburl(item['artwork_url'],
                                                  'small'),
                 thumbnailMedium=self.get_thumburl(item['artwork_url'],
                                                   'medium'),
                 thumbnailLarge=self.get_thumburl(item['artwork_url'],
                                                  'large'),
             )
         except (KeyError, ValueError) as e:
             print(e)
             continue
         tracks.append(track)
     return tracks
def get_candidate_tracks(client, query_string, num_results=25):
    results = client.search(query_string, limit=num_results)
    candidate_tracks = [
        Track(item, item['name'], item['artists'][0]['name'],
              item['album']['name'], item['uri'])
        for item in results['tracks']['items']
    ]
    return candidate_tracks
Пример #7
0
    def get(self, genre):
        try:
            if genre not in self.genre_dict:
                raise InvalidArgument('Invalid genre')

            artists = self.genre_dict[genre]
            selected = random.randrange(0, len(artists))
            return Track.get_top5_tracks_by_artists(artists[selected])
        except InvalidArgument as e:
            abort(400, message=str(e))
        except ResourceNotFound as e:
            abort(404, message='Resource Not Found')
        except e:
            abort(500, message='Unknown Error')
Пример #8
0
def read_backup(playlist_name):
    with open(f'backup/{playlist_name}') as f:
        lines = f.readlines()

        playlist_json = json.loads(lines[0])
        playlist = PlaylistMetadata(playlist_json['name'],
                                    playlist_json['uri'],
                                    playlist_json['length'])

        tracks = list(
            map(
                lambda l: Track(l['complete'], l['name'], l['artist'], l[
                    'album'], l['uri']),
                (json.loads(line) for line in lines[1:])))

    return playlist, tracks
def fetch_tracks(client, username, playlist):
    tracks = []
    uri = playlist.uri
    total = playlist.length
    offset = 0

    while offset < total:
        playlist_tracks = client.user_playlist_tracks(username,
                                                      uri,
                                                      offset=offset)
        tracks.extend(
            Track(item['track'], item['track']['name'], item['track']
                  ['artists'][0]['name'], item['track']['album']['name'],
                  item['track']['uri']) for item in playlist_tracks['items'])
        offset += 100

    return tracks
def normalise_tracks(tracks, transformations):
    normalised = []

    for track in tracks:
        for transformation in transformations:
            track = transformation.apply(track)

        name = track.name
        name = re.sub(FEATURING, "", name)
        name = re.sub(REMASTERED, "", name)

        for removal in REMOVALS:
            name = name.replace(removal, "")

        normalised.append(
            Track(track.complete, name, track.artist, track.album, track.uri))

    return normalised
Пример #11
0
def create_track(album_id, request, base_url):
    if not verify_data(request=request):
        return jsonify({'message': 'input inválido'}), 400
    if len(album_id) == 0:
        return jsonify({'message': 'input inválido'}), 400
    json = request.get_json(force=True)
    if json.get('name') is None or json.get('duration') is None:
        return jsonify({'message': 'input inválido'}), 400
    possible_album = Album.query.filter_by(id=album_id).first()
    if possible_album is None:
        return jsonify({'message': 'álbum no existe'}), 422
    album = possible_album
    track_name = json['name']
    track_id = b64encode(f'{track_name}:{album.id}'.encode()).decode('utf-8')
    track_id = truncate_id(track_id)
    possible_track = Track.query.filter_by(id=track_id).first()
    if possible_track is None:
        track = Track.create(track_id=track_id,
                             album_id=album_id,
                             name=json['name'],
                             duration=json['duration'],
                             base_url=base_url)
        return jsonify(track.json()), 201
    return jsonify(possible_track.json()), 409
Пример #12
0
    help_string = f'\nThat wasn\'t an option, dummy. Select a number between 1 and {num_options}\n'

    try:
        result = int(prompt(prompt_string))
    except ValueError:
        # Just let the error get printed once below
        pass

    while result < 1 or result > num_options:
        print(help_string)

        try:
            result = int(prompt(prompt_string))
        except ValueError:
            pass

    return result


if __name__ == '__main__':
    o = Track({}, 'a', 'b', 'c')
    opt = [
        {},
        Track({}, 'a', 'B', 'c'),
        Track({}, 'A', 'BB', 'cccc'),
        Track({}, 'A', 'dsadsad', 'ewq'),
        Track({}, 'A', 'BB', 'dsa'),
        Track({}, 'ewqsaA', 'BB', 'cccc'),
    ]
    prompt_for_input(o, opt)
def cron_job():
    if run_cron == 1:
        tags_payload = {
            "method": "tag.getTopTags",
            "api_key": API_KEY,
            "format": "json"
        }
        i = 0
        top_tags = deserializer(requests.get(BASE_URL, params=tags_payload))
        tags_lst = top_tags['toptags']['tag']
        db_session.add_all(
            [Tag(tag=item['name'], tag_rank=i + 1) for item in tags_lst[:15]])
        db_session.commit()

        for key, value in MUSIC.items():
            for item in tags_lst[:15]:
                payload = {
                    "method": value,
                    "tag": item['name'],
                    "api_key": API_KEY,
                    "format": "json"
                }

                top = deserializer(requests.get(BASE_URL, params=payload))

                if key == "artist":
                    first_key = "top" + key + "s"
                    top_item = top[first_key][key]
                    db_session.add_all([
                        Artist(tag=item['name'],
                               artist_rank=next_item['@attr']['rank'],
                               artist_mbid=next_item.get('mbid', 'None'),
                               artist_name=next_item['name'],
                               streamable=next_item['streamable'],
                               url=next_item['url'])
                        for next_item in top_item[:30]
                    ])

                if key == "album":
                    first_key = key + "s"
                    top_item = top[first_key][key]
                    db_session.add_all([
                        Album(tag=item['name'],
                              album_rank=next_item['@attr']['rank'],
                              album_name=next_item['name'],
                              album_mbid=next_item.get('mbid', 'None'),
                              artist_name=next_item['artist']['name'],
                              artist_mbid=next_item['artist'].get(
                                  'mbid', 'None'),
                              artist_url=next_item['artist']['url'],
                              url=next_item['url'])
                        for next_item in top_item[:30]
                    ])

                if key == "track":
                    first_key = key + "s"
                    top_item = top[first_key][key]
                    db_session.add_all([
                        Track(tag=item['name'],
                              track_rank=next_item['@attr']['rank'],
                              track_name=next_item['name'],
                              track_mbid=next_item.get('mbid', 'None'),
                              track_duration=int(next_item.get(
                                  'duration', '0')),
                              artist_name=next_item['artist']['name'],
                              artist_mbid=next_item['artist'].get(
                                  'mbid', 'None'),
                              artist_url=next_item['artist']['url'],
                              streamable=next_item['streamable']['fulltrack'],
                              url=next_item['url'])
                        for next_item in top_item[:30]
                    ])
                db_session.commit()