### Setup for Face Detection and Clustering Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/USAGE_EXAMPLES.md This snippet installs the pyannote library and prepares the data directory. It also mounts Google Drive for persistent storage. ```python from google.colab import drive import os # Mount Drive drive.mount('/content/drive') # Install pyannote !pip install -q pyannote.video # Prepare data directory !mkdir -p pyannote-data ``` -------------------------------- ### Setup Environment for Video Colorization Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/USAGE_EXAMPLES.md This snippet sets up the Google Colab environment by mounting Google Drive, verifying GPU compatibility (Tesla T4 or P100), and installing necessary libraries like fastai and DeOldify. ```python from google.colab import drive import pynvml import torch # Mount Drive drive.mount('/content/drive') # Verify GPU requirements pynvml.nvmlInit() handle = pynvml.nvmlDeviceGetHandleByIndex(0) device_name = pynvml.nvmlDeviceGetName(handle) if device_name != b'Tesla T4' and device_name != b'Tesla P100-PCIE-16GB': raise Exception(f"Unsupported GPU: {device_name}. Requires T4 or P100.") print(f"GPU: {device_name}") # Enable GPU optimization torch.backends.cudnn.benchmark = True # Setup DeOldify !git clone https://github.com/jantic/DeOldify.git %cd DeOldify/ !pip install -q fastai ``` -------------------------------- ### Install pyannote-video and Dependencies Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb Installs specific versions of imageio, imgaug, mido, python-rtmidi, and then installs the pyannote-video package. This ensures compatibility and installs the core library. ```bash !pip install imageio==2.4.1 imgaug==0.2.5 mido==1.2.6 python-rtmidi==1.2 !pip install pyannote-video ``` -------------------------------- ### Install youtube-dl Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb Installs the youtube-dl package, which is required for downloading videos from YouTube. This is a prerequisite for processing video files from YouTube. ```bash !pip install youtube-dl ``` -------------------------------- ### Colab Environment Setup for Image Colorization Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/USAGE_EXAMPLES.md Mounts Google Drive, checks for GPU availability, and clones and sets up the DeOldify library with necessary dependencies. ```python from google.colab import drive import torch # Mount Drive drive.mount('/content/drive') # Check GPU if not torch.cuda.is_available(): print('GPU not available.') else: device_name = torch.cuda.get_device_name(0) print(f'GPU available: {device_name}') # Enable GPU optimization torch.backends.cudnn.benchmark = True # Clone and setup DeOldify !git clone https://github.com/jantic/DeOldify.git %cd DeOldify/ # Install dependencies !pip install -q fastai pillow ``` -------------------------------- ### Install OpenCV and FFmpeg Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Installs the OpenCV development library, Python bindings for OpenCV, and FFmpeg. These are necessary dependencies for Darknet, especially when using video processing. ```bash !apt install libopencv-dev python-opencv ffmpeg ``` -------------------------------- ### Setup and Data Preparation for YOLOv4 Training Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/USAGE_EXAMPLES.md Mounts Google Drive, clones the Darknet repository, builds it with GPU support, and prepares the dataset directory structure. It then copies the dataset from Google Drive. ```python from google.colab import drive import os import fnmatch import numpy as np # Mount Google Drive for dataset/weights persistence drive.mount('/content/drive') # Clone Darknet repository !git clone https://github.com/AlexeyAB/darknet/ %cd darknet/ # Build Darknet with GPU support !make GPU=1 CUDNN=1 # Create dataset directories !mkdir -p build/darknet/x64/data/obj !mkdir -p build/darknet/x64/backup # Copy dataset from Drive !cp -r "/content/drive/My Drive/datasets/firearms/*" build/darknet/x64/data/obj/ ``` -------------------------------- ### Start YOLOv4 Training without Display Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb Starts the YOLOv4 training process while disabling the loss-window display. This is useful for training on remote servers or environments without a graphical interface. ```bash ./darknet detector train data/obj.data yolo-obj.cfg yolov4.conv.137 -dont_show ``` -------------------------------- ### Train YOLOv3 Model Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Guns_Detection.ipynb Initiates the training process for a YOLOv3 model using specified data, configuration, and pre-trained weights. Use this command to start training from scratch. ```bash ./darknet detector train build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/darknet53.conv.74 -dont_show ``` -------------------------------- ### Install DeOldify Dependencies Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/ImageColorizerColab.ipynb Installs all the necessary Python packages listed in the 'requirements.txt' file for DeOldify to function. ```bash !pip install -r requirements.txt ``` -------------------------------- ### Start YOLOv4 Training Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb Initiates the YOLOv4 training process using the Darknet command-line interface. This command specifies the data configuration file, the network configuration file, and the pre-trained weights to use. ```bash ./darknet detector train data/obj.data yolo-obj.cfg yolov4.conv.137 ``` -------------------------------- ### Start YOLOv4 Training with mAP and Loss Chart Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb Initiates YOLOv4 training and enables the display of Mean Average Precision (mAP) and Loss charts during training on a remote server. The charts can be accessed via a web browser. ```bash ./darknet detector train data/obj.data yolo-obj.cfg yolov4.conv.137 -dont_show -mjpeg_port 8090 -map ``` -------------------------------- ### Complete PyTorch Training Loop Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/fastai_pytorch.md This snippet demonstrates a full training loop for a PyTorch model. It includes setup for device, model loading, loss function, optimizer, and the core training steps: forward pass, backward pass, and optimizer step. Ensure you have your DataLoader (train_loader) and model (MyColorizer) defined. ```python import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader # Setup device = torch.device("cuda" if torch.cuda.is_available() else "cpu") torch.backends.cudnn.benchmark = True # Load model model = MyColorizer().to(device) # Loss and optimizer criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # Training loop for epoch in range(num_epochs): for batch_idx, (images, targets) in enumerate(train_loader): images = images.to(device) targets = targets.to(device) # Forward pass outputs = model(images) loss = criterion(outputs, targets) # Backward pass optimizer.zero_grad() loss.backward() optimizer.step() if batch_idx % 10 == 0: print(f"Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}") torch.cuda.empty_cache() ``` -------------------------------- ### VideoWriter.isOpened() Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/opencv_utilities.md Checks if the VideoWriter object has been successfully initialized and is ready to accept frames. This is a good practice to verify before starting the writing process. ```APIDOC ## VideoWriter.isOpened() ### Description Checks if video writer is successfully initialized. ### Method (Implicitly called on a VideoWriter object) ### Parameters None ### Returns - bool - True if writer is ready, False if initialization failed ### Example: ```python out = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 30.0, (1920, 1080)) if out.isOpened(): print("Writer initialized successfully") ``` ``` -------------------------------- ### Get pyannote-face.py Help Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb Displays the help message for the pyannote-face.py script, showing available commands and options. This is useful for understanding the script's capabilities. ```bash !pyannote-face.py --help ``` -------------------------------- ### Complete Multi-Task Deep Learning Pipeline in Colab Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/USAGE_EXAMPLES.md This example demonstrates a complete pipeline integrating object detection, image colorization, and video analysis. It requires mounting Google Drive and utilizes libraries like OpenCV, PyTorch, Fastai, and Pyannote. ```python from google.colab import drive, files import cv2 import torch import os # Mount Drive drive.mount('/content/drive') # ============= STEP 1: Object Detection ============= print("Step 1: Object Detection") # Load YOLO model !./darknet detector test data.cfg yolo.cfg weights.weights input_video.mp4 # Load detection results detections = cv2.imread('predictions.jpg') # ============= STEP 2: Image Colorization ============= print("Step 2: Image Colorization") import fastai from deoldify.visualize import get_image_colorizer colorizer = get_image_colorizer(artistic=True) # Colorize detected objects colorized_path = colorizer.plot_transformed_image( 'predictions.jpg', render_factor=13, figsize=(8, 8) ) # ============= STEP 3: Video Analysis ============= print("Step 3: Face Detection") from pyannote.video.face.clustering import FaceClustering clustering = FaceClustering(threshold=0.6) face_tracks, embeddings = clustering.model.preprocess('embedding.txt') result = clustering(face_tracks, features=embeddings) # ============= STEP 4: Save Results ============= print("Step 4: Saving results") # Create output directory output_dir = '/content/drive/My Drive/analysis_results/' os.makedirs(output_dir, exist_ok=True) # Save all outputs files.download(colorized_path) with open(f'{output_dir}clustering.txt', 'w') as f: for _, track_id, label in result.itertracks(yield_label=True): f.write(f'{track_id} {label}\n') print("Analysis complete!") ``` -------------------------------- ### Train YOLOv3 (Google Colab) Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Command to start YOLOv3 training within a Google Colab environment. This command executes the Darknet training executable. ```bash !./darknet detector train build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/darknet53.conv.74 -dont_show ``` -------------------------------- ### Clone DeOldify Repository Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/ImageColorizerColab.ipynb Clones the DeOldify GitHub repository into the Colab environment. This is the first step to installing the library. ```bash !git clone https://github.com/jantic/DeOldify.git DeOldify ``` -------------------------------- ### Download Video from YouTube Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb Downloads a video from YouTube using youtube-dl, specifying quality constraints. Ensure youtube-dl is installed. ```python #download video from Youtube (!pip install youtube-dl) !youtube-dl -f 'bestvideo[height<=720]+bestaudio/best[height<=720]' -o '%(title)s.%(ext)s' --restrict-filenames https://www.youtube.com/watch?v=b6VRDcnziQU ``` -------------------------------- ### Process Large Videos in Chunks with Memory Management Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/USAGE_EXAMPLES.md This example illustrates a strategy for processing very long videos by breaking them into smaller chunks to manage memory effectively. It includes clearing GPU cache between chunks to prevent memory buildup. ```python import cv2 import torch from deoldify.visualize import get_video_colorizer colorizer = get_video_colorizer() # For very long videos, process in chunks cap = cv2.VideoCapture('long_video.mp4') fps = cap.get(cv2.CAP_PROP_FPS) frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) chunk_duration = 60 # 1 minute chunks chunk_frames = int(fps * chunk_duration) for chunk_num in range(0, frame_count, chunk_frames): # Create temporary video for chunk temp_video = f'chunk_{chunk_num}.mp4' # Extract and colorize chunk # (implementation depends on video splitting library) # Clear GPU cache between chunks torch.cuda.empty_cache() print(f"Processed chunk {chunk_num}/{frame_count}") ``` -------------------------------- ### Training YOLOv4 Model Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/USAGE_EXAMPLES.md Downloads pre-trained YOLOv4 weights and starts the training process using the configured data and model files. After training, it copies the resulting weights to Google Drive for persistence. ```python # Download pre-trained weights !cp '../drive/My Drive/weights/yolov4.conv.137' build/darknet/x64/ # Start training !./darknet detector train build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/yolov4.conv.137 -dont_show # Save checkpoint to Drive !cp -r build/darknet/x64/backup/*.weights "/content/drive/My Drive/models/yolo-obj/" ``` -------------------------------- ### Update and Upgrade System Packages Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Installs and updates system packages, and displays system information. This is a common first step in Colab environments. ```bash !apt update !apt upgrade -y !uname -m && cat /etc/*release !gcc --version !uname -r ``` -------------------------------- ### Listing Specific Video Files Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb This command lists files in the 'pyannote-data/' directory that start with 'BRICS'. It's a more targeted way to view the relevant video and data files created during the process. ```bash ls pyannote-data/BRICS* ``` -------------------------------- ### Colorize Local Image with Varying Quality Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/deoldify_colorization.md Colorizes a local image file and displays the results. This example iterates through different render factors to demonstrate the quality/speed tradeoff. The output figure size can be adjusted. ```python colorizer = get_image_colorizer(artistic=True) # Colorize with increasing quality factors for render_factor in range(10, 46, 2): colorizer.plot_transformed_image( 'test_images/image.png', render_factor=render_factor, display_render_factor=True, figsize=(7, 7) ) ``` -------------------------------- ### Get Current GPU Device Index Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/fastai_pytorch.md Retrieves the index of the currently active GPU device in PyTorch. Useful for multi-GPU setups. ```python import torch device_id = torch.cuda.current_device() print(f"Currently using GPU {device_id}") ``` -------------------------------- ### Get GPU Device Name Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/google_colab_utilities.md Queries and retrieves the model name of a GPU device using its handle. This example also includes initialization and device handle retrieval. ```python import pynvml pynvml.nvmlInit() handle = pynvml.nvmlDeviceGetHandleByIndex(0) device_name = pynvml.nvmlDeviceGetName(handle) if device_name != b'Tesla T4' and device_name != b'Tesla P100-PCIE-16GB': raise Exception("Unsupported GPU type") ``` -------------------------------- ### Get GPU Device Handle by Index Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/google_colab_utilities.md Retrieves a handle for a specific GPU device using its index. The index typically starts at 0 for the first GPU available in the system. ```python handle = pynvml.nvmlDeviceGetHandleByIndex(0) ``` -------------------------------- ### Initialize Colorizers Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/VideoColorizerColab.ipynb Initializes the DeOldify colorization models. 'get_video_colorizer()' loads the model for video processing, and 'get_image_colorizer(artistic=True)' loads the model for artistic image colorization. ```python colorizer = get_video_colorizer() colorizer_img = get_image_colorizer(artistic=True) ``` -------------------------------- ### Complete Face Detection and Clustering Pipeline Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/pyannote_video.md Demonstrates a full workflow for face detection and clustering, including initializing the clustering model, loading tracks and embeddings, running the clustering algorithm, configuring display settings, renaming clusters, exporting results to a file, and displaying the annotated video. ```python from pyannote.video.face.clustering import FaceClustering from pyannote.core import notebook, Segment import io import base64 from IPython.display import HTML # Initialize clustering clustering = FaceClustering(threshold=0.6) # Load tracks and embeddings face_tracks, embeddings = clustering.model.preprocess('data/video.embedding.txt') # Run clustering result = clustering(face_tracks, features=embeddings) # Configure display notebook.reset() notebook.crop = Segment(0, 42) # Rename clusters to person names mapping = { 0: 'Person_A', 1: 'Person_B', 2: 'Person_C' } result = result.rename_labels(mapping=mapping) # Export results with open('labels.txt', 'w') as fp: for _, track_id, cluster in result.itertracks(yield_label=True): fp.write(f'{track_id} {cluster}\n') # Display annotated video video = io.open('video.track.mp4', 'r+b').read() encoded = base64.b64encode(video) HTML(data=f'') ``` -------------------------------- ### Initialize Image Colorizer Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/deoldify_colorization.md Initializes an image colorization model. Downloads pre-trained model weights on first call. Use artistic mode for vibrant colors or stable mode for conservative colors. Requires GPU for optimal performance. ```python import fastai from deoldify.visualize import * import torch torch.backends.cudnn.benchmark = True # Load artistic colorizer colorizer = get_image_colorizer(artistic=True) # Colorize from URL image_path = colorizer.plot_transformed_image_from_url( url='https://example.com/bw_image.jpg', render_factor=13, compare=True ) ``` -------------------------------- ### List Local Weights After Copy Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb List the weight files in the local build/darknet/x64/ directory after copying them from Google Drive. This confirms the files are in place for resuming training. ```python %ls build/darknet/x64/*.weights ``` -------------------------------- ### Segment(start: float, end: float) Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/pyannote_video.md Creates a temporal segment, representing a time range in video, used for timeline filtering and display. The duration is calculated as end - start. ```APIDOC ## Segment(start: float, end: float) ### Description Creates a temporal segment for timeline cropping and annotation. Represents a time range in video, used for timeline filtering and display. Duration is calculated as end - start. ### Parameters #### Path Parameters - **start** (float) - Required - Start time in seconds - **end** (float) - Required - End time in seconds ### Returns - **Segment** - Temporal segment object ### Example ```python from pyannote.core import Segment # Create 42-second segment for display display_segment = Segment(0, 42) ``` ``` -------------------------------- ### Run YOLOv3 Demo on Video Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Guns_Detection.ipynb Executes a real-time object detection demo on a video file using a trained YOLOv3 model. Outputs the processed video with detections. ```bash ./darknet detector demo build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/guns_1000it.weights -thresh 0.20 -dont_show Guns.mp4 -out_filename Guns_output.mp4 ``` -------------------------------- ### pyannote.core.Segment Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/INDEX.md Creates a time segment with a start and end time. ```APIDOC ## pyannote.core.Segment ### Description Creates a time segment with a start and end time. ### Method ``` python Segment(start: float, end: float) ``` ### Parameters #### Path Parameters - **start** (float) - Required - The start time of the segment. - **end** (float) - Required - The end time of the segment. ``` -------------------------------- ### Download Sample Images Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb Downloads sample images from a URL to be used for object detection testing. These images serve as input for the detection process. ```bash #download Images !wget -O data/spg1.jpg http://spg.nic.in/images/SPGslide4.jpg !wget -O data/spg2.jpg http://spg.nic.in/images/SPGslide1.jpg !wget -O data/spg3.jpg http://spg.nic.in/images/SPGslide3.jpg ``` -------------------------------- ### pyannote.core.Segment Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/types.md Represents a specific time range within a video, defined by start and end times. ```APIDOC ## pyannote.core.Segment ### Description Temporal segment representing a time range in a video. ### Type Definition ```python Segment(start: float, end: float) ``` ### Fields | Field | Type | Description | |-------|------|-------------| | start | float | Start time in seconds | | end | float | End time in seconds | ### Properties | Property | Type | Description | |----------|------|-------------| | duration | float | Duration = end - start | | middle | float | Midpoint time | ### Used By - Video timeline tracking - Temporal cropping for display - Shot segmentation ### Example ```python from pyannote.core import Segment # Create 42-second segment segment = Segment(0, 42) print(segment.duration) # 42.0 print(segment.middle) # 21.0 ``` ``` -------------------------------- ### Create and Navigate to YouTube Videos Directory Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/VideoColorizerColab.ipynb These commands create a new directory named 'youtube_videos' and change the current working directory to it. This is useful for organizing downloaded YouTube content. ```python %cd .. %mkdir youtube_videos %cd youtube_videos ``` -------------------------------- ### torch.cuda.is_available() Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/google_colab_utilities.md Checks if CUDA GPU support is available in the current PyTorch installation. This is crucial for determining if GPU-accelerated operations can be utilized. ```APIDOC ## torch.cuda.is_available() ### Description Checks if CUDA GPU support is available in the current PyTorch installation. ### Method ```python import torch result = torch.cuda.is_available() ``` ### Returns - **bool**: True if GPU is available, False otherwise. ### Example ```python import torch if not torch.cuda.is_available(): print('GPU not available.') ``` ``` -------------------------------- ### Get Annotation Timeline Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/pyannote_video.md Extracts the temporal coverage of all segments within an annotation. Merges overlapping tracks into a unified timeline. ```python # Get timeline information timeline = face_tracks.get_timeline() # Returns temporal coverage of all face detections ``` -------------------------------- ### torch.cuda.get_device_name(device: int) Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/fastai_pytorch.md Gets the name of a specific GPU device by its index. This helps in identifying the hardware being used for computation. ```APIDOC ## torch.cuda.get_device_name(device: int) ### Description Gets the name of a GPU device. ### Parameters #### Path Parameters - **device** (int) - Optional - Default: current - GPU device index. ### Returns - **str**: Device name (e.g., "Tesla T4"). ### Example ```python import torch device_name = torch.cuda.get_device_name(0) print(f"GPU: {device_name}") ``` ``` -------------------------------- ### List Trained Weights Files Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb List all weight files present in the backup directory. This is useful for checking the progress of training and identifying available checkpoints. ```python %ls build/darknet/x64/backup/*.weights ``` -------------------------------- ### torch.cuda.current_device() Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/fastai_pytorch.md Returns the index of the currently active GPU device. This is useful for managing multi-GPU setups or confirming which GPU is being used. ```APIDOC ## torch.cuda.current_device() ### Description Returns the index of currently active GPU. ### Returns - **int**: GPU device index (0 for first GPU). ### Example ```python import torch device_id = torch.cuda.current_device() print(f"Currently using GPU {device_id}") ``` ``` -------------------------------- ### List Files in pyannote-data Directory Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb Lists the files within the cloned pyannote-data directory. Used to confirm that the sample video was downloaded correctly. ```bash ls pyannote-data/ ``` -------------------------------- ### Upgrade Outdated Python Packages Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb Upgrades all outdated Python packages installed in the environment. Ensures that the latest versions of dependencies are used. ```bash !pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U ``` -------------------------------- ### Create Temporal Segment Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/pyannote_video.md Creates a temporal segment using start and end times in seconds. Used for timeline cropping and annotation. ```python from pyannote.core import Segment # Create 42-second segment for display display_segment = Segment(0, 42) ``` -------------------------------- ### Create Directory and Copy File from Google Drive Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb Creates a new directory and copies a video file from Google Drive into the Colab environment. This prepares data for processing. ```bash %mkdir pyannote-data !cp -r "/content/drive/My Drive/GoogleColab/BRICS.mp4" pyannote-data/ ``` -------------------------------- ### Initialize Video Colorizer Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/deoldify_colorization.md Initializes a video colorization model. Downloads the pre-trained model and is optimized for processing frame sequences to maintain temporal consistency. Requires significant GPU memory for longer videos. ```python import fastai from deoldify.visualize import * import torch torch.backends.cudnn.benchmark = True # Load video colorizer colorizer = get_video_colorizer() # Colorize video (see method documentation below) ``` -------------------------------- ### Check GPU Availability with PyTorch Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/errors.md Use this snippet to verify if a GPU is accessible by PyTorch. Ensure PyTorch is installed and CUDA is properly configured. ```python import torch if not torch.cuda.is_available(): print('GPU not available.') ``` -------------------------------- ### Download Pretrained Models Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/VideoColorizerColab.ipynb Downloads the pre-trained weights for both video and image colorization models. These models are saved into a 'models' directory within the DeOldify folder. ```bash !mkdir 'models' #Download Pretrained Weights for video !wget https://www.dropbox.com/s/336vn9y4qwyg9yz/ColorizeVideo_gen.pth?dl=0 -O ./models/ColorizeVideo_gen.pth #Download Pretrained Weights for image !wget https://www.dropbox.com/s/zkehq1uwahhbc2o/ColorizeArtistic_gen.pth?dl=0 -O ./models/ColorizeArtistic_gen.pth ``` -------------------------------- ### Import DeOldify and Fastai Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/ImageColorizerColab.ipynb Imports the DeOldify visualization utilities and Fastai library. Sets PyTorch's cuDNN benchmark to True for performance optimization. ```python import fastai from deoldify.visualize import * torch.backends.cudnn.benchmark = True ``` -------------------------------- ### Get GPU Device Name Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/fastai_pytorch.md Retrieves the name of a specified GPU device using its index. Defaults to the current device if no index is provided. ```python import torch device_name = torch.cuda.get_device_name(0) print(f"GPU: {device_name}") ``` -------------------------------- ### Download DeOldify Models Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/ImageColorizerColab.ipynb Creates a 'models' directory and downloads the pre-trained 'ColorizeArtistic_gen.pth' model weights from a Dropbox URL. ```bash !mkdir 'models' !wget https://www.dropbox.com/s/zkehq1uwahhbc2o/ColorizeArtistic_gen.pth?dl=0 -O ./models/ColorizeArtistic_gen.pth ``` -------------------------------- ### List Downloaded Videos Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/VideoColorizerColab.ipynb This command lists the files within a specific directory, showing the structure of downloaded videos and their descriptions. It helps verify the download process and organization. ```bash !ls Tommydan333/Uploads_from_Tommydan333/ ``` -------------------------------- ### List Files Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Lists files with detailed information, including size and permissions, for all .mp4 files in the current directory. ```bash ls -lh *.mp4 ``` -------------------------------- ### Zip Video Descriptions Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/VideoColorizerColab.ipynb This command creates a zip archive named 'all_video_desc.zip' containing the downloaded video descriptions and associated files from the specified directory. Use this to compress and back up your downloaded metadata. ```bash !zip -r all_video_desc.zip Tommydan333/Uploads_from_Tommydan333/ ``` -------------------------------- ### Fixing Makefile Compilation Error in Darknet Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/errors.md Resolves 'make: *** [Makefile] Error 1' by ensuring CUDA toolkit is installed and rebuilding the project. Use when encountering 'nvcc: No such file or directory'. ```bash # Install CUDA development tools !apt-get update !apt-get install -y cuda-toolkit # Rebuild cd darknet make clean make ``` -------------------------------- ### Visualize Face Tracks with pyannote-face.py Demo Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb Generates a video demonstrating the detected face tracks. This command requires the input video, the tracking data file, and specifies the output video file name. It may download necessary dependencies like ffmpeg if not found. ```bash !pyannote-face.py demo pyannote-data/BRICS.mp4 \ pyannote-data/BRICS.track.txt \ pyannote-data/BRICS.track.mp4 ``` -------------------------------- ### Run YOLOv3 Demo on Video (Google Colab) Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Runs a YOLOv3 model on a video file for object detection within Google Colab, saving the results to a specified output file. ```bash !./darknet detector demo build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/smoking_800it_1avgLoss.weights -thresh 0.20 -dont_show Smoking.mp4 -out_filename Smoking_20%.mp4 ``` -------------------------------- ### Manage CUDA Memory for Out of Memory Errors Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/errors.md This example demonstrates strategies to mitigate CUDA out of memory errors by reducing batch size, clearing the GPU cache, and processing data sequentially. ```python import torch # Reduce batch size batch_size = 32 # Reduce from 64 # Clear GPU cache torch.cuda.empty_cache() # Reduce input size img_size = 416 # Use 416x416 instead of 608x608 # Process sequentially for item in data: output = model(item) torch.cuda.empty_cache() ``` -------------------------------- ### Create and Initialize VideoWriter Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/opencv_utilities.md Use `cv2.VideoWriter` to create a new video file. Specify the output filename, codec (fourcc), frames per second (fps), and frame size. Check `isOpened()` after creation to ensure initialization was successful. ```python import cv2 # Define codec and properties fourcc = cv2.VideoWriter_fourcc(*'mp4v') # MP4 codec fps = 30.0 frame_size = (1920, 1080) # Create writer out = cv2.VideoWriter('output.mp4', fourcc, fps, frame_size) if not out.isOpened(): print("Failed to create writer") else: # Write frame (must be 1920x1080) out.write(frame) # Close when done out.release() ``` -------------------------------- ### Copying Video Files to Google Drive Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb This command copies all files starting with 'BRICS' from the 'pyannote-data/' directory to a specified folder in Google Drive. This is a common practice for backing up or organizing processed data. ```bash !cp -r pyannote-data/BRICS* "/content/drive/My Drive/GColab_ML_DL/pyannote_data/" ``` -------------------------------- ### pynvml.nvmlInit Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/google_colab_utilities.md Initializes the NVIDIA Management Library interface. This must be called before using other pynvml functions. ```APIDOC ## pynvml.nvmlInit ### Description Initializes the NVIDIA Management Library interface. ### Method `nvmlInit` ### Example ```python import pynvml pynvml.nvmlInit() ``` ``` -------------------------------- ### Create Object Names File Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Guns_Detection.ipynb Creates the 'obj.names' file, which lists the names of the custom objects to be detected. Each object name should be on a new line. ```python all_classes = "Gun" file = "text_file = open(\"build/darknet/x64/data/obj.names\", \"w\");text_file.write(all_classes);text_file.close()" exec(file) %pycat build/darknet/x64/data/obj.names ``` -------------------------------- ### Initialize Image Colorizer Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/ImageColorizerColab.ipynb Initializes the DeOldify image colorizer object. Set 'artistic=True' for artistic colorization. ```python colorizer = get_image_colorizer(artistic=True) ``` -------------------------------- ### Video Colorization Configuration Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/configuration.md Sets up and executes video colorization using DeOldify. Specifies input and output file names, and the render factor for quality/speed balance. ```python from deoldify.visualize import get_video_colorizer colorizer = get_video_colorizer() output_path = colorizer.colorize_from_file_name( file_name='bw_video.mp4', output_file_name='colorized_video.mp4', render_factor=13 ) # For different video lengths: # 1 minute: ~2-3 minutes processing time # 5 minutes: ~10-15 minutes processing time # 10 minutes: ~20-30 minutes processing time ``` -------------------------------- ### Train YOLOv4 Model on Linux Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb This command initiates the training process for a YOLOv4 model on a Linux system. It specifies the data configuration, network configuration, and pre-trained weights to use. ```python # To train on Linux use command: !./darknet detector train build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/yolov4.conv.137 -dont_show ``` -------------------------------- ### Create Train and Validation Files Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Generates 'train.txt' and 'valid.txt' files, populating them with paths to image files, randomly splitting them into training (80%) and validation (20%) sets. ```python import os, fnmatch import numpy as np train_file = open("build/darknet/x64/data/train.txt", "w") valid_file = open("build/darknet/x64/data/valid.txt", "w") listOfFiles = os.listdir('build/darknet/x64/data/obj/') pattern = "*.jpg" for f_name in listOfFiles: if fnmatch.fnmatch(f_name, pattern): if np.random.rand(1) < 0.8: train_file.write("build/darknet/x64/data/obj/"+f_name+"\n") #print ("data/obj/"+f_name) else: valid_file.write("build/darknet/x64/data/obj/"+f_name+"\n") train_file.close() valid_file.close() ``` -------------------------------- ### Display pyannote-structure.py Help Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb Displays the help message for the pyannote-structure.py script, showing available commands and options. Useful for understanding script functionality. ```bash !pyannote-structure.py --help ``` -------------------------------- ### Create PyTorch Tensors Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/fastai_pytorch.md Demonstrates various methods for creating PyTorch tensors, including from Python lists, random initialization, zeros, ones, and NumPy arrays. Ensure PyTorch is imported. ```python import torch # From Python lists x = torch.tensor([1.0, 2.0, 3.0]) # Random tensors x = torch.randn(3, 4) # Normal distribution x = torch.rand(3, 4) # Uniform [0, 1) # Zeros and ones x = torch.zeros(3, 4) x = torch.ones(3, 4) # From numpy import numpy as np np_array = np.array([1, 2, 3]) x = torch.from_numpy(np_array) ``` -------------------------------- ### Download YOLOv4 Weights Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb Downloads the pre-trained YOLOv4 weights file required for object detection. Ensure the path is correct or use the provided Google Drive link. ```python #Download yolov4.weights file %cp '../drive/My Drive/Colab Notebooks/Darknet/yolov4.weights' . ``` -------------------------------- ### Configuration for YOLOv4 Object Detection Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/USAGE_EXAMPLES.md Creates the 'obj.names' and 'obj.data' files required for custom dataset training. It also configures the 'yolov4.cfg' file for single-class detection by modifying parameters like batch size, input dimensions, and training steps. ```python # Create class names file all_classes = """Firearm """ with open("build/darknet/x64/data/obj.names", "w") as f: f.write(all_classes) # Create dataset metadata file obj_data = """classes=1 train=build/darknet/x64/data/train.txt valid=build/darknet/x64/data/valid.txt names=build/darknet/x64/data/obj.names backup=build/darknet/x64/backup/ """ with open("build/darknet/x64/data/obj.data", "w") as f: f.write(obj_data) # Configure model architecture import subprocess # Copy base config subprocess.run(['cp', 'cfg/yolov4.cfg', 'cfg/yolo-obj.cfg']) # Modify for single-class detection modifications = [ ('s/batch=64/batch=32/g', 'Batch size'), ('s/subdivisions=8/subdivisions=16/g', 'Gradient accumulation'), ('s/width=608/width=416/g', 'Input width'), ('s/height=608/height=416/g', 'Input height'), ('s/max_batches = 500500/max_batches = 4000/g', 'Training iterations'), ('s/steps=400000,450000/steps=3200,3600/g', 'Learning rate schedule'), ('s/classes=80/classes=1/g', 'Number of classes'), ('s/filters=255/filters=18/g', 'Output filters = (1+5)*3'), ] for pattern, desc in modifications: subprocess.run(['sed', '-i', pattern, 'cfg/yolo-obj.cfg']) ``` -------------------------------- ### Processing and Rendering Videos from Local Files Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/VideoColorizerColab.ipynb Processes videos from a local source directory, renders them using a specified render factor, and copies the results to a target directory. Includes error handling for file operations. ```python class color: BLUE = '\033[94m' GREEN = '\033[92m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' #The above code is just for fun only! import os import shutil from os import listdir from os.path import isfile, join render_factor = 21 #This is the default directory, first you have to copy the video here old_video_source = 'video/source/' fileName = [] i = [] fileNames = [f for f in listdir(old_video_source) if isfile(join(old_video_source, f))] for fileName in fileNames: try: #Video proccessing & rendering print(color.BOLD + str(fileName) + color.END + color.BLUE + ' ready for proccessig.' + color.END) video_path = colorizer.colorize_from_file_name(str(fileName), render_factor) print(color.GREEN + 'Video rendering done, Now ' + color.END + color.BOLD + fileName + color.END + ' file ready for copy.') #Copying file build_video_dir = 'video/result/' new_build_video_path = build_video_dir + str(fileName) target_dir = '../drive/My Drive/Colab Notebooks/Old_ColorizeVideos' assert not os.path.isabs(new_build_video_path) target = os.path.join(target_dir, os.path.dirname(new_build_video_path)) # Create the folders if not already exists #os.makedirs(target_dir) # adding exception handling try: shutil.copy(new_build_video_path, target_dir) print(color.BOLD + fileName + color.RED + " Successfully Copied to " + color.END + target_dir + "\n") except IOError as e: print("Unable to copy file. %s" % e) except: print("Unexpected error:", sys.exc_info()) ``` -------------------------------- ### Create Object Names File Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Creates the 'obj.names' file in the Darknet data directory, listing the names of the objects to be detected. Each object name should be on a new line. ```python all_classes = """Smoking """ file = """text_file = open(\"build/darknet/x64/data/obj.names\", \"w\");text_file.write(all_classes);text_file.close()""" exec(file) %pycat build/darknet/x64/data/obj.names ``` -------------------------------- ### Image Colorization Render Factor Comparison Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/configuration.md Illustrates the speed and quality trade-offs for image colorization based on the render factor. Higher render factors yield better quality but are slower. ```python # Fast colorization (high quality factor = lower actual speed) render_factor = 13 # Balanced speed/quality # Speed: ~2-3 seconds per image on T4 GPU # Slow colorization (maximum quality) render_factor = 45 # Maximum quality # Speed: ~5-10 seconds per image on T4 GPU ``` -------------------------------- ### Run YOLOv3 Demo on Video (Colab) Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Guns_Detection.ipynb Runs the Darknet YOLOv3 object detection demo on a video file within a Google Colab environment. This command processes the video and saves the output. ```python !./darknet detector demo build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/smoking_800it_1avgLoss.weights -thresh 0.20 -dont_show Guns.mp4 -out_filename Guns_1class_20%.mp4 ``` -------------------------------- ### Download Files from Google Colab Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Initiates a download prompt for specified files from the Google Colab environment to the user's local machine. ```python from google.colab import files files.download('build/darknet/x64/yolo-obj_1500up_05avgLoss.weights') ``` -------------------------------- ### Run YOLOv3 Demo on Video Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Executes a YOLOv3 model on a video file to detect objects and saves the output to a new video file. The '-dont_show' flag prevents displaying the video during processing. ```bash ./darknet detector demo build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/smoking_1000it.weights -thresh 0.20 -dont_show Smoking.mp4 -out_filename Smoking_output.mp4 ``` -------------------------------- ### Resume YOLOv3 Training (Google Colab) Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Command to resume YOLOv3 training from a previously saved weight file in a Google Colab environment. ```bash !./darknet detector train build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/yolo-obj_1000.weights -dont_show ``` -------------------------------- ### get_video_colorizer Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/deoldify_colorization.md Initializes a video colorization model. This function downloads the pre-trained model and is optimized for processing frame sequences to maintain temporal consistency. ```APIDOC ## get_video_colorizer() ### Description Initializes a video colorization model. This function downloads the pre-trained model and is optimized for processing frame sequences to maintain temporal consistency. ### Parameters None ### Returns VideoColorizer - Colorizer object for video processing ### Behavior - Downloads pre-trained video colorization model - Processes frame sequences to maintain temporal consistency - Requires significant GPU memory for longer videos - Leverages PyTorch and FastAI backend ### Example ```python import fastai from deoldify.visualize import * import torch torch.backends.cudnn.benchmark = True # Load video colorizer colorizer = get_video_colorizer() # Colorize video (see method documentation below) ``` ``` -------------------------------- ### Project File Organization Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/INDEX.md Illustrates the directory structure of the deep learning project, showing the location of key markdown files and API reference documentation. ```text /workspace/home/output/ ├── README.md (Main entry point) ├── PROJECT_OVERVIEW.md (Context) ├── types.md (Type definitions) ├── configuration.md (Configuration options) ├── errors.md (Error handling) ├── USAGE_EXAMPLES.md (Workflows) ├── INDEX.md (This file) └── api-reference/ ├── google_colab_utilities.md ├── darknet_yolo.md ├── deoldify_colorization.md ├── pyannote_video.md ├── opencv_utilities.md └── fastai_pytorch.md ``` -------------------------------- ### Generating Annotated Video with pyannote-face.py Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/pyannote_video - Face Detection, Tracking & clustering in Videos.ipynb This command-line snippet uses the pyannote-face.py script to generate a new video file with face detection and tracking annotations. It takes the input video, track information, and label file as arguments. ```bash !pyannote-face.py demo pyannote-data/BRICS.mp4 \ pyannote-data/BRICS.track.txt \ --label=pyannote-data/BRICS1.labels.txt \ pyannote-data/BRICS1.final.mp4 ``` -------------------------------- ### Download YouTube Video Descriptions Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/VideoColorizerColab.ipynb This command downloads only the description for each video from a YouTube channel, saving it to a .description file. It skips the actual video download. This is useful for archiving metadata without downloading large video files. ```bash !youtube-dl --skip-download --youtube-skip-dash-manifest --write-description -o '%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' --restrict-filenames -v https://www.youtube.com/user/Tommydan333 ``` -------------------------------- ### List Weights in Google Drive Backup Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv4_Google_Colab_(Firearm_Detection).ipynb List the contents of the backup directory on Google Drive. This command verifies that the weights files have been successfully copied and are available. ```python %ls '../drive/My Drive/Colab Notebooks/Darknet/backup/' ``` -------------------------------- ### Run Darknet YOLO Detector Demo Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/darknet_yolo.md Executes the Darknet detector on a video file, processing frames individually and saving the output with detections. Use the `-dont_show` flag to disable on-screen playback. ```bash ./darknet detector demo build/darknet/x64/data/obj.data cfg/yolo-obj.cfg build/darknet/x64/yolo-obj_1500up_05avgLoss.weights firearms_video.mp4 -dont_show ``` -------------------------------- ### Initialize pynvml for GPU Management Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/_autodocs/api-reference/google_colab_utilities.md Initializes the NVIDIA Management Library (NVML) interface. This must be called before using other pynvml functions to query GPU information. ```python import pynvml pynvml.nvmlInit() ``` -------------------------------- ### Display YOLOv3 Configuration Source: https://github.com/hardik0/deep-learning-with-googlecolab/blob/master/Darknet_YOLOv3_Cigarette_Smoking_Detection.ipynb Prints the content of the modified YOLOv3 configuration file to verify the changes. ```bash %pycat cfg/yolo-obj.cfg ```