Пример #1
0
    def clean(self, value):
        delta = utils.parse_duration(value)

        if not delta:
            raise ValidationError('Invalid duration format.')

        return delta
Пример #2
0
 def create_listitem(self, lms_song):
     '''Create Kodi listitem from LMS song details'''
     listitem = xbmcgui.ListItem(lms_song["title"])
     duration = parse_duration(lms_song.get("duration"))
     listitem.setInfo(
         'music', {
             'title': lms_song["title"],
             'artist': lms_song["trackartist"],
             'album': lms_song.get("album"),
             'duration': duration,
             'discnumber': lms_song.get("disc"),
             'rating': lms_song.get("rating"),
             'genre': lms_song["genres"],
             'tracknumber': lms_song.get("track_number"),
             'lyrics': lms_song.get("lyrics"),
             'year': lms_song.get("year"),
             'comment': lms_song.get("comment")
         })
     listitem.setArt({"thumb": lms_song["thumb"]})
     listitem.setIconImage(lms_song["thumb"])
     listitem.setThumbnailImage(lms_song["thumb"])
     if lms_song.get("remote_title") or not duration:
         # workaround for radio streams
         file_name = "http://127.0.0.1:%s/track/radio" % (self.webport)
     else:
         file_name = "http://127.0.0.1:%s/track/%s" % (self.webport,
                                                       "%s" % duration)
     listitem.setProperty("sl_path", lms_song["url"])
     listitem.setContentLookup(False)
     listitem.setProperty('do_not_analyze', 'true')
     cmd = quote_plus("playlist index %s" % lms_song["playlist index"])
     org_url = "plugin://plugin.audio.squeezebox?action=command&params=%s" % cmd
     listitem.setProperty("original_listitem_url", org_url)
     return listitem, file_name
Пример #3
0
    async def playlist(self, ctx, _id=1):
        song_list = self.database.select(ctx.guild.id)
        await ctx.send(embed=discord.Embed(
            title='Играет плейлист',
            color=0x94ffe4,
            description=f"Плейлист из {len(song_list)} треков"))
        for id, song, guild in song_list:
            if id < _id:
                continue

            self.database.set_now_playing(id, guild)
            try:
                video_id = search_youtube(song.split(' '))[0]['id']
            except:
                continue

            video, song = await get_audio(ctx, video_id)

            ctx.voice_client.play(
                song,
                after=lambda error: print('Ошибка с плеером: ' + error)
                if error else None)

            await ctx.send(embed=discord.Embed(
                title=video.title,
                description=f"Плейлист ID {id}",
                color=0x00ffbf).set_image(url=video.bigthumbhd).set_author(
                    name=video.author).set_footer(
                        text=f"Продолжительность - {video.duration}"))
            await asyncio.sleep(parse_duration(video.duration))
Пример #4
0
def process_watch_history(data):
    print('starting watch history job')
    data = gzip.decompress(data).decode()
    try:
        data = json.loads(data)
    except json.decoder.JSONDecodeError as e:
        return "PARSER"
    if type(data) != list:
        print('json type ', type(data))
        return "PARSER"
    parser = YouTubeHistoryParser()
    parser.feed(data)

    print('{0} video ids and {1} datetimes'.format(len(parser.video_ids),
                                                   len(parser.datetimes)))
    if len(parser.video_ids) == 0 or len(parser.video_ids) != len(
            parser.datetimes):
        return "PARSER"

    queries = set(parser.video_ids)
    result = query_api(queries)
    if type(result) == str:  #an error occured
        print('an error occured, type:', result)
        return result

    total_seconds = 0
    durations, datetimes = [], []
    for i in range(len(parser.video_ids)):
        vid = parser.video_ids[i]
        if vid in result:
            duration = result[vid]
            h, m, s = utils.parse_duration(duration)
            seconds = 3600 * h + 60 * m + s
            durations.append(seconds / 60.0)
            datetimes.append(parser.datetimes[i])
            total_seconds += seconds

    number_of_videos = len(durations)
    total_days = total_seconds / 3600.0 / 24.0

    data = {'number_of_videos': number_of_videos, 'total_days': total_days}

    data = reformat_data(datetimes, durations)
    data['number_of_videos'] = number_of_videos
    data['total_days'] = total_days

    data = json.dumps(data).encode()
    file_size = sys.getsizeof(data) * 1E-6
    data = gzip.compress(data)
    compressed_file_size = sys.getsizeof(data) * 1E-6
    savings = file_size - compressed_file_size

    print(
        'original result {0:.1f} MB, compressed {1:.1f} MB, savings {2:.1f} MB ({3:.1f} %)'
        .format(file_size, compressed_file_size, savings,
                savings / file_size * 100))
    print('job complete')
    return data
Пример #5
0
def _embed_youtube_shortcode(url):
    query = urlparse.parse_qs(url.query, keep_blank_values=False)
    stripped_path = url.path[1:]
    t = query.get('t', ['0'])[0]

    if not re.match('[\-_0-9a-zA-Z]+', stripped_path):
        raise EmbeddingNotSupportedException('Bad video ID.')

    if re.match(utils.TIME_DELTA_FORMAT, t):
        t = int(utils.parse_duration(t).total_seconds())
    elif re.match(r'^\d+$', t):
        pass
    else:
        raise EmbeddingNotSupportedException('Bad time stamp.')

    return _yt_embed_pattern % (stripped_path, t)
Пример #6
0
def main():
    inputs = utils.format_inputs()
    task = inputs['task']
    ret = [json.dumps(task)]
    if 'end' in task and 'end' not in inputs['prior']:
        timew = json.loads(commands.getoutput('timew get dom.tracked.1.json'))
        cmd = 'timew duration "%(uuid)s" from %(entry)s - %(end)s' % task
        if 'end' not in timew and task['uuid'] in timew['tags']:
            cmd = 'timew stop :quiet && ' + cmd
        if 'estimate' in task:
            ret.append('Estimate Duration: %s' %
                       utils.parse_duration(task['estimate']))
        ret.append('Total Duration: %s' % commands.getoutput(cmd))
    if len(ret) == 1:
        ret.append('')
    print('\n'.join(ret))
Пример #7
0
def get_data_to_buffer():
    buffer = list()
    phone_idx = dict()
    duration_idx = dict()

    with open(os.path.join("data", "phone_idx.txt"), "r",
              encoding="utf-8") as f:
        lines = f.readlines()
        for line in lines:
            line_split = line.split("|")
            file_id = line_split[0]
            p_idx = line_split[1][:-1].split(" ")
            for i, phone in enumerate(p_idx):
                p_idx[i] = int(phone)
            phone_idx.update({file_id: p_idx})

    with open(os.path.join("data", "duration_idx.txt"), "r",
              encoding="utf-8") as f:
        lines = f.readlines()
        for line in lines:
            line_split = line.split("|")
            file_id = line_split[0]
            d_idx = line_split[1][:-1].split(" ")
            for i, duration in enumerate(d_idx):
                d_idx[i] = int(duration)
            duration_idx.update({file_id: d_idx})

    start = time.perf_counter()
    for key in tqdm(phone_idx):
        mel_file_path = os.path.join(hp.mel_path, key + ".npy")
        mel = np.load(mel_file_path)
        phone = phone_idx[key]
        duration = duration_idx[key]
        len_dur = len(duration)
        duration = utils.parse_duration(duration, phone)
        if len_dur != np.sum(np.array(duration)):
            raise Exception("data processing error")
        buffer.append({
            "text": torch.Tensor(np.array(phone)),
            "duration": torch.Tensor(np.array(duration)),
            "mel_target": torch.Tensor(mel)
        })
    end = time.perf_counter()
    print("cost {:.2f}s to load all data into buffer.".format(end - start))
    return buffer
Пример #8
0
    async def mute(self, ctx, name, duration=None):
        template = ctx.session.query(TemplateDb).filter_by(
            guild_id=ctx.guild.id, name=name).first()

        if not template:
            raise TemplateNotFoundError(ctx, ctx.guild.id, name)

        if not duration:
            if template.alert_id:
                return await ctx.send(ctx.s("alerts.not_muted").format(name))

            mute = ctx.session.query(MutedTemplate).filter_by(
                template_id=template.id).first()

            if not mute:
                return await ctx.send(ctx.s("alerts.not_muted").format(name))

            template.alert_id = mute.alert_id
            ctx.session.delete(mute)
            await ctx.send(ctx.s("alerts.unmuted").format(name))
        else:
            try:
                duration = float(duration) * 3600
            except ValueError:
                duration = parse_duration(ctx, duration)

            if not template.alert_id:
                return await ctx.send(
                    ctx.s("alerts.already_muted").format(name))

            mute = MutedTemplate(template=template,
                                 alert_id=template.alert_id,
                                 expires=time.time() + duration)
            ctx.session.add(mute)
            template.alert_id = None
            await ctx.send(ctx.s("alerts.muted").format(name, duration / 3600))
Пример #9
0
_ed_map = {
    int:
    lambda ex_v, dic: datetime.utcnow().replace(microsecond=0) + timedelta(
        hours=ex_v),
    float:
    lambda ex_v, dic: datetime.utcnow().replace(microsecond=0) + timedelta(
        hours=ex_v),
    tuple:
    lambda ex_v, dic: datetime.utcnow().replace(microsecond=0) + timedelta(
        *ex_v),
    dict:
    lambda ex_v, dic: datetime.utcnow().replace(microsecond=0) + timedelta(
        **ex_v),
    str:
    lambda ex_v, dic: datetime.utcnow().replace(microsecond=0) +
    parse_duration(ex_v),
    timedelta:
    lambda ex_v, dic: datetime.utcnow().replace(microsecond=0) + ex_v,
    datetime:
    lambda ex_v, dic: ex_v,
}


class ElasticCache(ElasticInput):
    __slots__ = ['count', 'expire_date']
    subtypes = ('elasticcache', )

    def __init__(self, name, **kwargs):
        super().__init__(name=name, **kwargs)
        # create an index in elasticsearch, ignore status code 400 (index already exists)
        if self.location:
    def create_track_listitem(self, lms_item):
        '''Create Kodi listitem from LMS track details'''
        listitem = xbmcgui.ListItem(lms_item["title"])
        listitem.setInfo(
            'music', {
                'title': lms_item["title"],
                'artist': lms_item["trackartist"],
                'album': lms_item.get("album"),
                'duration': parse_duration(lms_item.get("duration")),
                'discnumber': lms_item.get("disc"),
                'rating': lms_item.get("rating"),
                'genre': lms_item["genres"],
                'tracknumber': lms_item.get("track_number"),
                'lyrics': lms_item.get("lyrics"),
                'year': lms_item.get("year"),
                'comment': lms_item.get("comment"),
                "mediatype": "song"
            })
        listitem.setArt({"thumb": lms_item["thumb"]})
        listitem.setIconImage(lms_item["thumb"])
        listitem.setThumbnailImage(lms_item["thumb"])
        listitem.setProperty("isPlayable", "false")
        listitem.setProperty("DBYPE", "song")
        cmd = quote_plus("playlist play %s" % lms_item.get("url"))

        contextmenu = []
        if "playlist index" in lms_item and lms_item["playlist index"]:
            # contextmenu for now playing list
            pl_index = int(lms_item["playlist index"])
            pl_pos = int(self.lmsserver.cur_index)
            cmd = quote_plus("playlist index %s" % pl_index)
            params = quote_plus("playlist index %s" % pl_index)
            contextmenu.append((self.addon.getLocalizedString(32203),
                                "RunPlugin(%s?action=command&params=%s)" %
                                (PLUGIN_BASE, params)))
            contextmenu.append(
                (self.addon.getLocalizedString(32204),
                 "RunPlugin(%s?action=playlistplaynext&params=%s)" %
                 (PLUGIN_BASE, pl_index)))
            params = quote_plus("playlist move %s +1" % pl_index)
            contextmenu.append((xbmc.getLocalizedString(13332),
                                "RunPlugin(%s?action=command&params=%s)" %
                                (PLUGIN_BASE, params)))
            params = quote_plus("playlist move %s -1" % pl_index)
            contextmenu.append((xbmc.getLocalizedString(13333),
                                "RunPlugin(%s?action=command&params=%s)" %
                                (PLUGIN_BASE, params)))
            params = quote_plus("playlist delete %s" % pl_index)
            contextmenu.append((xbmc.getLocalizedString(117),
                                "RunPlugin(%s?action=command&params=%s)" %
                                (PLUGIN_BASE, params)))
            params = quote_plus(xbmc.getLocalizedString(192))
            contextmenu.append(
                ("Clear playlist", "RunPlugin(%s?action=command&params=%s)" %
                 (PLUGIN_BASE, params)))
        else:
            # normal contextmenu
            params = quote_plus("playlist play %s" % lms_item["url"])
            contextmenu.append((self.addon.getLocalizedString(32203),
                                "RunPlugin(%s?action=command&params=%s)" %
                                (PLUGIN_BASE, params)))
            params = quote_plus("playlist insert %s" % lms_item["url"])
            contextmenu.append((self.addon.getLocalizedString(32204),
                                "RunPlugin(%s?action=command&params=%s)" %
                                (PLUGIN_BASE, params)))
            params = quote_plus("playlist add %s" % lms_item["url"])
            contextmenu.append((self.addon.getLocalizedString(32205),
                                "RunPlugin(%s?action=command&params=%s)" %
                                (PLUGIN_BASE, params)))
        listitem.addContextMenuItems(contextmenu, True)
        url = "plugin://plugin.audio.squeezebox?action=command&params=%s" % cmd
        xbmcplugin.addDirectoryItem(handle=ADDON_HANDLE,
                                    url=url,
                                    listitem=listitem,
                                    isFolder=False)