How to use locals_to_params method in Playwright Python

Best Python code snippet using playwright-python

core.py

Source:core.py Github

copy

Full Screen

...68 return args69class ProntoClass:70 def __init__(self, vh=540, vw=960, fps=30, **kwargs):71 self.vbg = solid_color_img((vh,vw,3), alpha=0)72 store_attr(self, ','.join(dict_keys(locals_to_params(locals()))))73class Animation(ProntoClass):74 def __init__(self, temp, vh=540, vw=960, an_fn=noop, animation_dur=1, fps=30, **kwargs):75 super().__init__(**locals_to_params(locals()))76 self.an_fn = partial(an_fn, **locals_to_params(locals()))77 self.animate()78 self.durs = [x.duration for x in self.clips]79 80 def animate(self):81 x = self.an_fn(self.temp)82 if not is_list(x):83 x = [x]84 # if self.reverse:85 # x = x[::-1]86 self.an_chunks = x87 self.v = mp.ImageSequenceClip(x, fps=self.fps)88 self.clips = [self.v]89class MoveAnimation(Animation):90 def __init__(self, temp, bg=solid_color_img((540,960,3)), x1=0., y1=0., x2=0.5, y2=0.5, steps=15, fn=pto_noop, h2=None, w2=None,91 vh=540, vw=960, **kwargs):92 an_fn = move_img93 super().__init__(**locals_to_params(locals()))94class VerticalAppearAnimation(Animation):95 def __init__(self, temp, direction='up', num_chunks=5, animation_dur=1, fps=30, num_chunks_2=5, animation_dur_2=1, **kwargs):96 an_fn = animate_vertical_appear97 self.fwd = Animation(**locals_to_params(locals())).v98 self.v = self.fwd99 an_fn = partial(an_fn, reverse=True)100 num_chunks = num_chunks_2101 animation_dur = animation_dur_2102 self.bwd = Animation(**locals_to_params(locals())).v103 self.clips = [self.fwd, self.bwd]104 self.durs = [num_chunks/fps, num_chunks_2/fps]105class HorizontalAppearAnimation(Animation):106 def __init__(self, temp, direction='right', num_chunks=5, animation_dur=1, fps=30, num_chunks_2=5, animation_dur_2=1, **kwargs):107 an_fn = animate_horizontal_appear108 self.fwd = Animation(**locals_to_params(locals())).v109 self.v = self.fwd110 an_fn = partial(an_fn, reverse=True)111 num_chunks = num_chunks_2112 animation_dur = animation_dur_2113 self.bwd = Animation(**locals_to_params(locals())).v114 self.clips = [self.fwd, self.bwd]115 self.durs = [num_chunks/fps, num_chunks_2/fps]116class VerticalSlideAnimation:117 def __init__(self, temp, direction='down', num_chunks=5, bg=None, animation_dur=1, fps=30,118 num_chunks_2=5, animation_dur_2=1, **kwargs):119 an_fn = animate_vertical_slide120 self.fwd = Animation(**locals_to_params(locals())).v121 self.v = self.fwd122 an_fn = partial(an_fn, reverse=True)123 num_chunks = num_chunks_2124 animation_dur = animation_dur_2125 self.bwd = Animation(**locals_to_params(locals())).v126 self.clips = [self.fwd, self.bwd]127 self.durs = [num_chunks/fps, num_chunks_2/fps]128 129class HorizontalSlideAnimation:130 def __init__(self, temp, direction='right', num_chunks=5, bg=None, animation_dur=1, fps=30,131 num_chunks_2=5, animation_dur_2=1, **kwargs):132 an_fn = animate_horizontal_slide133 self.fwd = Animation(**locals_to_params(locals())).v134 self.v = self.fwd135 an_fn = partial(an_fn, reverse=True)136 num_chunks = num_chunks_2137 animation_dur = animation_dur_2138 self.bwd = Animation(**locals_to_params(locals())).v139 self.clips = [self.fwd, self.bwd]140 self.durs = [num_chunks/fps, num_chunks_2/fps]141 142class ZoomAnimation(Animation):143 def __init__(self, temp, direction='right', bg=None, pos=(0.,0.), num_chunks=3,144 zoom_scales=[5,1], zoom_chunks=3, **kwargs):145 an_fn = animate_zoom_appear146 super().__init__(**locals_to_params(locals()))147class OpenAnimation(Animation):148 def __init__(self, temp, direction='mv', num_chunks=5, bg=None, animation_dur=1, fps=30, **kwargs):149 an_fn = animate_open150 super().__init__(**locals_to_params(locals()))151 152class CloseAnimation(Animation):153 def __init__(self, temp, direction='mv', num_chunks=5, bg=None, animation_dur=1, fps=30, **kwargs):154 reverse = True155 an_fn = partial(animate_open, reverse=reverse)156 super().__init__(**locals_to_params(locals()))157 158class OpenCloseAnimation:159 def __init__(self, temp, direction='mv', bg=None, num_chunks=5, num_chunks_2=5,160 animation_dur=1, animation_dur_2=1, fps=30, **kwargs):161 self.open = OpenAnimation(**locals_to_params(locals())).v162 num_chunks = num_chunks_2163 animation_dur = animation_dur_2164 self.close = CloseAnimation(**locals_to_params(locals())).v165 self.clips = [self.open, self.close]166 self.durs = [num_chunks/fps, num_chunks_2/fps]167def no_effect(text='', font_size=40, font='/usr/local/share/fonts/relaxed/NotoSansTC-Medium.otf',168 color='white', align='center', wrap_width=25, start=0, end=5, fps=30, img=None, **kwargs):169 170 '''171 No special effect, just the text or image on the screen.172 Parameters:173 text (str): The text to display.174 font_size (int): The font size.175 font (str): The font to use.176 color (str or [r,g,b] list): The color of the text.177 align (str): The alignment of the text. Can be one of 'left', 'center', 'right'.178 wrap_width (int): The nuber of text characters per line.179 start (int): The starting timestamp(second) of the clip.180 end (int): The ending timestamp(second) of the clip.181 fps (int): The frames per second of the clip.182 img (str): If text is an emtpy string, this image will be used instead.183 '''184 185 duration = end-start186 clips = []187 pos = []188 times = []189 190 if len(text) > 0:191 img = text_template(text=text, wrap_width=wrap_width, font=font, font_size=font_size,192 gap=0, align=align, color=color, full_text_bg=True, text_bg_alpha=0)193 elif img is None:194 return blank_clip(duration)195 clips.append(mp.ImageClip(img, duration=duration))196 pos.append([0.5,0.5])197 times.append([0,duration])198 h,w = get_hw(img)199 return ProntoClip(clips=clips, times=times, pos=pos, start=start, end=end, fps=fps, vh=w, vw=w)200def art_effect(text='', font_size=40, color='white', font='/usr/local/share/fonts/relaxed/NotoSansTC-Medium.otf', theme=[16,184,254],201 align='center', start=0, end=5, fps=30, img=None, **kwargs):202 203 '''204 Effect adapted from the Art template.205 The text/image will be split into 3 and slide down onto the screen with a colorful bar on the left.206 Parameters:207 text (str): The text to display.208 font_size (int): The font size.209 font (str): The font to use.210 theme (str or [r,g,b] list): The color of the bar on the left.211 color (str or [r,g,b] list): The color of the text.212 align (str): The alignment of the text. Can be one of 'left', 'center', 'right'.213 wrap_width (int): The nuber of text characters per line.214 start (int): The starting timestamp(second) of the clip.215 end (int): The ending timestamp(second) of the clip.216 fps (int): The frames per second of the clip.217 img (str): If text is an emtpy string, this image will be used instead.218 '''219 220 duration = end-start221 clips = []222 pos = []223 times = []224 225 if len(text) > 0:226 img = text_template(text=text, wrap_width=55, font=font, font_size=font_size, text_bg_color=theme,227 gap=0, align=align, color=color, full_text_bg=True, text_bg_alpha=0)228 elif img is None:229 return blank_clip(duration)230 231 img_clip = mp.ImageClip(img, duration=duration)232 th,tw = get_hw(img)233 num_splits = 3234 splits = np.array_split(range(tw), num_splits)235 t1,t2,t3 = [img[:,x[0]:x[-1]+1] for x in splits]236 tws = [get_hw(t)[1] for t in [t1,t2,t3]]237 num_chunks = 5238 an_dur = num_chunks/fps239 t1_an1 = VerticalSlideAnimation(t1, direction='down', num_chunks=num_chunks).fwd240 t2_an1 = VerticalSlideAnimation(t2, direction='down', num_chunks=num_chunks).fwd241 t3_an1 = VerticalSlideAnimation(t3, direction='down', num_chunks=num_chunks).fwd242 img_clip2 = VerticalAppearAnimation(img, direction='up', num_chunks_2=num_chunks).bwd243 gap = 20244 barw = 5245 barh = th-5246 bar = solid_color_img((barh, barw, 3), color=theme)247 bar_an1 = VerticalSlideAnimation(bar, direction='down', num_chunks=num_chunks).fwd248 bar_an2 = VerticalAppearAnimation(bar, direction='up', num_chunks_2=num_chunks).bwd249 img_pos = [gap//2+barw, 0]250 clips += [t1_an1, t2_an1, t3_an1, bar_an1, bar_an2, img_clip, img_clip2]251 pos += [img_pos, [f'fwd_posx+{tws[0]}', 'fwd_posy'], [f'fwd_posx+{tws[1]}', 'fwd_posy']]252 pos += [[0, f'fwd_posy+7']]*2253 pos += [img_pos]*2254 times += [[an_dur,an_dur*4], [an_dur*2,an_dur*4], [an_dur*3,an_dur*4]]255 times += [[an_dur,duration-an_dur-an_dur], duration-an_dur-an_dur]256 times += [[an_dur*4, duration-an_dur-an_dur], duration-an_dur-an_dur]257 w = barw+tws[0]+tws[1]+tws[2]+gap258 h = max(max([get_hw(t1)[0], get_hw(t2)[0], get_hw(t3)[0]]),barh)259 return ProntoClip(clips=clips, times=times, pos=pos, start=start, end=end, fps=fps, vh=h, vw=w)260def slide_effect(text='', direction='right', font_size=40, font='/usr/local/share/fonts/relaxed/NotoSansTC-Medium.otf',261 color='white', align='center', wrap_width=25, start=0, end=5, fps=30, slide_out=True,262 img=None, **kwargs):263 264 '''265 The text/image will slide onto the screen.266 Parameters:267 text (str): The text to display.268 direction (str): The direction of the slide. Can be one of 'left', 'right', 'up', 'down'.269 font_size (int): The font size.270 font (str): The font to use.271 color (str or [r,g,b] list): The color of the text.272 align (str): The alignment of the text. Can be one of 'left', 'center', 'right'.273 wrap_width (int): The nuber of text characters per line.274 start (int): The starting timestamp(second) of the clip.275 end (int): The ending timestamp(second) of the clip.276 fps (int): The frames per second of the clip.277 img (str): If text is an emtpy string, this image will be used instead.278 slide_out (bool): If True, the text will also slide out of the screen.279 '''280 281 ans = {'down':VerticalSlideAnimation, 'up':VerticalSlideAnimation, 'right':HorizontalSlideAnimation, 'left':HorizontalSlideAnimation}282 duration = end-start283 clips = []284 pos = []285 times = []286 287 if len(text) > 0:288 img = text_template(text=text, wrap_width=wrap_width, font=font, font_size=font_size,289 gap=0, align=align, color=color, full_text_bg=True, text_bg_alpha=0)290 elif img is None:291 return blank_clip(duration)292 an = ans[direction]293 img_an = an(temp=img, direction=direction, num_chunks=5, num_chunks_2=5, fps=fps)294 clips = img_an.clips295 pos += [[0.5,0.5]]*len(clips)296 dur0, dur1 = img_an.durs297 times += [[0, duration-dur1], duration-dur1]298 h,w = get_hw(img)299 if not slide_out:300 clips = clips[:1]301 times = times[:1]302 pos = pos[:1]303 return ProntoClip(clips=clips, times=times, pos=pos, start=start, end=end, fps=fps, vh=w, vw=w)304def move_effect(text='', bg=None, x1=0., y1=0., x2=0.5, y2=0.5, steps=15, fn=pto_noop, h2=None, w2=None,305 font_size=40, font='/usr/local/share/fonts/relaxed/NotoSansTC-Medium.otf', color='white', align='center',306 wrap_width=25, start=0, end=5, fps=30, img=None, vh=540, vw=960, **kwargs):307 308 '''309 The text/image will move from position (x1,y1) to position (x2,y2).310 Parameters:311 text (str): The text to display.312 bg (image): The background on which the text/image can move around.313 If None, the background will be the entire screen based on vh and vw.314 x1 (float or int): The starting x position of the text/image.315 y1 (float or int): The starting y position of the text/image.316 x2 (float or int): The ending x position of the text/image.317 y2 (float or int): The ending y position of the text/image.318 steps (int): The number of steps/frames to move the text/image. 15 means the text/image moves for half a second if fps is 30.319 h2 (int): The final height of the text/image. If None, the text/image is not resized.320 w2 (int): The final width of the text/image. If None, the text/image is not resized.321 font_size (int): The font size.322 font (str): The font to use.323 color (str or [r,g,b] list): The color of the text.324 align (str): The alignment of the text. Can be one of 'left', 'center', 'right'.325 wrap_width (int): The nuber of text characters per line.326 start (int): The starting timestamp(second) of the clip.327 end (int): The ending timestamp(second) of the clip.328 fps (int): The frames per second of the clip.329 img (str): If text is an emtpy string, this image will be used instead.330 vh (int): The height of the overall video the text/image will be displayed on.331 vw (int): The width of the overall video the text/image will be displayed on.332 ''' 333 334 duration = end-start335 clips = []336 pos = []337 times = []338 339 if len(text) > 0:340 img = text_template(text=text, wrap_width=wrap_width, font=font, font_size=font_size,341 gap=0, align=align, color=color, full_text_bg=True, text_bg_alpha=0)342 elif img is None:343 return blank_clip(duration)344 if bg is None:345 bg = solid_color_img((vh,vw,3), alpha=0)346 clips.append(MoveAnimation(img, bg=bg, x1=x1, y1=y1, x2=x2, y2=y2, steps=steps, fn=fn, h2=h2, w2=w2, fps=fps).v)347 pos.append([0.5,0.5])348 times.append([0,-1])349 h,w = get_hw(bg)350 return ProntoClip(clips=clips, times=times, pos=pos, start=start, end=end, fps=fps, vh=h, vw=w)351def slide_move_effect(text='', direction='right', font_size=40, font='/usr/local/share/fonts/relaxed/NotoSansTC-Medium.otf',352 color='white', align='center', wrap_width=25, start=0, end=5, fps=30,353 bg=None, x1=0.5, y1=0.5, x2=0.75, y2=0.5, steps=5, fn=pto_noop, h2=None, w2=None, vh=540, vw=960,354 img=None, **kwargs):355 356 '''357 The text/image will slide in a direction and then move from position (x1,y1) to position (x2,y2).358 Parameters:359 text (str): The text to display.360 direction (str): The direction of the slide. Can be one of 'down', 'up', 'right', 'left'.361 font_size (int): The font size.362 font (str): The font to use.363 color (str or [r,g,b] list): The color of the text.364 align (str): The alignment of the text. Can be one of 'left', 'center', 'right'.365 wrap_width (int): The nuber of text characters per line.366 start (int): The starting timestamp(second) of the clip.367 end (int): The ending timestamp(second) of the clip.368 fps (int): The frames per second of the clip.369 bg (image): The background on which the text/image can move around.370 If None, the background will be the entire screen based on vh and vw.371 x1 (float or int): The starting x position of the text/image.372 y1 (float or int): The starting y position of the text/image.373 x2 (float or int): The ending x position of the text/image.374 y2 (float or int): The ending y position of the text/image.375 steps (int): The number of steps/frames to move the text/image. 15 means the text/image moves for half a second if fps is 30.376 h2 (int): The final height of the text/image. If None, the text/image is not resized.377 w2 (int): The final width of the text/image. If None, the text/image is not resized.378 vh (int): The height of the overall video the text/image will be displayed on.379 vw (int): The width of the overall video the text/image will be displayed on.380 img (str): If text is an emtpy string, this image will be used instead.381 ''' 382 383 duration = end-start384 clips = []385 pos = []386 times = []387 388 if len(text) == 0 and img is None:389 return blank_clip(duration)390 391 if bg is None:392 bg = solid_color_img((vh,vw,3), alpha=0)393 # bg_clip = mp.ImageClip(bg, duration=duration)394 395 slide_start = 0396 slide_end = 1.5397 clips.append(slide_effect(text=text, direction=direction, font_size=font_size, font=font, color=color, align=align, wrap_width=wrap_width,398 start=slide_start, end=slide_end, fps=fps, slide_out=False, img=img, **kwargs))399 pos.append([x1, y1])400 times.append([slide_start, slide_end])401 move_start = slide_end-steps/fps402 clips.append(move_effect(text=text, font_size=font_size, font=font, color=color, align=align, wrap_width=wrap_width, img=img,403 bg=bg, x1=x1, y1=y1, x2=x2, y2=y2, steps=steps, fn=fn, h2=h2, w2=w2, fps=fps, start=move_start, end=end))404 pos.append([0.,0.])405 times.append(move_start)406 print(pos)407 return ProntoClip(bg_clip='', clips=clips, times=times, pos=pos, start=start, end=end, fps=fps, vh=vh, vw=vw)408def candid_effect(text='', font_size=30, font='/usr/local/share/fonts/relaxed/NotoSansTC-Medium.otf',409 color='white', align='center', wrap_width=55, start=0, end=5, fps=30, theme='blue',410 img=None, **kwargs):411 412 '''413 Effect adapted from the Candid template. A textbox opens and closes witha grey background and bars on each side.414 Parameters:415 text (str): The text to display.416 font_size (int): The font size.417 font (str): The font to use.418 color (str or [r,g,b] list): The color of the text.419 align (str): The alignment of the text. Can be one of 'left', 'center', 'right'.420 wrap_width (int): The nuber of text characters per line.421 start (int): The starting timestamp(second) of the clip.422 end (int): The ending timestamp(second) of the clip.423 fps (int): The frames per second of the clip.424 theme (str or [r,g,b] list): The color of the bars on each side.425 img (str): If text is an emtpy string, this image will be used instead.426 ''' 427 428 duration = end-start429 pos = [[0,0]]*2430 close_dur = 3/fps431 open_end = duration-close_dur*2432 times = [[0,open_end], open_end]433 if len(text) > 0:434 text = text_case(text, 'capitalize')435 img = text_template(text=text, wrap_width=wrap_width, font=font, font_size=font_size,436 gap=10, align=align, color=color, full_text_bg=True, text_bg_alpha=170,437 text_bg_color=(40,40,40))438 elif img is None:439 return blank_clip(duration)440 441 th,tw = get_hw(img)442 line = solid_color_img((th,5,3), color=theme, alpha=225)443 img = np.concatenate([line, img, line], axis=1)444 th,tw = get_hw(img)445 446 text_an = OpenCloseAnimation(temp=img, direction='mh', num_chunks=5, num_chunks_2=3, fps=fps)447 clips = [text_an.open, text_an.close] 448 449 return ProntoClip(vh=th, vw=tw, clips=clips, pos=pos, times=times, end=duration)450def bold_effect(text='', font_size=95, font='/usr/local/share/fonts/energized/Poppins-ExtraBold.ttf', theme='blue',451 color='white', align='left', wrap_width=15, start=0, end=5, fps=30, img=None, vh=540, vw=960,452 pos=['left', 'center'], **kwargs):453 454 '''455 Effect adapted from the Bold template.456 The text splits into 3 and zooms in/out with a slightly transparent background on the whole video.457 Parameters:458 text (str): The text to display.459 font_size (int): The font size.460 font (str): The font to use.461 theme (str or [r,g,b] list): The color of the slightly transparent background.462 color (str or [r,g,b] list): The color of the text.463 align (str): The alignment of the text. Can be one of 'left', 'center', 'right'.464 wrap_width (int): The nuber of text characters per line.465 start (int): The starting timestamp(second) of the clip.466 end (int): The ending timestamp(second) of the clip.467 fps (int): The frames per second of the clip.468 img (str): If text is an emtpy string, this image will be used instead.469 vh (int): The height of the overall video the text/image will be displayed on.470 vw (int): The width of the overall video the text/image will be displayed on.471 pos (list): The [x,y] position of the text on the video.472 ''' 473 474 duration = end-start475 zoom_start = 0476 zoom_dur = min(4, duration-1)477 zoom_end = zoom_start+zoom_dur478 zoom_out_dur = 2/fps479 if len(text) > 0:480 text = text_case(text, 'upper')481 img = text_template(text=text, temp_alpha=0, align=align, temp_bg_color=theme, text_bg_alpha=0, font_size=font_size, font=font,482 wrap_width=wrap_width, gap=0, color=color)483 elif img is None:484 return blank_clip(duration)485 vbg = solid_color_img((vh,vw,3), alpha=0)486 zoom_in = ZoomAnimation(img, direction='right', bg=vbg, pos=pos, num_chunks=3, zoom_chunks=3, zoom_scales=[5,1]).v487 zoom_out = ZoomAnimation(img, direction='right', bg=vbg, pos=pos, num_chunks=1, zoom_chunks=2, zoom_scales=[1,5]).v488 zoom_bg = mp.ImageClip(solid_color_img_like(vbg, color=theme, alpha=45), duration=zoom_dur-zoom_out_dur)489 times = [zoom_start, [zoom_start, zoom_end-zoom_out_dur],zoom_end-zoom_out_dur]490 return ProntoClip(clips=[zoom_bg, zoom_in, zoom_out], vh=vh, w=vw, times=times, end=duration)491def zoom_effect(text='', font_size=95, font='/usr/local/share/fonts/energized/Poppins-ExtraBold.ttf',492 color='white', align='left', wrap_width=15, start=0, end=5, fps=30, img=None, vh=540, vw=960,493 pos=['left', 'center'], **kwargs):494 495 '''496 The text zooms in/out with a slightly transparent background on the whole video.497 Parameters:498 text (str): The text to display.499 font_size (int): The font size.500 font (str): The font to use.501 color (str or [r,g,b] list): The color of the text.502 align (str): The alignment of the text. Can be one of 'left', 'center', 'right'.503 wrap_width (int): The nuber of text characters per line.504 start (int): The starting timestamp(second) of the clip.505 end (int): The ending timestamp(second) of the clip.506 fps (int): The frames per second of the clip.507 img (str): If text is an emtpy string, this image will be used instead.508 vh (int): The height of the overall video the text/image will be displayed on.509 vw (int): The width of the overall video the text/image will be displayed on.510 pos (list): The [x,y] position of the text on the video.511 ''' 512 513 duration = end-start514 zoom_start = 0515 zoom_dur = min(4, duration-1)516 zoom_end = zoom_start+zoom_dur517 zoom_out_dur = 2/fps518 if len(text) > 0:519 text = text_case(text, 'upper')520 img = text_template(text=text, temp_alpha=0, align=align, text_bg_alpha=0, font_size=font_size, font=font,521 wrap_width=wrap_width, gap=0, color=color)522 elif img is None:523 return blank_clip(duration)524 vbg = solid_color_img((vh,vw,3), alpha=0)525 zoom_in = ZoomAnimation(img, direction='right', bg=vbg, pos=pos, num_chunks=1, zoom_chunks=3, zoom_scales=[5,1]).v526 zoom_out = ZoomAnimation(img, direction='right', bg=vbg, pos=pos, num_chunks=1, zoom_chunks=2, zoom_scales=[1,5]).v527 # zoom_bg = mp.ImageClip(solid_color_img_like(vbg, color=theme, alpha=45), duration=zoom_dur-zoom_out_dur)528 times = [[zoom_start, zoom_end-zoom_out_dur],zoom_end-zoom_out_dur]529 return ProntoClip(clips=[zoom_in, zoom_out], vh=vh, w=vw, times=times, end=duration)530def fresh_effect(text='', font_size=40, font='Poppins-ExtraBold.ttf', theme=[16,184,254],531 color='white', wrap_width=35, start=0, end=5, fps=30, img=None, **kwargs):532 533 '''534 Effect adapted from the Fresh template.535 The text background and the text slide in and out one after another.536 Parameters:537 text (str): The text to display.538 font_size (int): The font size.539 font (str): The font to use.540 theme (str or [r,g,b] list): The color of the text background.541 color (str or [r,g,b] list): The color of the text.542 wrap_width (int): The nuber of text characters per line.543 start (int): The starting timestamp(second) of the clip.544 end (int): The ending timestamp(second) of the clip.545 fps (int): The frames per second of the clip.546 img (str): If text is an emtpy string, this image will be used instead.547 ''' 548 549 duration = end-start550 # all_pos = [['left', 'top'], ['left', 'bottom'], ['center', 'center'], ['right', 'bottom'], ['right', 'top']]551 directions = ['down', 'right']552 alignement = ['left', 'right']553 ans = {'down':VerticalAppearAnimation, 'right':HorizontalAppearAnimation}554 clips = []555 pos = []556 times = []557 558 if len(text) == 0 and img is None:559 return blank_clip(duration)560 if len(text) > 0:561 # temp_pos = random.choice(all_pos)562 temp_pos = [0,0]563 bb_direction = random.choice(directions)564 temp_direction = random.choice(directions)565 trans_direction = random.choice(directions)566 bb_an = ans[bb_direction]567 temp_an = ans[temp_direction]568 trans_direction = ans[trans_direction]569 align = random.choice(alignement)570 blank_bgs, text_bgs, temp = text_template_components(text=text, align=align,571 temp_bg_color=theme, color=color,572 text_bg_alpha=210, font_size=font_size,573 font=font, wrap_width=wrap_width)574 chunks = 10575 slide_dur = chunks/fps576 bbg_dur = duration-slide_dur577 bbgs = [bb_an(bbg, direction=bb_direction, num_chunks=chunks, fps=fps).v for bbg in blank_bgs]578 clips += bbgs579 times += [[0, bbg_dur]]*len(bbgs)580 pos += [temp_pos]*len(bbgs)581 tbg_start = 0.1582 tbgs = [mp.ImageClip(tbg, duration=bbg_dur-tbg_start).set_fadein(slide_dur) for tbg in text_bgs]583 clips += tbgs584 times += [tbg_start]*len(tbgs)585 pos += [temp_pos]*len(tbgs)586 temp_v = temp_an(temp, direction=temp_direction, num_chunks=chunks, fps=fps, reverse=True).v587 clips.append(temp_v)588 times.append(bbg_dur)589 pos.append(temp_pos)590 vh,vw = get_hw(temp)591 return ProntoClip(clips=clips, pos=pos, times=times, vh=vh, vw=vw, end=duration)592def fresh_start_effect(text='', font_size=40, font='Poppins-ExtraBold.ttf', theme=[16,184,254],593 color='white', wrap_width=35, start=0, end=5, fps=30, img=None, vh=540, vw=960, pos=[0.5,0.15], **kwargs):594 duration = end-start595 text_pos = copy.deepcopy(pos)596 clips = []597 pos = []598 times = []599 bg = solid_color_img((vh, vw, 3), alpha=170, color=theme)600 clips.append(mp.ImageClip(bg, duration=duration))601 pos.append([0,0])602 times.append([0,-1])603 604 if len(text) > 0:605 temp = text_template(text=text, temp_alpha=0, align='center', text_bg_alpha=0, font_size=font_size,606 font=font, gap=0, full_text_bg=True, color=color, wrap_width=wrap_width)607 th,tw = get_hw(temp)608 text_clip = mp.ImageClip(temp, duration=duration-0.2).set_fadein(0.5)609 clips.append(text_clip)610 pos.append(text_pos)611 times.append(0.2)612 underline_clip = mp.ImageClip(solid_color_img((10, 75, 3), color=color), duration=duration-0.1).set_fadein(0.5)613 clips.append(underline_clip)614 times.append(0.1)615 pos.append([0.5,f'fwd_posy+{th+10}'])616 return ProntoClip(clips=clips, pos=pos, times=times, vh=vh, vw=vw, end=duration, fps=fps)617def sap_effect(text='', font_size1=35, font1='FranklinGothic_Bold.ttf', font_size2=25, font2='FranklinGothic-Light.ttf',618 theme=[255,215,0], color='white', start=0, end=5, fps=30, vw=960, **kwargs):619 620 duration = end-start621 clips = []622 pos = []623 times = []624 625 if len(text) == 0:626 return blank_clip(duration)627 if not is_list(text):628 text = [text]629 t1 = text[0]630 text1 = text_template(text=t1, wrap_width=25, font=font1, font_size=font_size1, gap=0,631 align='left', color=color, full_text_bg=True, text_bg_alpha=0)632 if len(text) > 1:633 t2 = text[1]634 else:635 t2 = ''636 text2 = text_template(text=t2, wrap_width=40, font=font2, font_size=font_size2, gap=0,637 align='left', color=color, full_text_bg=True, text_bg_alpha=0)638 chunks = 10639 an_dur = chunks/fps640 text1_an = HorizontalSlideAnimation(text1, direction='right', num_chunks=chunks, fps=fps).fwd641 text2_an = VerticalSlideAnimation(text2, direction='down', num_chunks=chunks, fps=30).fwd642 643 h1,w1 = get_hw(text1)644 h2,w2 = get_hw(text2)645 646 slider1 = solid_color_img(((h1+h2+10, vw//8, 3)), color=theme)647 sh,sw = get_hw(slider1)648 barw = 10649 bar = solid_color_img((sh,barw,3), color=theme)650 sh2, sw2 = sh, vw-sw+barw651 slider2 = solid_color_img((sh2,sw2,3), color=theme)652 653 slider1_an1 = HorizontalSlideAnimation(slider1, direction='right', num_chunks=chunks, fps=fps).fwd654 slider1_an2 = HorizontalSlideAnimation(slider1, direction='left', num_chunks=chunks, fps=30).bwd655 656 slider2_an1 = HorizontalSlideAnimation(slider2, direction='right', num_chunks=chunks, fps=fps).fwd657 slider2_an2 = HorizontalSlideAnimation(slider2, direction='left', num_chunks=chunks, fps=30).bwd658 bar_clip = mp.ImageClip(bar, duration=an_dur)659 660 clips = [slider1_an1, slider1_an2, bar_clip, text1_an, text2_an, slider2_an1, slider2_an2]661 pos = [[0.,0.], [0.,0.],662 [sw-barw, 0.],663 [f'fwd_posx+{barw+5}', 'fwd_posy+5'],664 ['fwd_posx', f'fwd_posy+{h1}'],665 ['fwd_posx2', 'fwd_posy2'], ['fwd_posx2', 'fwd_posy2']666 ]667 times = [0, an_dur,668 [an_dur, duration-an_dur],669 [an_dur, duration-an_dur],670 [an_dur*2, duration-an_dur],671 duration-an_dur*2,672 duration-an_dur,673 ]674 return ProntoClip(clips=clips, pos=pos, times=times, vh=sh, vw=vw, start=0, end=duration, fps=fps)675 676effects_dict = {'no_effect':no_effect, 'art_effect':art_effect, 'slide_effect':slide_effect, 'move_effect':move_effect,677 'slide_move_effect': slide_move_effect, 'candid_effect':candid_effect, 'bold_effect':bold_effect,678 'zoom_effect': zoom_effect, 'fresh_effect': fresh_effect, 'fresh_start_effect':fresh_start_effect,679 'sap_effect': sap_effect680 }681def slide_transition(v, direction='left', num_chunks=5, fps=30, vh=540, vw=960, clip_dur=5):682 if path_or_str(v):683 v = read_and_resize(v, dur=clip_dur, fps=fps, h=vh, w=vw)684 temp = first_frame(v)685 ans = {'down':VerticalSlideAnimation, 'up':VerticalSlideAnimation, 'right':HorizontalSlideAnimation, 'left':HorizontalSlideAnimation}686 an = ans[direction]687 trans_v = an(temp, direction=direction, num_chunks=num_chunks, fps=fps)688 return trans_v689def zoom_transition(v, zoom_chunks=5, zoom_scales=[0.2,1], pos=(0.5,0.5), bg=None, fps=30, vh=540, vw=960, clip_dur=5):690 if path_or_str(v):691 v = read_and_resize(v, dur=clip_dur, fps=fps, h=vh, w=vw)692 temp = first_frame(v)693 trans_v = ZoomAnimation(num_chunks=1, **locals_to_params(locals()))694 return trans_v695def fresh_transition(v, theme=[16,184,254], fps=30):696 if type(v).__name__ == 'ProntoClip':697 v = v.v698 vw,vh = v.size699 trans_direction = random.choice(['down', 'right'])700 ans = {'down':VerticalAppearAnimation, 'right':HorizontalAppearAnimation}701 trans_an = ans[trans_direction]702 return trans_an(solid_color_img((vh, vw, 3), color=theme, alpha=255),703 direction=trans_direction, num_chunks=10, fps=fps, reverse=True)704def add_transition(v, trans, start=0, end=5, fps=30):705 if trans is None:706 return v707 duration = end-start708 # print(trans['trans_name'], trans['trans_args'])709 trans_name = trans['trans_name']710 trans, trans_args = trans_dict[trans_name], trans.get('trans_args', {})711 trans = trans(v, **trans_args, fps=fps)712 trans_v = trans.v713 if 'fresh' in trans_name:714 trans_dur = 0715 else:716 trans_dur = trans.durs[0]717 vw,vh = trans_v.size718 v = ProntoClip(clips=[v,trans_v], times=[[trans_dur, -1], 0], vh=vh, vw=vw, start=0, end=duration)719 # save_video(v, 'trans.mp4')720 return v721def add_clip_effect(v, effect, fps=30):722 if effect is None:723 return v724 effect, effect_args = clip_effects_dict[effect['effect_name']], effect['effect_args']725 v = effect(v, **effect_args, fps=fps)726 return v727trans_dict = {'slide_transition': slide_transition, 'zoom_transition':zoom_transition, 'fresh_transition':fresh_transition}728def fresh_end_effect(v, start=0, end=5, theme=[16,184,254], **kwargs):729 duration = end-start730 vw,vh = v.size731 bg = solid_color_img((vh,vw,3), color=theme, alpha=255)732 bg_clip = mp.ImageClip(bg, duration=duration)733 duration = max(duration, v.duration)734 return ProntoClip(clips=[v, bg_clip], pos=[[0,0], [0,0]], times=[[0,-1], [start, end]], vh=vh, vw=vw, end=duration)735clip_effects_dict = {'fresh_end_effect':fresh_end_effect}736class ProntoClip(ProntoClass):737 def __init__(self, bg_clip='', clips=[], vh=540, vw=960, start=0, end=5, pos=[], times=[], music_files=[], music_file='',738 vo_files=[], vo_file='', logger=None,**kwargs):739 super().__init__(**locals_to_params(locals()))740 self.logger=logger741 self.duration = end-start742 self.first_frames = []743 for i,c in enumerate(self.clips):744 self.first_frames.append(first_frame(c))745 if type(c).__name__ == 'ProntoClip':746 self.clips[i] = c.v747 if path_or_str(bg_clip):748 bg_clip = str(bg_clip)749 if self.logger:750 self.logger.debug(f'**************** BG CLIP = {bg_clip}')751 if len(bg_clip) > 0:752 bg_clip = read_and_resize(bg_clip, dur=self.duration, h=vh, w=vw)753 self.first_frames.insert(0, first_frame(bg_clip))...

Full Screen

Full Screen

_page.py

Source:_page.py Github

copy

Full Screen

...317 selector: str,318 timeout: float = None,319 state: Literal["attached", "detached", "hidden", "visible"] = None,320 ) -> Optional[ElementHandle]:321 return await self._main_frame.wait_for_selector(**locals_to_params(locals()))322 async def is_checked(self, selector: str, timeout: float = None) -> bool:323 return await self._main_frame.is_checked(**locals_to_params(locals()))324 async def is_disabled(self, selector: str, timeout: float = None) -> bool:325 return await self._main_frame.is_disabled(**locals_to_params(locals()))326 async def is_editable(self, selector: str, timeout: float = None) -> bool:327 return await self._main_frame.is_editable(**locals_to_params(locals()))328 async def is_enabled(self, selector: str, timeout: float = None) -> bool:329 return await self._main_frame.is_enabled(**locals_to_params(locals()))330 async def is_hidden(self, selector: str, timeout: float = None) -> bool:331 return await self._main_frame.is_hidden(**locals_to_params(locals()))332 async def is_visible(self, selector: str, timeout: float = None) -> bool:333 return await self._main_frame.is_visible(**locals_to_params(locals()))334 async def dispatch_event(335 self, selector: str, type: str, eventInit: Dict = None, timeout: float = None336 ) -> None:337 return await self._main_frame.dispatch_event(**locals_to_params(locals()))338 async def evaluate(self, expression: str, arg: Serializable = None) -> Any:339 return await self._main_frame.evaluate(expression, arg)340 async def evaluate_handle(341 self, expression: str, arg: Serializable = None342 ) -> JSHandle:343 return await self._main_frame.evaluate_handle(expression, arg)344 async def eval_on_selector(345 self,346 selector: str,347 expression: str,348 arg: Serializable = None,349 ) -> Any:350 return await self._main_frame.eval_on_selector(selector, expression, arg)351 async def eval_on_selector_all(352 self,353 selector: str,354 expression: str,355 arg: Serializable = None,356 ) -> Any:357 return await self._main_frame.eval_on_selector_all(selector, expression, arg)358 async def add_script_tag(359 self,360 url: str = None,361 path: Union[str, Path] = None,362 content: str = None,363 type: str = None,364 ) -> ElementHandle:365 return await self._main_frame.add_script_tag(**locals_to_params(locals()))366 async def add_style_tag(367 self, url: str = None, path: Union[str, Path] = None, content: str = None368 ) -> ElementHandle:369 return await self._main_frame.add_style_tag(**locals_to_params(locals()))370 async def expose_function(self, name: str, callback: Callable) -> None:371 await self.expose_binding(name, lambda source, *args: callback(*args))372 async def expose_binding(373 self, name: str, callback: Callable, handle: bool = None374 ) -> None:375 if name in self._bindings:376 raise Error(f'Function "{name}" has been already registered')377 if name in self._browser_context._bindings:378 raise Error(379 f'Function "{name}" has been already registered in the browser context'380 )381 self._bindings[name] = callback382 await self._channel.send(383 "exposeBinding", dict(name=name, needsHandle=handle or False)384 )385 async def set_extra_http_headers(self, headers: Dict[str, str]) -> None:386 await self._channel.send(387 "setExtraHTTPHeaders", dict(headers=serialize_headers(headers))388 )389 @property390 def url(self) -> str:391 return self._main_frame.url392 async def content(self) -> str:393 return await self._main_frame.content()394 async def set_content(395 self,396 html: str,397 timeout: float = None,398 waitUntil: DocumentLoadState = None,399 ) -> None:400 return await self._main_frame.set_content(**locals_to_params(locals()))401 async def goto(402 self,403 url: str,404 timeout: float = None,405 waitUntil: DocumentLoadState = None,406 referer: str = None,407 ) -> Optional[Response]:408 return await self._main_frame.goto(**locals_to_params(locals()))409 async def reload(410 self,411 timeout: float = None,412 waitUntil: DocumentLoadState = None,413 ) -> Optional[Response]:414 return from_nullable_channel(415 await self._channel.send("reload", locals_to_params(locals()))416 )417 async def wait_for_load_state(418 self, state: DocumentLoadState = None, timeout: float = None419 ) -> None:420 return await self._main_frame.wait_for_load_state(**locals_to_params(locals()))421 async def wait_for_event(422 self, event: str, predicate: Callable = None, timeout: float = None423 ) -> Any:424 async with self.expect_event(event, predicate, timeout) as event_info:425 pass426 return await event_info427 async def go_back(428 self,429 timeout: float = None,430 waitUntil: DocumentLoadState = None,431 ) -> Optional[Response]:432 return from_nullable_channel(433 await self._channel.send("goBack", locals_to_params(locals()))434 )435 async def go_forward(436 self,437 timeout: float = None,438 waitUntil: DocumentLoadState = None,439 ) -> Optional[Response]:440 return from_nullable_channel(441 await self._channel.send("goForward", locals_to_params(locals()))442 )443 async def emulate_media(444 self,445 media: Literal["print", "screen"] = None,446 colorScheme: ColorScheme = None,447 ) -> None:448 await self._channel.send("emulateMedia", locals_to_params(locals()))449 async def set_viewport_size(self, viewportSize: ViewportSize) -> None:450 self._viewport_size = viewportSize451 await self._channel.send("setViewportSize", locals_to_params(locals()))452 @property453 def viewport_size(self) -> Optional[ViewportSize]:454 return self._viewport_size455 async def bring_to_front(self) -> None:456 await self._channel.send("bringToFront")457 async def add_init_script(458 self, script: str = None, path: Union[str, Path] = None459 ) -> None:460 if path:461 with open(path, "r") as file:462 script = file.read()463 if not isinstance(script, str):464 raise Error("Either path or source parameter must be specified")465 await self._channel.send("addInitScript", dict(source=script))466 async def route(self, url: URLMatch, handler: RouteHandler) -> None:467 self._routes.append(RouteHandlerEntry(URLMatcher(url), handler))468 if len(self._routes) == 1:469 await self._channel.send(470 "setNetworkInterceptionEnabled", dict(enabled=True)471 )472 async def unroute(473 self, url: URLMatch, handler: Optional[RouteHandler] = None474 ) -> None:475 self._routes = list(476 filter(477 lambda r: r.matcher.match != url or (handler and r.handler != handler),478 self._routes,479 )480 )481 if len(self._routes) == 0:482 await self._channel.send(483 "setNetworkInterceptionEnabled", dict(enabled=False)484 )485 async def screenshot(486 self,487 timeout: float = None,488 type: Literal["jpeg", "png"] = None,489 path: Union[str, Path] = None,490 quality: int = None,491 omitBackground: bool = None,492 fullPage: bool = None,493 clip: FloatRect = None,494 ) -> bytes:495 params = locals_to_params(locals())496 if "path" in params:497 del params["path"]498 encoded_binary = await self._channel.send("screenshot", params)499 decoded_binary = base64.b64decode(encoded_binary)500 if path:501 with open(path, "wb") as fd:502 fd.write(decoded_binary)503 return decoded_binary504 async def title(self) -> str:505 return await self._main_frame.title()506 async def close(self, runBeforeUnload: bool = None) -> None:507 try:508 await self._channel.send("close", locals_to_params(locals()))509 if self._owned_context:510 await self._owned_context.close()511 except Exception as e:512 if not is_safe_close_error(e):513 raise e514 def is_closed(self) -> bool:515 return self._is_closed516 async def click(517 self,518 selector: str,519 modifiers: List[KeyboardModifier] = None,520 position: Position = None,521 delay: float = None,522 button: MouseButton = None,523 clickCount: int = None,524 timeout: float = None,525 force: bool = None,526 noWaitAfter: bool = None,527 ) -> None:528 return await self._main_frame.click(**locals_to_params(locals()))529 async def dblclick(530 self,531 selector: str,532 modifiers: List[KeyboardModifier] = None,533 position: Position = None,534 delay: float = None,535 button: MouseButton = None,536 timeout: float = None,537 force: bool = None,538 noWaitAfter: bool = None,539 ) -> None:540 return await self._main_frame.dblclick(**locals_to_params(locals()))541 async def tap(542 self,543 selector: str,544 modifiers: List[KeyboardModifier] = None,545 position: Position = None,546 timeout: float = None,547 force: bool = None,548 noWaitAfter: bool = None,549 ) -> None:550 return await self._main_frame.tap(**locals_to_params(locals()))551 async def fill(552 self, selector: str, value: str, timeout: float = None, noWaitAfter: bool = None553 ) -> None:554 return await self._main_frame.fill(**locals_to_params(locals()))555 async def focus(self, selector: str, timeout: float = None) -> None:556 return await self._main_frame.focus(**locals_to_params(locals()))557 async def text_content(self, selector: str, timeout: float = None) -> Optional[str]:558 return await self._main_frame.text_content(**locals_to_params(locals()))559 async def inner_text(self, selector: str, timeout: float = None) -> str:560 return await self._main_frame.inner_text(**locals_to_params(locals()))561 async def inner_html(self, selector: str, timeout: float = None) -> str:562 return await self._main_frame.inner_html(**locals_to_params(locals()))563 async def get_attribute(564 self, selector: str, name: str, timeout: float = None565 ) -> Optional[str]:566 return await self._main_frame.get_attribute(**locals_to_params(locals()))567 async def hover(568 self,569 selector: str,570 modifiers: List[KeyboardModifier] = None,571 position: Position = None,572 timeout: float = None,573 force: bool = None,574 ) -> None:575 return await self._main_frame.hover(**locals_to_params(locals()))576 async def select_option(577 self,578 selector: str,579 value: Union[str, List[str]] = None,580 index: Union[int, List[int]] = None,581 label: Union[str, List[str]] = None,582 element: Union["ElementHandle", List["ElementHandle"]] = None,583 timeout: float = None,584 noWaitAfter: bool = None,585 ) -> List[str]:586 params = locals_to_params(locals())587 return await self._main_frame.select_option(**params)588 async def set_input_files(589 self,590 selector: str,591 files: Union[str, Path, FilePayload, List[Union[str, Path]], List[FilePayload]],592 timeout: float = None,593 noWaitAfter: bool = None,594 ) -> None:595 return await self._main_frame.set_input_files(**locals_to_params(locals()))596 async def type(597 self,598 selector: str,599 text: str,600 delay: float = None,601 timeout: float = None,602 noWaitAfter: bool = None,603 ) -> None:604 return await self._main_frame.type(**locals_to_params(locals()))605 async def press(606 self,607 selector: str,608 key: str,609 delay: float = None,610 timeout: float = None,611 noWaitAfter: bool = None,612 ) -> None:613 return await self._main_frame.press(**locals_to_params(locals()))614 async def check(615 self,616 selector: str,617 timeout: float = None,618 force: bool = None,619 noWaitAfter: bool = None,620 ) -> None:621 return await self._main_frame.check(**locals_to_params(locals()))622 async def uncheck(623 self,624 selector: str,625 timeout: float = None,626 force: bool = None,627 noWaitAfter: bool = None,628 ) -> None:629 return await self._main_frame.uncheck(**locals_to_params(locals()))630 async def wait_for_timeout(self, timeout: float) -> None:631 await self._main_frame.wait_for_timeout(timeout)632 async def wait_for_function(633 self,634 expression: str,635 arg: Serializable = None,636 timeout: float = None,637 polling: Union[float, Literal["raf"]] = None,638 ) -> JSHandle:639 return await self._main_frame.wait_for_function(**locals_to_params(locals()))640 @property641 def workers(self) -> List["Worker"]:642 return self._workers.copy()643 async def pause(self) -> None:644 await self._browser_context._pause()645 async def pdf(646 self,647 scale: float = None,648 displayHeaderFooter: bool = None,649 headerTemplate: str = None,650 footerTemplate: str = None,651 printBackground: bool = None,652 landscape: bool = None,653 pageRanges: str = None,654 format: str = None,655 width: Union[str, float] = None,656 height: Union[str, float] = None,657 preferCSSPageSize: bool = None,658 margin: PdfMargins = None,659 path: Union[str, Path] = None,660 ) -> bytes:661 params = locals_to_params(locals())662 if "path" in params:663 del params["path"]664 encoded_binary = await self._channel.send("pdf", params)665 decoded_binary = base64.b64decode(encoded_binary)666 if path:667 with open(path, "wb") as fd:668 fd.write(decoded_binary)669 return decoded_binary670 @property671 def video(672 self,673 ) -> Optional[Video]:674 context_options = self._browser_context._options675 if "recordVideo" not in context_options:...

Full Screen

Full Screen

_locator.py

Source:_locator.py Github

copy

Full Screen

...110 force: bool = None,111 noWaitAfter: bool = None,112 trial: bool = None,113 ) -> None:114 params = locals_to_params(locals())115 return await self._frame.check(self._selector, strict=True, **params)116 async def click(117 self,118 modifiers: List[KeyboardModifier] = None,119 position: Position = None,120 delay: float = None,121 button: MouseButton = None,122 clickCount: int = None,123 timeout: float = None,124 force: bool = None,125 noWaitAfter: bool = None,126 trial: bool = None,127 ) -> None:128 params = locals_to_params(locals())129 return await self._frame.click(self._selector, strict=True, **params)130 async def dblclick(131 self,132 modifiers: List[KeyboardModifier] = None,133 position: Position = None,134 delay: float = None,135 button: MouseButton = None,136 timeout: float = None,137 force: bool = None,138 noWaitAfter: bool = None,139 trial: bool = None,140 ) -> None:141 params = locals_to_params(locals())142 return await self._frame.dblclick(self._selector, strict=True, **params)143 async def dispatch_event(144 self,145 type: str,146 eventInit: Dict = None,147 timeout: float = None,148 ) -> None:149 params = locals_to_params(locals())150 return await self._frame.dispatch_event(self._selector, strict=True, **params)151 async def evaluate(152 self, expression: str, arg: Serializable = None, timeout: float = None153 ) -> Any:154 return await self._with_element(155 lambda h, _: h.evaluate(expression, arg),156 timeout,157 )158 async def evaluate_all(self, expression: str, arg: Serializable = None) -> Any:159 params = locals_to_params(locals())160 return await self._frame.eval_on_selector_all(self._selector, **params)161 async def evaluate_handle(162 self, expression: str, arg: Serializable = None, timeout: float = None163 ) -> "JSHandle":164 return await self._with_element(165 lambda h, o: h.evaluate_handle(expression, arg), timeout166 )167 async def fill(168 self,169 value: str,170 timeout: float = None,171 noWaitAfter: bool = None,172 force: bool = None,173 ) -> None:174 params = locals_to_params(locals())175 return await self._frame.fill(self._selector, strict=True, **params)176 def locator(177 self,178 selector: str,179 has_text: Union[str, Pattern] = None,180 has: "Locator" = None,181 ) -> "Locator":182 return Locator(183 self._frame,184 f"{self._selector} >> {selector}",185 has_text=has_text,186 has=has,187 )188 def frame_locator(self, selector: str) -> "FrameLocator":189 return FrameLocator(self._frame, self._selector + " >> " + selector)190 async def element_handle(191 self,192 timeout: float = None,193 ) -> ElementHandle:194 params = locals_to_params(locals())195 handle = await self._frame.wait_for_selector(196 self._selector, strict=True, state="attached", **params197 )198 assert handle199 return handle200 async def element_handles(self) -> List[ElementHandle]:201 return await self._frame.query_selector_all(self._selector)202 @property203 def first(self) -> "Locator":204 return Locator(self._frame, f"{self._selector} >> nth=0")205 @property206 def last(self) -> "Locator":207 return Locator(self._frame, f"{self._selector} >> nth=-1")208 def nth(self, index: int) -> "Locator":209 return Locator(self._frame, f"{self._selector} >> nth={index}")210 async def focus(self, timeout: float = None) -> None:211 params = locals_to_params(locals())212 return await self._frame.focus(self._selector, strict=True, **params)213 async def count(214 self,215 ) -> int:216 return await self._frame._query_count(self._selector)217 async def drag_to(218 self,219 target: "Locator",220 force: bool = None,221 noWaitAfter: bool = None,222 timeout: float = None,223 trial: bool = None,224 sourcePosition: Position = None,225 targetPosition: Position = None,226 ) -> None:227 params = locals_to_params(locals())228 del params["target"]229 return await self._frame.drag_and_drop(230 self._selector, target._selector, strict=True, **params231 )232 async def get_attribute(self, name: str, timeout: float = None) -> Optional[str]:233 params = locals_to_params(locals())234 return await self._frame.get_attribute(235 self._selector,236 strict=True,237 **params,238 )239 async def hover(240 self,241 modifiers: List[KeyboardModifier] = None,242 position: Position = None,243 timeout: float = None,244 force: bool = None,245 trial: bool = None,246 ) -> None:247 params = locals_to_params(locals())248 return await self._frame.hover(249 self._selector,250 strict=True,251 **params,252 )253 async def inner_html(self, timeout: float = None) -> str:254 params = locals_to_params(locals())255 return await self._frame.inner_html(256 self._selector,257 strict=True,258 **params,259 )260 async def inner_text(self, timeout: float = None) -> str:261 params = locals_to_params(locals())262 return await self._frame.inner_text(263 self._selector,264 strict=True,265 **params,266 )267 async def input_value(self, timeout: float = None) -> str:268 params = locals_to_params(locals())269 return await self._frame.input_value(270 self._selector,271 strict=True,272 **params,273 )274 async def is_checked(self, timeout: float = None) -> bool:275 params = locals_to_params(locals())276 return await self._frame.is_checked(277 self._selector,278 strict=True,279 **params,280 )281 async def is_disabled(self, timeout: float = None) -> bool:282 params = locals_to_params(locals())283 return await self._frame.is_disabled(284 self._selector,285 strict=True,286 **params,287 )288 async def is_editable(self, timeout: float = None) -> bool:289 params = locals_to_params(locals())290 return await self._frame.is_editable(291 self._selector,292 strict=True,293 **params,294 )295 async def is_enabled(self, timeout: float = None) -> bool:296 params = locals_to_params(locals())297 return await self._frame.is_editable(298 self._selector,299 strict=True,300 **params,301 )302 async def is_hidden(self, timeout: float = None) -> bool:303 params = locals_to_params(locals())304 return await self._frame.is_hidden(305 self._selector,306 strict=True,307 **params,308 )309 async def is_visible(self, timeout: float = None) -> bool:310 params = locals_to_params(locals())311 return await self._frame.is_visible(312 self._selector,313 strict=True,314 **params,315 )316 async def press(317 self,318 key: str,319 delay: float = None,320 timeout: float = None,321 noWaitAfter: bool = None,322 ) -> None:323 params = locals_to_params(locals())324 return await self._frame.press(self._selector, strict=True, **params)325 async def screenshot(326 self,327 timeout: float = None,328 type: Literal["jpeg", "png"] = None,329 path: Union[str, pathlib.Path] = None,330 quality: int = None,331 omitBackground: bool = None,332 animations: Literal["allow", "disabled"] = None,333 caret: Literal["hide", "initial"] = None,334 scale: Literal["css", "device"] = None,335 mask: List["Locator"] = None,336 ) -> bytes:337 params = locals_to_params(locals())338 return await self._with_element(339 lambda h, timeout: h.screenshot(timeout=timeout, **params)340 )341 async def scroll_into_view_if_needed(342 self,343 timeout: float = None,344 ) -> None:345 return await self._with_element(346 lambda h, timeout: h.scroll_into_view_if_needed(timeout=timeout),347 timeout,348 )349 async def select_option(350 self,351 value: Union[str, List[str]] = None,352 index: Union[int, List[int]] = None,353 label: Union[str, List[str]] = None,354 element: Union["ElementHandle", List["ElementHandle"]] = None,355 timeout: float = None,356 noWaitAfter: bool = None,357 force: bool = None,358 ) -> List[str]:359 params = locals_to_params(locals())360 return await self._frame.select_option(361 self._selector,362 strict=True,363 **params,364 )365 async def select_text(self, force: bool = None, timeout: float = None) -> None:366 params = locals_to_params(locals())367 return await self._with_element(368 lambda h, timeout: h.select_text(timeout=timeout, **params), timeout369 )370 async def set_input_files(371 self,372 files: Union[373 str,374 pathlib.Path,375 FilePayload,376 List[Union[str, pathlib.Path]],377 List[FilePayload],378 ],379 timeout: float = None,380 noWaitAfter: bool = None,381 ) -> None:382 params = locals_to_params(locals())383 return await self._frame.set_input_files(384 self._selector,385 strict=True,386 **params,387 )388 async def tap(389 self,390 modifiers: List[KeyboardModifier] = None,391 position: Position = None,392 timeout: float = None,393 force: bool = None,394 noWaitAfter: bool = None,395 trial: bool = None,396 ) -> None:397 params = locals_to_params(locals())398 return await self._frame.tap(399 self._selector,400 strict=True,401 **params,402 )403 async def text_content(self, timeout: float = None) -> Optional[str]:404 params = locals_to_params(locals())405 return await self._frame.text_content(406 self._selector,407 strict=True,408 **params,409 )410 async def type(411 self,412 text: str,413 delay: float = None,414 timeout: float = None,415 noWaitAfter: bool = None,416 ) -> None:417 params = locals_to_params(locals())418 return await self._frame.type(419 self._selector,420 strict=True,421 **params,422 )423 async def uncheck(424 self,425 position: Position = None,426 timeout: float = None,427 force: bool = None,428 noWaitAfter: bool = None,429 trial: bool = None,430 ) -> None:431 params = locals_to_params(locals())432 return await self._frame.uncheck(433 self._selector,434 strict=True,435 **params,436 )437 async def all_inner_texts(438 self,439 ) -> List[str]:440 return await self._frame.eval_on_selector_all(441 self._selector, "ee => ee.map(e => e.innerText)"442 )443 async def all_text_contents(444 self,445 ) -> List[str]:...

Full Screen

Full Screen

_frame.py

Source:_frame.py Github

copy

Full Screen

...99 ) -> Optional[Response]:100 return cast(101 Optional[Response],102 from_nullable_channel(103 await self._channel.send("goto", locals_to_params(locals()))104 ),105 )106 def _setup_navigation_wait_helper(self, timeout: float = None) -> WaitHelper:107 wait_helper = WaitHelper(self._loop)108 wait_helper.reject_on_event(109 self._page, "close", Error("Navigation failed because page was closed!")110 )111 wait_helper.reject_on_event(112 self._page, "crash", Error("Navigation failed because page crashed!")113 )114 wait_helper.reject_on_event(115 self._page,116 "framedetached",117 Error("Navigating frame was detached!"),118 lambda frame: frame == self,119 )120 if timeout is None:121 timeout = self._page._timeout_settings.navigation_timeout()122 wait_helper.reject_on_timeout(timeout, f"Timeout {timeout}ms exceeded.")123 return wait_helper124 def expect_navigation(125 self,126 url: URLMatch = None,127 wait_until: DocumentLoadState = None,128 timeout: float = None,129 ) -> EventContextManagerImpl[Response]:130 if not wait_until:131 wait_until = "load"132 if timeout is None:133 timeout = self._page._timeout_settings.navigation_timeout()134 deadline = monotonic_time() + timeout135 wait_helper = self._setup_navigation_wait_helper(timeout)136 matcher = URLMatcher(url) if url else None137 def predicate(event: Any) -> bool:138 # Any failed navigation results in a rejection.139 if event.get("error"):140 return True141 return not matcher or matcher.matches(event["url"])142 wait_helper.wait_for_event(143 self._event_emitter,144 "navigated",145 predicate=predicate,146 )147 async def continuation() -> Optional[Response]:148 event = await wait_helper.result()149 if "error" in event:150 raise Error(event["error"])151 if wait_until not in self._load_states:152 t = deadline - monotonic_time()153 if t > 0:154 await self.wait_for_load_state(state=wait_until, timeout=t)155 if "newDocument" in event and "request" in event["newDocument"]:156 request = from_channel(event["newDocument"]["request"])157 return await request.response()158 return None159 return EventContextManagerImpl(asyncio.create_task(continuation()))160 async def wait_for_load_state(161 self, state: DocumentLoadState = None, timeout: float = None162 ) -> None:163 if not state:164 state = "load"165 if state not in ("load", "domcontentloaded", "networkidle"):166 raise Error("state: expected one of (load|domcontentloaded|networkidle)")167 if state in self._load_states:168 return169 wait_helper = self._setup_navigation_wait_helper(timeout)170 wait_helper.wait_for_event(171 self._event_emitter, "loadstate", lambda s: s == state172 )173 await wait_helper.result()174 async def frame_element(self) -> ElementHandle:175 return from_channel(await self._channel.send("frameElement"))176 async def evaluate(self, expression: str, arg: Serializable = None) -> Any:177 return parse_result(178 await self._channel.send(179 "evaluateExpression",180 dict(181 expression=expression,182 arg=serialize_argument(arg),183 ),184 )185 )186 async def evaluate_handle(187 self, expression: str, arg: Serializable = None188 ) -> JSHandle:189 return from_channel(190 await self._channel.send(191 "evaluateExpressionHandle",192 dict(193 expression=expression,194 arg=serialize_argument(arg),195 ),196 )197 )198 async def query_selector(self, selector: str) -> Optional[ElementHandle]:199 return from_nullable_channel(200 await self._channel.send("querySelector", dict(selector=selector))201 )202 async def query_selector_all(self, selector: str) -> List[ElementHandle]:203 return list(204 map(205 cast(ElementHandle, from_channel),206 await self._channel.send("querySelectorAll", dict(selector=selector)),207 )208 )209 async def wait_for_selector(210 self,211 selector: str,212 timeout: float = None,213 state: Literal["attached", "detached", "hidden", "visible"] = None,214 ) -> Optional[ElementHandle]:215 return from_nullable_channel(216 await self._channel.send("waitForSelector", locals_to_params(locals()))217 )218 async def is_checked(self, selector: str, timeout: float = None) -> bool:219 return await self._channel.send("isChecked", locals_to_params(locals()))220 async def is_disabled(self, selector: str, timeout: float = None) -> bool:221 return await self._channel.send("isDisabled", locals_to_params(locals()))222 async def is_editable(self, selector: str, timeout: float = None) -> bool:223 return await self._channel.send("isEditable", locals_to_params(locals()))224 async def is_enabled(self, selector: str, timeout: float = None) -> bool:225 return await self._channel.send("isEnabled", locals_to_params(locals()))226 async def is_hidden(self, selector: str, timeout: float = None) -> bool:227 return await self._channel.send("isHidden", locals_to_params(locals()))228 async def is_visible(self, selector: str, timeout: float = None) -> bool:229 return await self._channel.send("isVisible", locals_to_params(locals()))230 async def dispatch_event(231 self, selector: str, type: str, eventInit: Dict = None, timeout: float = None232 ) -> None:233 await self._channel.send(234 "dispatchEvent",235 dict(selector=selector, type=type, eventInit=serialize_argument(eventInit)),236 )237 async def eval_on_selector(238 self,239 selector: str,240 expression: str,241 arg: Serializable = None,242 ) -> Any:243 return parse_result(244 await self._channel.send(245 "evalOnSelector",246 dict(247 selector=selector,248 expression=expression,249 arg=serialize_argument(arg),250 ),251 )252 )253 async def eval_on_selector_all(254 self,255 selector: str,256 expression: str,257 arg: Serializable = None,258 ) -> Any:259 return parse_result(260 await self._channel.send(261 "evalOnSelectorAll",262 dict(263 selector=selector,264 expression=expression,265 arg=serialize_argument(arg),266 ),267 )268 )269 async def content(self) -> str:270 return await self._channel.send("content")271 async def set_content(272 self,273 html: str,274 timeout: float = None,275 waitUntil: DocumentLoadState = None,276 ) -> None:277 await self._channel.send("setContent", locals_to_params(locals()))278 @property279 def name(self) -> str:280 return self._name or ""281 @property282 def url(self) -> str:283 return self._url or ""284 @property285 def parent_frame(self) -> Optional["Frame"]:286 return self._parent_frame287 @property288 def child_frames(self) -> List["Frame"]:289 return self._child_frames.copy()290 def is_detached(self) -> bool:291 return self._detached292 async def add_script_tag(293 self,294 url: str = None,295 path: Union[str, Path] = None,296 content: str = None,297 type: str = None,298 ) -> ElementHandle:299 params = locals_to_params(locals())300 if path:301 with open(path, "r") as file:302 params["content"] = file.read() + "\n//# sourceURL=" + str(Path(path))303 del params["path"]304 return from_channel(await self._channel.send("addScriptTag", params))305 async def add_style_tag(306 self, url: str = None, path: Union[str, Path] = None, content: str = None307 ) -> ElementHandle:308 params = locals_to_params(locals())309 if path:310 with open(path, "r") as file:311 params["content"] = (312 file.read() + "\n/*# sourceURL=" + str(Path(path)) + "*/"313 )314 del params["path"]315 return from_channel(await self._channel.send("addStyleTag", params))316 async def click(317 self,318 selector: str,319 modifiers: List[KeyboardModifier] = None,320 position: Position = None,321 delay: float = None,322 button: MouseButton = None,323 clickCount: int = None,324 timeout: float = None,325 force: bool = None,326 noWaitAfter: bool = None,327 ) -> None:328 await self._channel.send("click", locals_to_params(locals()))329 async def dblclick(330 self,331 selector: str,332 modifiers: List[KeyboardModifier] = None,333 position: Position = None,334 delay: float = None,335 button: MouseButton = None,336 timeout: float = None,337 force: bool = None,338 noWaitAfter: bool = None,339 ) -> None:340 await self._channel.send("dblclick", locals_to_params(locals()))341 async def tap(342 self,343 selector: str,344 modifiers: List[KeyboardModifier] = None,345 position: Position = None,346 timeout: float = None,347 force: bool = None,348 noWaitAfter: bool = None,349 ) -> None:350 await self._channel.send("tap", locals_to_params(locals()))351 async def fill(352 self, selector: str, value: str, timeout: float = None, noWaitAfter: bool = None353 ) -> None:354 await self._channel.send("fill", locals_to_params(locals()))355 async def focus(self, selector: str, timeout: float = None) -> None:356 await self._channel.send("focus", locals_to_params(locals()))357 async def text_content(self, selector: str, timeout: float = None) -> Optional[str]:358 return await self._channel.send("textContent", locals_to_params(locals()))359 async def inner_text(self, selector: str, timeout: float = None) -> str:360 return await self._channel.send("innerText", locals_to_params(locals()))361 async def inner_html(self, selector: str, timeout: float = None) -> str:362 return await self._channel.send("innerHTML", locals_to_params(locals()))363 async def get_attribute(364 self, selector: str, name: str, timeout: float = None365 ) -> Optional[str]:366 return await self._channel.send("getAttribute", locals_to_params(locals()))367 async def hover(368 self,369 selector: str,370 modifiers: List[KeyboardModifier] = None,371 position: Position = None,372 timeout: float = None,373 force: bool = None,374 ) -> None:375 await self._channel.send("hover", locals_to_params(locals()))376 async def select_option(377 self,378 selector: str,379 value: Union[str, List[str]] = None,380 index: Union[int, List[int]] = None,381 label: Union[str, List[str]] = None,382 element: Union["ElementHandle", List["ElementHandle"]] = None,383 timeout: float = None,384 noWaitAfter: bool = None,385 ) -> List[str]:386 params = locals_to_params(387 dict(388 selector=selector,389 timeout=timeout,390 noWaitAfter=noWaitAfter,391 **convert_select_option_values(value, index, label, element),392 )393 )394 return await self._channel.send("selectOption", params)395 async def set_input_files(396 self,397 selector: str,398 files: Union[str, Path, FilePayload, List[Union[str, Path]], List[FilePayload]],399 timeout: float = None,400 noWaitAfter: bool = None,401 ) -> None:402 params = locals_to_params(locals())403 params["files"] = normalize_file_payloads(files)404 await self._channel.send("setInputFiles", params)405 async def type(406 self,407 selector: str,408 text: str,409 delay: float = None,410 timeout: float = None,411 noWaitAfter: bool = None,412 ) -> None:413 await self._channel.send("type", locals_to_params(locals()))414 async def press(415 self,416 selector: str,417 key: str,418 delay: float = None,419 timeout: float = None,420 noWaitAfter: bool = None,421 ) -> None:422 await self._channel.send("press", locals_to_params(locals()))423 async def check(424 self,425 selector: str,426 timeout: float = None,427 force: bool = None,428 noWaitAfter: bool = None,429 ) -> None:430 await self._channel.send("check", locals_to_params(locals()))431 async def uncheck(432 self,433 selector: str,434 timeout: float = None,435 force: bool = None,436 noWaitAfter: bool = None,437 ) -> None:438 await self._channel.send("uncheck", locals_to_params(locals()))439 async def wait_for_timeout(self, timeout: float) -> None:440 await self._connection._loop.create_task(asyncio.sleep(timeout / 1000))441 async def wait_for_function(442 self,443 expression: str,444 arg: Serializable = None,445 timeout: float = None,446 polling: Union[float, Literal["raf"]] = None,447 ) -> JSHandle:448 params = locals_to_params(locals())449 params["arg"] = serialize_argument(arg)450 return from_channel(await self._channel.send("waitForFunction", params))451 async def title(self) -> str:...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python 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