How to use secs_to_timestamp method in Robotframework

Best Python code snippet using robotframework

xsc2beatmap

Source:xsc2beatmap Github

copy

Full Screen

...144# if current_measure in tempos:145# print("tempo %3d %3d %.8f bpm" %146# (section, measure, tempos[current_measure]))147#148# timestamp = secs_to_timestamp(secs)149# print "%-5s %3d %3d %2d %s" % (label, section, measure, beat, timestamp)150# prev_measure = current_measure151def get_beat_tempos(beats):152 tempos = [ ]153 prev_secs = None154 last_tempo = None155 for i in xrange(len(beats)):156 label, section, measure, beat, secs = beats[i]157 if prev_secs is not None:158 tempo = 60.0 / (secs - prev_secs)159 tempos.append(tempo)160 prev_secs = secs161 return tempos162def show_beats_with_beat_tempos(beats):163 tempos = get_beat_tempos(beats)164 for i in xrange(len(beats)):165 label, section, measure, beat, secs = beats[i]166 timestamp = secs_to_timestamp(secs)167 out = "%-5s %3d %3d %2d %16s 1 1" % \168 (label, section, measure, beat, timestamp)169 if i < len(tempos):170 out += " %.8f" % tempos[i]171 print(out)172def timestamp_to_secs(timestamp):173 hours, mins, secs = timestamp.split(':')174 return (int(hours)*60 + int(mins))*60.0 + float(secs)175def secs_to_timestamp(secs):176 mins = secs / 60177 secs = secs % 60178 hours = mins / 60179 mins = mins % 60180 secs = "%.06f" % secs181 if secs[1] == '.':182 secs = '0' + secs183 return "%d:%02d:%s" % (hours, mins, secs)184def main():185 start_time, beats = read_beats(sys.argv[1])186 show_beats_with_beat_tempos(beats)187if __name__ == '__main__':...

Full Screen

Full Screen

bot.py

Source:bot.py Github

copy

Full Screen

...46@bot.command(name='pic', help='Force KayBot to look at disgusting food and share pics of it.')47async def post_pic(ctx):48 title, vid_id = get_random_video()49 time = get_random_time_secs(vid_id)50 ts = secs_to_timestamp(time)51 logging.info(f'Randomly selected "{title}" with id "{vid_id}" and timestamp "{ts}"')52 with tempfile.TemporaryDirectory() as tmpdir:53 attempts = 054 while attempts < 5:55 attempts += 156 screenshot = get_screenshot(time, vid_id, str(tmpdir))57 if not os.path.exists(screenshot):58 continue59 image = File(screenshot)60 await ctx.send(f'`{title} ({ts})`', file=image)61 return62 logging.error(f'Failed to screenshot "{title}" ({vid_id}), potentially due to stream link timeout')63def get_channel_id() -> str:64 return choice(IDS)65def get_random_video() -> str:66 global VIDEOS67 reqs = make_request({68 'part': 'contentDetails',69 'id': get_channel_id(),70 'key': YOUTUBE_TOKEN,71 })72 url = 'https://youtube.googleapis.com/youtube/v3/channels' + reqs73 response = requests.get(url=url).json()74 details, = response['items']75 uploads_id = details['contentDetails']['relatedPlaylists']['uploads']76 reqs = {77 'part': ['snippet', 'contentDetails', 'status'],78 'playlistId': uploads_id,79 'key': YOUTUBE_TOKEN,80 'maxResults': '50',81 'pageToken': '',82 }83 url = 'https://youtube.googleapis.com/youtube/v3/playlistItems' + make_request(reqs)84 response = requests.get(url=url).json()85 # if no new videos have been uploaded then use 'cache'86 if not (len(VIDEOS) < response['pageInfo']['totalResults']):87 return choice(VIDEOS)88 VIDEOS.clear()89 while True:90 url = 'https://youtube.googleapis.com/youtube/v3/playlistItems' + make_request(reqs)91 response = requests.get(url=url).json()92 items = response['items']93 if not items:94 break95 VIDEOS += [(vid['snippet']['title'], vid['snippet']['resourceId']['videoId']) for vid in items]96 next_page = response['nextPageToken'] if 'nextPageToken' in response else ''97 if not next_page:98 break99 reqs['pageToken'] = next_page100 return choice(VIDEOS)101def get_random_time_secs(video_id: str) -> Duration:102 req = {103 'id': video_id,104 'part': 'contentDetails',105 'key': YOUTUBE_TOKEN,106 }107 video_details = requests.get(url='https://www.googleapis.com/youtube/v3/videos' + make_request(req)).json()108 time = parse_duration(video_details['items'][0]['contentDetails']['duration'])109 return randint(1, time.total_seconds())110def secs_to_timestamp(total_secs: int) -> str:111 mins, secs = total_secs // 60, total_secs % 60112 if mins < 10:113 mins = "0" + str(mins)114 if secs < 10:115 secs = "0" + str(secs)116 return f'{mins}:{secs}'117def get_screenshot(time_secs: int, video_id: str, tmpdir: str) -> str:118 ts = secs_to_timestamp(time_secs)119 youtubedl_url = get_youtubedl_url(video_id)120 121 cmd = ('ffmpeg', '-ss', ts, '-i', f'"{youtubedl_url}"', '-vframes', '1', '-q:v', '2', f'"{tmpdir}/out.png"',)122 cmd_str = ' '.join(cmd)123 subprocess.run(cmd_str, shell=True)124 return f'{tmpdir}/out.png'125def get_youtubedl_url(video_id: str, quality: int = 137) -> str:126 youtube_dl_cmd = ('youtube-dl', '-f', str(quality), '--get-url',127 f'https://www.youtube.com/watch?v={video_id}',)128 return subprocess.check_output(youtube_dl_cmd).decode().strip()129def start():130 logging.basicConfig(filename='kaybot.log', level=logging.DEBUG)131 print(f'Connecting bot...')132 bot.run(DISCORD_TOKEN)...

Full Screen

Full Screen

vtt.py

Source:vtt.py Github

copy

Full Screen

...5from bs4 import BeautifulSoup6def timestamp_to_secs(ts):7 hours, minutes, seconds = ts.split(':')8 return float(hours)*60*60 + float(minutes)*60 + float(seconds)9def secs_to_timestamp(secs):10 m, s = divmod(secs, 60)11 h, m = divmod(m, 60)12 return "%02d:%02d:%02f" % (h, m, s)13def parse_cued(data):14 out = []15 pat = r'<(\d\d:\d\d:\d\d(\.\d+)?)>'16 for lines in data:17 meta, content = lines18 start, end = meta.split(' --> ')19 end = end.split(' ')[0]20 start = timestamp_to_secs(start)21 end = timestamp_to_secs(end)22 text = BeautifulSoup(content, 'html.parser').text23 words = text.split(' ')24 sentence = {'text': '', 'words': []}25 for word in words:26 item = {}27 item['start'] = start28 item['end'] = end29 word_parts = re.split(pat, word)30 item['word'] = word_parts[0]31 if len(word_parts) > 1:32 item['end'] = timestamp_to_secs(word_parts[1])33 sentence['words'].append(item)34 start = item['end']35 sentence['text'] = ' '.join([w['word'] for w in sentence['words']])36 out.append(sentence)37 for index, sentence in enumerate(out):38 if index == 0:39 sentence['start'] = sentence['words'][0]['start']40 sentence['end'] = sentence['words'][-1]['end']41 continue42 first_word = sentence['words'][0]43 last_word = out[index-1]['words'][-1]44 if last_word['end'] > first_word['start']:45 last_word['end'] = first_word['start']46 sentence['start'] = sentence['words'][0]['start']47 sentence['end'] = sentence['words'][-1]['end']48 return out49def parse_uncued(data):50 out = []51 data = [d.strip() for d in data.split('\n') if d.strip() != '']52 out = [{'text': '', 'start': None, 'end': None}]53 for i, line in enumerate(data):54 if ' --> ' in line:55 start, end = line.split(' --> ')56 end = end.split(' ')[0]57 start = timestamp_to_secs(start)58 end = timestamp_to_secs(end)59 if out[-1]['start'] is None:60 out[-1]['start'] = start61 out[-1]['end'] = end62 else:63 out.append({'text': '', 'start': start, 'end': end})64 else:65 if out[-1]['start'] is not None:66 out[-1]['text'] += ' ' + line.strip()67 for o in out:68 o['text'] = o['text'].strip()69 return out70def parse_auto_sub(text):71 '''72 Parses webvtt and returns timestamps for words and lines73 Tested on automatically generated subtitles from YouTube74 '''75 pat = r'<(\d\d:\d\d:\d\d(\.\d+)?)>'76 out = []77 lines = []78 data = text.split('\n')79 data = [d for d in data if re.search(r'\d\d:\d\d:\d\d', d) is not None]80 for i, d in enumerate(data):81 if re.search(pat, d):82 lines.append((data[i-1], d))83 if len(lines) > 0:84 out = parse_cued(lines)85 else:86 out = parse_uncued(text)87 return out88def convert_to_srt(sentence):89 out = []90 for i, sentence in enumerate(sentence):91 out.append(str(i))92 start = sentence['words'][0]['start']93 end = sentence['words'][-1]['end']94 start = secs_to_timestamp(start)95 end = secs_to_timestamp(end)96 out.append('{} --> {}'.format(start, end))97 out.append(sentence['text'])98 out.append('')99 return '\n'.join(out)100def convert_to_sphinx(sentences):101 out = []102 for sentence in sentences:103 start = sentence['words'][0]['start']104 end = sentence['words'][-1]['end']105 out.append(sentence['text'])106 out.append('<s> {} {} .9'.format(start, start))107 for word in sentence['words']:108 out.append('{} {} {} {}'.format(word['word'], word['start'], word['end'], '.999'))109 out.append('</s> {} {} .9'.format(end, end))...

Full Screen

Full Screen

configurer.py

Source:configurer.py Github

copy

Full Screen

...47 try:48 secs = timestamp_to_secs(timestamp, seps=' :.-_')49 except ValueError:50 return None51 return secs_to_timestamp(secs, millis=True)52 def visit_suite(self, suite):53 model.SuiteConfigurer.visit_suite(self, suite)54 self._remove_keywords(suite)55 self._set_times(suite)56 suite.filter_messages(self.log_level)57 suite.set_criticality(self.critical_tags, self.non_critical_tags)58 def _remove_keywords(self, suite):59 for how in self.remove_keywords:60 suite.remove_keywords(how)61 def _set_times(self, suite):62 if self.start_time:63 suite.starttime = self.start_time64 if self.end_time:65 suite.endtime = self.end_time

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Robotframework automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful