### Install CodeVideoRenderer using pip Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_sources/install.rst This command installs the CodeVideoRenderer package and its Python dependencies using pip. Ensure you have Python 3.9 or higher installed. ```bash pip install CodeVideoRenderer ``` -------------------------------- ### Start Manim Rendering Process (Python) Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Initiates the Manim rendering process for a scene. This function displays a detailed progress bar showing speed and remaining time. It accepts a boolean parameter to control whether the rendering progress is output to the console. ```python @type_checker def render(self, output: bool = DEFAULT_OUTPUT_VALUE): r""" 启动 :math:`\mathbb{M}\text{anim}` 渲染流程,并显示包含速度和剩余时间的详细进度条。 Parameters ---------- output : ``bool`` 是否输出渲染进度到控制台。 """ self.output = output self.scene.render() ``` -------------------------------- ### RichProgressBarLogger Initialization and Setup Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Initializes a custom progress bar logger using the Rich library. This class extends ProgressBarLogger to provide enhanced visual feedback during video rendering. It sets up the Rich progress bar, manages its lifecycle, and customizes its appearance. ```python class RichProgressBarLogger(ProgressBarLogger): """ 一个进度条记录器,使用 Rich 库显示进度条。 """ def __init__( self, output: bool, title: str, init_state=None, bars=None, leave_bars=True, ignored_bars=None, logged_bars="all", print_messages=True, min_time_interval=0.1, ignore_bars_under=0, ): # 调用父类构造函数,初始化核心属性 super().__init__( init_state=init_state, bars=bars, ignored_bars=ignored_bars, logged_bars=logged_bars, ignore_bars_under=ignore_bars_under, min_time_interval=min_time_interval, ) # 初始化自定义属性 self.leave_bars = leave_bars self.print_messages = print_messages self.output = output self.title = title self.start_time = time.time() # 初始化 Rich 进度条 self.progress_bar = copy(default_progress_bar(self.output)) self.rich_bars = OrderedDict() # 存储 {bar_name: task_id} # 启动 Rich 进度条 if self.progress_bar and not self.progress_bar.live.is_started: self.progress_bar.start() ``` -------------------------------- ### Get All Pygments Languages Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Retrieves a list of all available language lexers supported by the Pygments library. This function iterates through all lexers and extracts their names, including sub-languages, to provide a comprehensive list for syntax highlighting or language detection. ```python def get_all_languages(): """ 获取所有可用的 Pygments 语言。 """ languages = [] for language in list(get_all_lexers()): if type(language[1]) == tuple: for subitem in language[1]: languages.append(subitem) return languages ``` -------------------------------- ### Override Manim Render Method for Timing and Logging Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR This Python code overrides the default Manim render method to include detailed logging and timing information. It logs the start and end of rendering, the renderer type (CPU/GPU), and the total render time. It also handles Manim configuration changes and restoration, and initiates post-rendering effects like glow. ```python def render(scene): """Override render to add timing log.""" if self.output: DEFAULT_OUTPUT_CONSOLE.log(f"Start rendering '{self.video_name}.mp4'.") DEFAULT_OUTPUT_CONSOLE.log("Start rendering CameraFollowCursorCVScene. [dim](by manim)[/]") if config.renderer == RendererType.CAIRO: DEFAULT_OUTPUT_CONSOLE.log('[blue]Currently using CPU (Cairo Renderer) for rendering.[/]') else: DEFAULT_OUTPUT_CONSOLE.log('[blue]Currently using GPU (OpenGL Renderer) for rendering.[/]') DEFAULT_OUTPUT_CONSOLE.log("Manim's config has been modified.") # 渲染并计算时间 with no_manim_output(): total_render_time = timeit(super().render, number=1) if self.output: DEFAULT_OUTPUT_CONSOLE.log(f"Successfully rendered CameraFollowCursorCVScene in {total_render_time:,.2f} seconds. [dim](by manim)[/]") del total_render_time # 恢复配置 config.disable_caching = self.origin_config['disable_caching'] config.renderer = self.origin_config['renderer'] if self.output: DEFAULT_OUTPUT_CONSOLE.log("Manim's config has been restored.") del self.origin_config if self.output: DEFAULT_OUTPUT_CONSOLE.log(f"Start adding glow effect to 'CameraFollowCursorCVScene.mp4'. [dim](by moviepy)[/]\n") # 添加发光效果 ``` -------------------------------- ### Get Type Name Utility Function Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Retrieves the name of a given type, specifically handling Union types by replacing '|' with 'or'. It also supports generic tuple types. ```python def typeName(item_type): """ 获取类型的名称,处理联合类型和泛型元组。 """ if isinstance(item_type, UnionType): return str(item_type).replace(" | ", "' or '") return item_type.__name__ ``` -------------------------------- ### Instantiate CameraFollowCursorCV for Animated Code Videos (Python) Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/camerafollowcursorcv Initializes the CameraFollowCursorCV class to create animated videos of code input. It handles cursor movement, line breaks, indentation, and camera motion, providing a professional programming demonstration. Dependencies include Manim and Pygments for syntax highlighting. It accepts either a code string or a file path for the code content. ```python from CodeVideoRenderer import CameraFollowCursorCV # Example using code_string renderer = CameraFollowCursorCV( video_name="my_animation", code_string="print('Hello, World!')", language="python", line_spacing=0.8, interval_range=(0.1, 0.2), camera_scale=0.5 ) # Example using code_file # renderer = CameraFollowCursorCV( # video_name="my_animation_from_file", # code_file="path/to/your/code.py", # language="python" # ) ``` -------------------------------- ### Create Placeholder Code Block for Alignment Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Generates a placeholder code block used for aligning other code elements. It utilizes the Manim library and considers line spacing and font configurations. ```python # 占位代码块(用于对齐) occupy = Code( code_string=total_line_numbers*(max_char_num_per_line*OCCUPY_CHARACTER + '\n'), language=self.language, paragraph_config={ 'font': DEFAULT_CODE_FONT, 'line_spacing': self.line_spacing } ).submobjects[2] ``` -------------------------------- ### Initialize Code Video Renderer Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Initializes the Code Video Renderer with various parameters for video generation. It validates input parameters such as video name, code source (string or file), language, renderer type, line spacing, interval range, and camera scale. It enforces constraints like providing only one code source and ensuring code content is valid and non-empty. ```python from manim import Scene, MovingCameraScene, Code, RoundedRectangle, WHITE, GREY from typing import Literal from pathlib import Path # Assuming these are defined elsewhere in the project # from .utils import type_checker, strip_empty_lines, DEFAULT_LINE_SPACING, DEFAULT_TYPE_INTERVAL, DEFAULT_TAB_WIDTH, AVAILABLE_CHARACTERS, EMPTY_CHARACTER, DEFAULT_CURSOR_HEIGHT, DEFAULT_CURSOR_WIDTH, DEFAULT_CODE_FORMATTER_STYLE, DEFAULT_CODE_FONT # from .config import config # from .languages import PygmentsLanguage # Placeholder definitions for demonstration purposes class PygmentsLanguage: pass class config: frame_rate = 30 disable_caching = False renderer = 'cairo' DEFAULT_LINE_SPACING = 1 DEFAULT_TYPE_INTERVAL = 0.1 DEFAULT_TAB_WIDTH = 4 AVAILABLE_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 \t\n()[]{{}}<>+-*/=!;:,.'\""" EMPTY_CHARACTER = '' DEFAULT_CURSOR_HEIGHT = 0.5 DEFAULT_CURSOR_WIDTH = 0.02 DEFAULT_CODE_FORMATTER_STYLE = 'monokai' DEFAULT_CODE_FONT = 'Monaco' def type_checker(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper def strip_empty_lines(code_str): return "\n".join(line for line in code_str.split('\n') if line.strip()) class MovingCameraScene: def construct(self): pass class CameraFollowCursorCVScene(MovingCameraScene): def __init__(self, video_name: str = "CameraFollowCursorCV", code_string: str = None, code_file: str = None, language: PygmentsLanguage = None, renderer: Literal['cairo', 'opengl'] = 'cairo', line_spacing: float | int = DEFAULT_LINE_SPACING, interval_range: tuple[float | int, float | int] = (DEFAULT_TYPE_INTERVAL, DEFAULT_TYPE_INTERVAL), camera_scale: float | int = 0.5): # video_name if not video_name: raise ValueError("video_name must be provided") # code_string and code_file if code_string and code_file: raise ValueError("Only one of code_string and code_file can be provided") elif code_string is not None: code_str = code_string.expandtabs(tabsize=DEFAULT_TAB_WIDTH) if not all(char in AVAILABLE_CHARACTERS for char in code_str): raise ValueError("'code_string' contains invalid characters") elif code_file is not None: try: # Simulating file reading for demonstration # In a real scenario, this would read from the actual file path if code_file == "example.py": code_str = "print('Hello, World!')\n".expandtabs(tabsize=DEFAULT_TAB_WIDTH) else: raise FileNotFoundError if not all(char in AVAILABLE_CHARACTERS for char in code_str): raise ValueError("'code_file' contains invalid characters") except FileNotFoundError: raise ValueError(f"'{code_file}' not found") except UnicodeDecodeError: raise ValueError("'code_file' contains non-ASCII characters, please remove them") from None else: raise ValueError("Either code_string or code_file must be provided") if code_str.translate(str.maketrans('', '', EMPTY_CHARACTER)) == '': raise ValueError("Code is empty") # line_spacing if line_spacing <= 0: raise ValueError("line_spacing must be greater than 0") # interval_range shortest_possible_duration = round(1/config.frame_rate, 7) if not all(interval >= shortest_possible_duration for interval in interval_range): raise ValueError(f"interval_range must be greater than or equal to {shortest_possible_duration}") del shortest_possible_duration if interval_range[0] > interval_range[1]: raise ValueError("The first term of interval_range must be less than or equal to the second term") # 变量 self.video_name = video_name self.code_string = code_string self.code_file = code_file self.language = language self.line_spacing = line_spacing self.interval_range = interval_range self.camera_scale = camera_scale # 其他 self.code_str = strip_empty_lines(code_str) self.code_str_lines = self.code_str.split("\n") self.origin_config = { 'disable_caching': config.disable_caching, 'renderer': config.renderer } config.disable_caching = True config.renderer = renderer self.scene = self._create_scene() def _create_scene(self): """构建代码动画场景。""" class CameraFollowCursorCVScene(MovingCameraScene): def construct(scene): """Build the code animation scene.""" # 初始化光标 cursor = RoundedRectangle( height=DEFAULT_CURSOR_HEIGHT, width=DEFAULT_CURSOR_WIDTH, corner_radius=DEFAULT_CURSOR_WIDTH / 2, fill_opacity=1, fill_color=WHITE, color=WHITE ) # 创建代码块 code_block = Code( code_string=self.code_str, language=self.language, formatter_style=DEFAULT_CODE_FORMATTER_STYLE, paragraph_config={ 'font': DEFAULT_CODE_FONT, 'line_spacing': self.line_spacing } ) line_number_mobject = code_block.submobjects[1].set_color(GREY) code_mobject = code_block.submobjects[2] total_line_numbers = len(line_number_mobject) total_char_numbers = len(''.join(line.strip() for line in self.code_str.split('\n'))) return CameraFollowCursorCVScene() # Example usage: # renderer_with_string = CameraFollowCursorCVScene(code_string="print('Hello')", language=PygmentsLanguage()) # renderer_with_file = CameraFollowCursorCVScene(code_file="example.py", language=PygmentsLanguage()) ``` -------------------------------- ### CodeVideoRenderer.CameraFollowCursorCVR Functions Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/functions This section details the utility functions within the CameraFollowCursorCVR class for managing output, processing strings, checking types, applying effects, and retrieving language information. ```APIDOC ## CodeVideoRenderer.CameraFollowCursorCVR.no_manim_output() ### Description Temporarily disables Manim's standard output and progress bar during code execution to avoid interfering with other outputs. ### Method N/A (This is a function within a class, not a direct API endpoint) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response N/A (This function modifies behavior, does not return data) #### Response Example N/A ``` ```APIDOC ## CodeVideoRenderer.CameraFollowCursorCVR.strip_empty_lines(_text : str_) ### Description Removes leading and trailing empty lines from a given string. ### Method N/A (This is a function within a class, not a direct API endpoint) ### Endpoint N/A ### Parameters * **_text** (str) - Required - The input string to process. ### Request Example N/A ### Response #### Success Response (str) - **_text** (str) - The string with leading and trailing empty lines removed. #### Response Example ```json { "example": "Processed string" } ``` ``` ```APIDOC ## CodeVideoRenderer.CameraFollowCursorCVR.typeName(_item_type_) ### Description Retrieves the name of a type, handling union types and generic tuples. ### Method N/A (This is a function within a class, not a direct API endpoint) ### Endpoint N/A ### Parameters * **_item_type_** (type) - Required - The type to get the name of. ### Request Example N/A ### Response #### Success Response (str) - **type_name** (str) - The name of the type. #### Response Example ```json { "example": "str" } ``` ``` ```APIDOC ## CodeVideoRenderer.CameraFollowCursorCVR.type_checker(_func_) ### Description A parameter checking decorator that verifies if the types of function arguments and return values match their annotations. ### Method N/A (This is a decorator, not a direct API endpoint) ### Endpoint N/A ### Parameters * **_func_** (function) - Required - The function to decorate. ### Request Example N/A ### Response #### Success Response N/A (This is a decorator that modifies function behavior) #### Response Example N/A ``` ```APIDOC ## CodeVideoRenderer.CameraFollowCursorCVR.add_glow_effect(_input_path : PathLike_, _output_path : PathLike_, _output : bool_) ### Description Adds a glow effect to a video. ### Method N/A (This is a function within a class, not a direct API endpoint) ### Endpoint N/A ### Parameters * **_input_path** (PathLike) - Required - The path to the input video file. * **_output_path** (PathLike) - Required - The path where the output video file will be saved. * **_output** (bool) - Required - Whether to show output during processing. ### Request Example N/A ### Response #### Success Response N/A (This function processes a video file and saves it to a path) #### Response Example N/A ``` ```APIDOC ## CodeVideoRenderer.CameraFollowCursorCVR.default_progress_bar(_output : bool_) ### Description Creates a Rich progress bar. ### Method N/A (This is a function within a class, not a direct API endpoint) ### Endpoint N/A ### Parameters * **_output** (bool) - Required - Whether to display the progress bar. ### Request Example N/A ### Response #### Success Response (rich.progress.Progress) - **progress_bar** (rich.progress.Progress) - An instance of a Rich progress bar. #### Response Example ```json { "example": "" } ``` ``` ```APIDOC ## CodeVideoRenderer.CameraFollowCursorCVR.get_all_languages() ### Description Retrieves all available Pygments languages. ### Method N/A (This is a function within a class, not a direct API endpoint) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response (list[str]) - **languages** (list[str]) - A list of available Pygments language names. #### Response Example ```json { "example": ["python", "javascript", "html"] } ``` ``` -------------------------------- ### Create Code Line Rectangle Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Generates a rectangular background for each line of code. It uses the placeholder block and line number mobject to define its boundaries and appearance. ```python # 创建代码行矩形框 code_line_rectangle = SurroundingRectangle( VGroup(occupy[-1], line_number_mobject[-1]), color="#333333", fill_opacity=1, stroke_width=0 ).set_y(occupy[0].get_y()) ``` -------------------------------- ### Entry Animation for Camera and Scene Elements Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Handles the initial animation sequence, moving the camera frame to the target center and adding initial scene elements like the code line rectangle, line numbers, and cursor. ```python # 入场动画 target_center = cursor.get_center() start_center = target_center + UP * 3 scene.camera.frame.scale(self.camera_scale).move_to(start_center) scene.add(code_line_rectangle, line_number_mobject[0].set_color(WHITE), cursor) scene.play( scene.camera.frame.animate.move_to(target_center), run_time=1, rate_func=rate_functions.ease_out_cubic ) ``` -------------------------------- ### Code Video Renderer Initialization Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Initializes the Code Video Renderer with specified parameters to create video animations from code. ```APIDOC ## POST /websites/zhuchongjing_github_io_codevideorenderer ### Description Initializes the Code Video Renderer to create video animations from code. You can provide code either as a string or from a file path. Various parameters control the appearance and behavior of the animation, including language for syntax highlighting, renderer type, line spacing, character interval, and camera scale. ### Method POST ### Endpoint /websites/zhuchongjing_github_io_codevideorenderer ### Parameters #### Query Parameters - **video_name** (str) - Optional - The filename for the output video (without extension). Defaults to "CameraFollowCursorCV". - **code_string** (str) - Optional - A string containing the code to be rendered. Cannot be provided if `code_file` is used. - **code_file** (str) - Optional - The path to a file containing the code to be rendered. Cannot be provided if `code_string` is used. - **language** (PygmentsLanguage) - Optional - The language for syntax highlighting (e.g., "python", "c++"). - **renderer** (Literal['cairo', 'opengl']) - Optional - The video renderer to use. Defaults to 'cairo'. - **line_spacing** (float | int) - Optional - The spacing between lines of code. Defaults to DEFAULT_LINE_SPACING. - **interval_range** (tuple[float | int, float | int]) - Optional - The range for character input interval (min, max). Defaults to (DEFAULT_TYPE_INTERVAL, DEFAULT_TYPE_INTERVAL). - **camera_scale** (float | int) - Optional - The scaling factor for the camera. Defaults to 0.5. ### Request Body This endpoint does not typically use a request body for initialization; parameters are passed as query parameters. ### Response #### Success Response (200) Returns a success message or status upon successful initialization. #### Response Example ```json { "status": "success", "message": "Renderer initialized successfully." } ``` ### Warnings - `code_string` and `code_file` are mutually exclusive; only one can be provided. - Code content cannot be empty and must only contain available characters (`AVAILABLE_CHARACTERS`). - All time-related parameters must be greater than or equal to 1/current_frame_rate. - `video_name` must be provided if not using the default. - `code_string` or `code_file` must be provided. - `line_spacing` must be greater than 0. - The first element of `interval_range` must be less than or equal to the second element. - `code_file` must not contain non-ASCII characters if using GBK encoding. ``` -------------------------------- ### Initialize Cursor Position Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Sets the initial position of the cursor to align with the beginning of the first code line. ```python # 初始化光标位置 cursor.align_to(occupy[0][0], LEFT).set_y(occupy[0][0].get_y()) ``` -------------------------------- ### Create Scene for Code Animation (Python) Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/camerafollowcursorcv The `create_scene` method within the CameraFollowCursorCV class is responsible for building the animation scene. This method is called internally during the initialization or rendering process to set up the visual elements for the code animation. ```python from CodeVideoRenderer import CameraFollowCursorCV renderer = CameraFollowCursorCV(code_string="print('Example')") renderer._create_scene() ``` -------------------------------- ### Create Code Animation Scene Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Constructs the scene for the code animation. This involves initializing a cursor and creating a 'Code' mobject from the provided code string and language. It also extracts line numbers and code content for further manipulation within the animation. ```python class CameraFollowCursorCVScene(MovingCameraScene): def construct(scene): """Build the code animation scene.""" # 初始化光标 cursor = RoundedRectangle( height=DEFAULT_CURSOR_HEIGHT, width=DEFAULT_CURSOR_WIDTH, corner_radius=DEFAULT_CURSOR_WIDTH / 2, fill_opacity=1, fill_color=WHITE, color=WHITE ) # 创建代码块 code_block = Code( code_string=self.code_str, language=self.language, formatter_style=DEFAULT_CODE_FORMATTER_STYLE, paragraph_config={ 'font': DEFAULT_CODE_FONT, 'line_spacing': self.line_spacing } ) line_number_mobject = code_block.submobjects[1].set_color(GREY) code_mobject = code_block.submobjects[2] total_line_numbers = len(line_number_mobject) total_char_numbers = len(''.join(line.strip() for line in self.code_str.split('\n'))) ``` -------------------------------- ### Process Code Lines with Progress Bar Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Iterates through each line of code, updates progress bars, highlights the current line number, and moves the cursor. It handles empty lines and triggers animations for line breaks and camera scaling. ```python with copy(default_progress_bar(self.output)) as progress: total_progress = progress.add_task(description="[yellow]Total[/yellow]", total=total_char_numbers) # 遍历代码行 for line in range(total_line_numbers): line_number_mobject.set_color(GREY) line_number_mobject[line].set_color(WHITE) char_num = len(self.code_str_lines[line].strip()) current_line_progress = progress.add_task(description=f"[green]Line {line+1}[/green]", total=char_num) code_line_rectangle.set_y(occupy[line].get_y()) scene.add(line_number_mobject[line]) def move_cursor_to_line_head(): """Move cursor to the first character in the line.""" cursor.align_to(occupy[line], LEFT).set_y(occupy[line].get_y()) if line != 0: linebreakAnimation() JUDGE_cameraScaleAnimation() playAnimation(run_time=DEFAULT_LINE_BREAK_RUN_TIME) try: if self.code_str_lines[line][0] not in string.whitespace: move_cursor_to_line_head() except IndexError: move_cursor_to_line_head() del move_cursor_to_line_head # 如果当前行为空行,跳过 if self.code_str_lines[line] == '' or char_num == 0: progress.remove_task(current_line_progress) continue ``` -------------------------------- ### Animate Code Typing and Camera Movement with Manim Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR This Python code animates the typing of code line by line using Manim. It handles character-by-character rendering, cursor movement, and camera oscillations based on typing progress. Dependencies include Manim library and NumPy. ```python first_non_space_index = len(self.code_str_lines[line]) - len(self.code_str_lines[line].lstrip()) total_typing_chars = char_num # 当前行实际要打的字数 # 遍历当前行的每个字符 submobjects_char_index = 0 for column in range(first_non_space_index, char_num + first_non_space_index): occupy_char = occupy[line][column] # 处理manim==0.19.1更新出现的空格消失问题 if not self.code_str_lines[line][column].isspace(): scene.add(code_mobject[line][submobjects_char_index]) submobjects_char_index += 1 cursor.next_to(occupy_char, RIGHT, buff=DEFAULT_CURSOR_TO_CHAR_BUFFER).set_y(code_line_rectangle.get_y()) # 相机持续摆动逻辑 line_break = False if column == first_non_space_index and first_non_space_index != 0: # 如果是缩进后的第一个字符,先执行换行归位 linebreakAnimation() line_break = True else: # 计算当前行的进度 (0.0 -> 1.0) current_idx = column - first_non_space_index max_idx = total_typing_chars - 1 if max_idx > 0: alpha = current_idx / max_idx else: alpha = 1.0 # 包络线 sin(alpha * pi),确保头尾为0 envelope = np.sin(alpha * np.pi) # 振荡项: sin(alpha * omega) wave_count = total_typing_chars / 15 omega = wave_count * 2 * np.pi oscillation = np.sin(alpha * omega) # 振幅为相机框高度的 2.5% amplitude = scene.camera.frame.height * 0.025 offset_y = amplitude * envelope * oscillation target_pos = cursor.get_center() + UP * offset_y scene.Animation_list.append({"move_to": target_pos}) # 缩放检测 & 播放 JUDGE_cameraScaleAnimation() playAnimation( run_time=DEFAULT_LINE_BREAK_RUN_TIME if line_break else random.uniform(*self.interval_range), rate_func=rate_functions.smooth if line_break else rate_functions.linear ) # 输出进度 progress.advance(total_progress, advance=1) progress.advance(current_line_progress, advance=1) progress.remove_task(current_line_progress) progress.remove_task(total_progress) scene.wait() ``` -------------------------------- ### Create Rich Progress Bar Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Creates a customizable progress bar using the Rich library. This function allows for detailed progress tracking with descriptions, bars, completion percentages, time remaining, and transfer speeds. It can be configured to output to a console or be disabled. ```python def default_progress_bar(output: bool): """ 创建一个 Rich 进度条。 """ return Progress( TextColumn("[progress.description]{task.description}"), BarColumn(), TextColumn("[yellow]{task.completed}/{task.total}"), TextColumn("[progress.percentage]{task.percentage:>3.0f}%"), TimeRemainingColumn(), TransferSpeedColumn(), console=DEFAULT_OUTPUT_CONSOLE if output else None ) ``` -------------------------------- ### CameraFollowCursorCV for Code Animation Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Creates animated videos simulating the code typing process. This class animates code line by line and character by character, with smooth camera movements following the cursor, resulting in a professional-looking programming demonstration. ```python class CameraFollowCursorCV: r""" 创建模拟代码输入过程的动画视频。它逐行、逐个字符地为代码制作动画,同时让镜头平滑移动以跟随光标,从而打造出具有专业外观的编程演示。 ``` -------------------------------- ### 生成简单视频 (Python) Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_sources/quickstart.rst 使用 CameraFollowCursorCV 类生成一个简单的 MP4 视频。需要安装 CodeVideoRenderer 库。输入为视频名称、要渲染的代码字符串和代码语言。输出为渲染后的 MP4 文件。 ```python from CodeVideoRenderer import CameraFollowCursorCV video = CameraFollowCursorCV( video_name="Demo", # 文件名 code_string="print('Hello World!')", # 代码 language="python" # 语言 ) video.render() ``` -------------------------------- ### PygmentsLanguage Class Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/classes Represents a Pygments language. ```APIDOC ## Class: PygmentsLanguage ### Description Represents a Pygments language. ### Parameters This class does not appear to have any constructor parameters based on the provided documentation. ``` -------------------------------- ### Render Animated Code Video (Python) Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/camerafollowcursorcv The `render` method initiates the Manim rendering process for the animated code video. It can optionally display a progress bar with speed and remaining time information in the console. The output parameter controls whether this progress information is shown. ```python from CodeVideoRenderer import CameraFollowCursorCV renderer = CameraFollowCursorCV(code_string="print('Rendering...')", video_name="output_video") renderer.render(output=True) ``` -------------------------------- ### Scene Construction Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Internal method to construct the animation scene using the provided code and configuration. ```APIDOC ## Internal Method: _create_scene ### Description This internal method constructs the code animation scene. It initializes a cursor (RoundedRectangle) and a Code Mobject, setting up the visual representation of the code with syntax highlighting and line numbers. ### Method Internal (called during initialization) ### Endpoint N/A ### Parameters This method uses parameters set during the initialization of the renderer class, such as `self.code_str`, `self.language`, `self.line_spacing`, etc. ### Request Example N/A (Internal method) ### Response #### Success Response Returns a scene object (e.g., `MovingCameraScene`) configured for code animation. #### Response Example ```python # Example of the returned scene object structure (conceptual) class CameraFollowCursorCVScene(MovingCameraScene): def construct(scene): # ... scene construction logic ... pass ``` ``` -------------------------------- ### Adjust Code Alignment for Manim Bug Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Applies a downward shift to the code and its placeholder if the first line of code contains only specific characters, addressing a known bug in Manim's alignment. ```python # 调整代码对齐(manim内置bug) if all(check in "acegmnopqrsuvwxyz+,-.:;<=>_~" + EMPTY_CHARACTER for check in self.code_str_lines[0]): code_mobject.shift(DOWN*CODE_OFFSET) occupy.shift(DOWN*CODE_OFFSET) ``` -------------------------------- ### Manage Rich Progress Bar Tasks Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Handles the creation and closing of individual Rich progress bar tasks within the RichProgressBarLogger. It ensures that tasks are properly added and removed, and updates their status based on the rendering progress. ```python def new_tqdm_bar(self, bar): """ 创建一个 Rich 进度条任务。 """ if not self.output or self.progress_bar is None: return # 关闭已有进度条 if bar in self.rich_bars: self.close_tqdm_bar(bar) # 获取父类维护的进度条信息 infos = self.bars[bar] # 创建 Rich 进度条任务 task_id = self.progress_bar.add_task(description=f"[yellow]{self.title}[/yellow]", total=infos["total"]) self.rich_bars[bar] = task_id def close_tqdm_bar(self, bar): """ 关闭 Rich 进度条任务。 """ if not self.output or self.progress_bar is None: return if bar in self.rich_bars: task_id = self.rich_bars[bar] # 若不需要保留,移除任务 if not self.leave_bars: self.progress_bar.remove_task(task_id) del self.rich_bars[bar] ``` -------------------------------- ### Placeholder for Pygments Language Class Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR A placeholder class definition for PygmentsLanguage. This class is likely intended to be extended or used in conjunction with Pygments for language-specific operations within the project. ```python class PygmentsLanguage: pass ``` -------------------------------- ### Define Fixed Animations for Camera Movement Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Sets up functions to manage camera animations, including moving the cursor to a new line and adjusting camera scale based on content width. ```python # 定义固定动画 scene.Animation_list = [] def linebreakAnimation(): scene.Animation_list.append({"move_to": cursor.get_center()}) def JUDGE_cameraScaleAnimation(): distance = (scene.camera.frame.get_x() - line_number_mobject.get_x()) / 14.22 if distance > self.camera_scale: scene.Animation_list.append({"scale": distance/self.camera_scale}) self.camera_scale = distance def playAnimation(**kwargs): if scene.Animation_list: cameraAnimation = scene.camera.frame.animate for anim in scene.Animation_list: if "move_to" in anim: cameraAnimation.move_to(anim["move_to"]) elif "scale" in anim: cameraAnimation.scale(anim["scale"]) scene.play(cameraAnimation, **kwargs) scene.Animation_list.clear() del cameraAnimation ``` -------------------------------- ### Adapt Camera Frame for OpenGL Renderer Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Ensures the camera frame is correctly set when using the OpenGL renderer in Manim. ```python # 适配opengl if config.renderer == RendererType.OPENGL: scene.camera.frame = scene.camera ``` -------------------------------- ### Strip Empty Lines Utility Function Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Removes leading and trailing empty lines from a given string. This function splits the input text into lines, identifies the first and last non-empty lines, and rejoins them. ```python def strip_empty_lines(text: str): """ 移除字符串首尾的空行。 """ lines = text.split("\n") start = 0 while start < len(lines) and lines[start].strip() == '': start += 1 end = len(lines) while end > start and lines[end - 1].strip() == '': end -= 1 return '\n'.join(lines[start:end]) ``` -------------------------------- ### Add Glow Effect to Video (Python) Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Applies a glow effect to a video file. It takes the input video path, constructs an output path, and applies the effect using moviepy. The function measures and logs the time taken for the effect to be applied. ```python input_path = str(scene.renderer.file_writer.movie_file_path) output_path = '\'.join(input_path.split('\')[:-1]) + rf'\{self.video_name}.mp4' total_effect_time = timeit(lambda: add_glow_effect(input_path=input_path, output_path=output_path, output=self.output), number=1) if self.output: DEFAULT_OUTPUT_CONSOLE.log(f"Successfully added glow effect in {total_effect_time:,.2f} seconds. [dim](by moviepy)[/]") DEFAULT_OUTPUT_CONSOLE.log(f"File ready at '{output_path}'.") del input_path, output_path, total_effect_time ``` -------------------------------- ### Disable Manim Output Context Manager Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Temporarily disables Manim's standard output and progress bar during code execution. This is useful for preventing rendering output from interfering with other console messages. It restores the original stdout, stderr, and progress bar settings upon exiting the context. ```python from manim import * from pathlib import Path from rich.progress import Progress, BarColumn, TextColumn, TimeRemainingColumn, TransferSpeedColumn from copy import copy from contextlib import contextmanager from io import StringIO from functools import wraps from typing import get_args, get_origin, Literal from os import PathLike from types import UnionType from moviepy import VideoFileClip from PIL import Image, ImageFilter, ImageEnhance from proglog import ProgressBarLogger from collections import OrderedDict from timeit import timeit from pygments.lexers import get_all_lexers import numpy as np import random, time, string, sys, inspect, time from .config import * @contextmanager def no_manim_output(): """ 用于在执行代码时,临时禁用 Manim 的标准输出和进度条,避免在渲染过程中干扰其他输出。 """ sys.stdout = StringIO() stderr_buffer = StringIO() sys.stderr = stderr_buffer config.progress_bar = "none" try: yield finally: sys.stdout = ORIGINAL_STDOUT sys.stderr = ORIGINAL_STDERR config.progress_bar = ORIGINAL_PROGRESS_BAR stderr_content = stderr_buffer.getvalue() if stderr_content: print(stderr_content, file=ORIGINAL_STDERR) ``` -------------------------------- ### RichProgressBarLogger Class Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/classes A progress bar logger that uses the Rich library to display progress bars. It inherits from ProgressBarLogger. ```APIDOC ## Class: RichProgressBarLogger ### Description A progress bar logger that uses the Rich library to display progress bars. It inherits from ProgressBarLogger. ### Parameters - **_output** (bool) - Required - Whether to output the progress bar. - **_title** (str) - Required - The title of the progress bar. - **_init_state** (any) - Optional - The initial state of the progress bar. - **_bars** (any) - Optional - The bars to display. - **_leave_bars** (bool) - Optional - Whether to leave the bars after completion. - **_ignored_bars** (any) - Optional - Bars to ignore. - **_logged_bars** (str) - Optional - Which bars to log ('all'). - **_print_messages** (bool) - Optional - Whether to print messages. - **_min_time_interval** (float) - Optional - The minimum time interval between updates. - **_ignore_bars_under** (int) - Optional - Ignore bars under this value. ### Methods #### `new_tqdm_bar(_bar_)` ##### Description Creates a Rich progress bar task. ##### Parameters - **_bar** (any) - Required - The bar to create. #### `close_tqdm_bar(_bar_)` ##### Description Closes a Rich progress bar task. ##### Parameters - **_bar** (any) - Required - The bar to close. #### `bars_callback(_bar_, _attr_, _value_, _old_value_)` ##### Description Updates a Rich progress bar task based on attribute changes. ##### Parameters - **_bar** (any) - Required - The bar to update. - **_attr** (str) - Required - The attribute to update. - **_value** (any) - Required - The new value. - **_old_value** (any) - Required - The old value. #### `stop()` ##### Description Closes the Rich progress bar. ``` -------------------------------- ### Type Checker Decorator for Function Arguments and Return Values Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR A decorator that validates function arguments and return values against their type annotations. It supports basic types, Union types, Literal values, generic tuples, and Pygments languages. Type mismatches raise TypeError or ValueError. ```python def type_checker(func): """ 一个参数检查装饰器,用于检查函数参数和返回值的类型是否符合注解。 """ @wraps(func) def wrapper(*args, **kwargs): sig = inspect.signature(func) bound_args = sig.bind(*args, **kwargs) for param_name, param_value in bound_args.arguments.items(): param_type = sig.parameters[param_name].annotation if param_type is inspect.Parameter.empty: continue # 无注解则跳过 # 处理带参数的泛型 tuple(如 tuple[float, float]) if get_origin(param_type) is tuple: # 校验是否为 tuple 实例 if not isinstance(param_value, tuple): raise TypeError( f"Parameter '{param_name}': Expected 'tuple', got '{type(param_value).__name__}'" ) # 校验长度和元素类型 item_types = get_args(param_type) if len(param_value) != len(item_types): raise ValueError( f"Parameter '{param_name}' length mismatch: Expected {len(item_types)}, got {len(param_value)}" ) for idx, (item, item_type) in enumerate(zip(param_value, item_types)): if not isinstance(item, item_type): raise TypeError( f"Parameter '{param_name}' item (index: {idx}): Expected '{typeName(item_type)}', got '{type(item).__name__}'" ) elif get_origin(param_type) is Literal: # 校验是否为 Literal 中的值 if param_value not in get_args(param_type): raise ValueError( f"Parameter '{param_name}': Expected value in {get_args(param_type)}, got '{param_value}'" ) elif param_type is PygmentsLanguage: if param_value not in get_all_languages(): raise ValueError( f"Parameter '{param_name}': Expected a valid Pygments language, got '{param_value}'" ) # 普通类型 else: if not isinstance(param_value, param_type): raise TypeError(f"Parameter '{param_name}': Expected '{typeName(param_type)}', got '{type(param_value).__name__}'") return func(*args, **kwargs) return wrapper ``` -------------------------------- ### PygmentsLanguage Class - Python Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/classes Represents language support for Pygments, likely used for syntax highlighting within the CodeVideoRenderer. ```python class PygmentsLanguage: """Represents language support for Pygments.""" pass ``` -------------------------------- ### Add Glow Effect to Video Frames Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Applies a glow effect to video frames using PIL and MoviePy. The function enhances brightness, blurs the image to create a glow, and further enhances the glow's brightness and saturation. It processes frames from an input video and saves the result to an output path if specified. ```python def add_glow_effect(input_path: PathLike, output_path: PathLike, output: bool): """ 为视频添加发光效果。 """ # 内部帧处理函数 def _frame_glow(t: np.ndarray): # 获取MoviePy的numpy帧并转为PIL图像 frame = t.astype(np.uint8) pil_img = Image.fromarray(frame).convert("RGBA") # 提升基础亮度 brightness_enhancer = ImageEnhance.Brightness(pil_img) pil_img = brightness_enhancer.enhance(1.2) # 创建模糊光晕层 glow = pil_img.filter(ImageFilter.GaussianBlur(radius=10)) # 提升光晕的亮度和饱和度 glow_bright_enhancer = ImageEnhance.Brightness(glow) glow = glow_bright_enhancer.enhance(1.5) glow_color_enhancer = ImageEnhance.Color(glow) ``` -------------------------------- ### Apply Glow Effect to Video Frame Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Applies a glow color enhancement to a video frame and blends it with the original image. This function takes a frame, enhances its glow, blends it, converts it to RGB, and clips the values to ensure they are within the valid 0-255 range. It's designed to be used with video processing libraries like moviepy. ```python def _frame_glow(frame): pil_img = Image.fromarray(frame) glow_color_enhancer = ImageEnhance.Color(pil_img) glow = glow_color_enhancer.enhance(1.2) # 混合原图像与光晕层 soft_glow_img = Image.blend(glow, pil_img, 0.4) glow_frame = np.array(soft_glow_img.convert("RGB")).astype(np.uint8) return np.clip(glow_frame, 0, 255) glow_video = VideoFileClip(input_path).image_transform(_frame_glow) glow_video.write_videofile(output_path, codec='libx264', audio=True, logger=RichProgressBarLogger(output=output, title="Glow Effect", leave_bars=False)) ``` -------------------------------- ### Calculate Maximum Character Number Per Line Source: https://zhuchongjing.github.io/CodeVideoRenderer-docs/_modules/CodeVideoRenderer/CameraFollowCursorCVR Calculates the maximum number of characters present in any single line of the code string. This is used for alignment purposes. ```python max_char_num_per_line = max([len(line.rstrip()) for line in self.code_str_lines]) ```