Updated on 2026-11-06 GMT+08:00

Video Frame Description and Summarization Example

This example demonstrates how to use scalar UDFs and UDAFs to describe video frames and generate video summaries. It extracts frames from a real video file via the AV library, stores them in a database table, uses the BLIP model to generate natural language descriptions for each frame, and employs the T5 model to aggregate these descriptions into a coherent video summary.

Scenario

In video content analysis, key frames need to be extracted from a video, natural language descriptions generated for each frame, and multiple frame descriptions synthesized into a coherent video summary. A scalar UDF in class form loads the BLIP model in __init__ and generates image descriptions for each frame in __call__. A UDAF aggregates multiple frame descriptions and uses the T5 model to generate a summary. This example uses the AV library to extract frames from a real video file as test data.

Notes and Constraints

  • The transformers package must be installed via pip during UDF runtime. Ensure the runtime environment has network access.
  • The __init__ parameters of a scalar UDF only support constant values.
  • It is recommended to call delete_function to clean up functions with the same name before registering a UDF to avoid errors during repeated execution.

Prerequisites

Preparations

This example uses the BLIP image captioning model and T5 text summarization model. You need to prepare the model files, video files, and Python dependencies.

  1. Install the Python dependencies.
    pip install torch==2.6.0
    pip install transformers==5.3.0 
    pip install pillow 
    pip install av
  2. Install the Hugging Face command line tool.
    pip install huggingface-hub
  3. Download the test video file to the same directory as the example script and rename it test_video.mp4.

    Download a short MP4 video that contains real-world scenes (recommended under 10 seconds).

  4. Download the BLIP image captioning model file to the same directory as the example script.
    hf download Salesforce/blip-image-captioning-base --local-dir ./blip-image-captioning-base
    If the hf download command is unavailable, manually download the file using a browser.
    1. Search for Salesforce/blip-image-captioning-base on the Hugging Face website and go to the model homepage.
    2. Click the Files and versions tab.
    3. Download the following files and save them to the local blip-image-captioning-base directory:
      • config.json
      • preprocessor_config.json
      • pytorch_model.bin
      • special_tokens_map.json
      • tokenizer_config.json
      • tokenizer.json
      • vocab.txt
    4. Place the blip-image-captioning-base directory in the same directory as the example script.
  5. Download the T5 text summarization model file to the same directory as the example script.
    hf download google-t5/t5-small --local-dir ./t5-small

    If the hf download command is unavailable, manually download the file using a browser.

    1. Search for google-t5/t5-small on the Hugging Face website and go to the model homepage.
    2. Click the Files and versions tab.
    3. Download the following files and save them to the local t5-small directory:
      • config.json
      • pytorch_model.bin
      • spiece.model
      • tokenizer.json
      • tokenizer_config.json
      • generation_config.json
    4. Place the t5-small directory in the same directory as the example script.

Example

This example integrates the entire process of video frame description and summary generation into a single executable code block. It includes connection management, scalar UDF definition (generating frame descriptions based on the BLIP model), UDAF definition (generating video summaries based on the T5 model), function registration, video frame extraction, frame-level description generation, and video summary aggregation.

  1. Import dependencies and define the create_connect context manager to encapsulate the creation and release of Aura service connections.
  2. Define the scalar UDF class VideoContentAnalyzer. Load the BLIP model in __init__. In __call__, generate descriptions for each frame of JPEG data, analyze content features, and return results in JSON format.
  3. Define the VideoSummaryGenerator class, load the T5 model, and aggregate multiple frame descriptions to generate a video summary.
  4. Define the UDAF class VideoSummarySystem. Use accumulate to collect descriptions of each frame, and finish to call the T5 model to generate a video summary.
  5. Connect to the AuraJobV2 endpoint and set the UDF workspace. Delete the existing UDFs and UDAFs with the same name, and then register them to the target database.
  6. Use the AV library to extract a maximum of 10 frames (in JPEG format) from the video file, create the video_frames table, and write the binary frame data.
  7. Load the video_frames dataset and use map_batches to call the scalar UDF to analyze each frame and generate the descriptions column.
  8. Call the UDAF via AggregateFnBuilder to aggregate multiple frame descriptions and generate a video summary, execute the query, and print the results.
import ibis
import typing
import os
from contextlib import contextmanager
from aura_frame.multimodal import ai_lake
from aura_frame.multimodal.function import AggregateFnBuilder

target_database = "test"  #Create a database in LakeFormation, for example, test. For details, see Creating a DataArts Lake Formation Instance and Planning Metadata.
@contextmanager
def create_connect():
#Connect to the AuraJobV2 endpoint. For details about the parameters, see Establishing a Connection with the AuraJobV2 Endpoint.
    con = ai_lake.connect(
        aura_endpoint=os.getenv("aura_endpoint"),         # Endpoint where the AuraJobV2 endpoint is located
        aura_endpoint_id=os.getenv("aura_endpoint_id"),    # AuraJobV2 endpoint ID
        aura_endpoint_name=os.getenv("aura_endpoint_name"),# AuraJobV2 endpoint name
        aura_workspace_id=os.getenv("aura_workspace_id"),  # Workspace ID
        lf_catalog_name=os.getenv("lf_catalog_name"),      # LakeFormation Catalog name
        access_key=os.getenv("access_key"),                # Access Key ID (AK)
        secret_key=os.getenv("secret_key"),                # Secret Key (SK)
        default_database=target_database,                       # LakeFormation database name
        use_single_cn_mode=True,   # Whether to enable the single-CN mode
        logging_level=logging.INFO # Set the log level.
    )
    print(f"Establish ai_lake.connect: {con}")
    try:
        yield con
    finally:
        # Close the connection.
        con.close()

class VideoContentAnalyzer:
    def __init__(self, model_name="./blip-image-captioning-base"):
        import torch
        from transformers import BlipProcessor, BlipForConditionalGeneration
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        self.processor = BlipProcessor.from_pretrained(model_name)
        self.model = BlipForConditionalGeneration.from_pretrained(
            model_name,
            torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
        ).to(self.device)
        self.model.eval()
    def __call__(self, frame: bytes, frame_index: int) -> str:
        import json
        analyse = self.analyze_frame(frame, frame_index)
        return json.dumps({"description": analyse})
    def analyze_frame(self, frame: bytes, frame_index: int):
        try:
            frame_description = self._generate_frame_description(frame)
            content_features = self._analyze_content_features(frame_description)
            analyse = {
                "description": frame_description,
                "content_type": content_features["content_type"],
                "key_objects": content_features["key_objects"],
                "scene_context": content_features["scene_context"],
            }
        except Exception:
            analyse = {}
        return analyse
    def _generate_frame_description(self, frame: bytes):
        import io
        from PIL import Image
        import torch
        pil_img = Image.open(io.BytesIO(frame)).convert("RGB")
        inputs = self.processor(images=pil_img, return_tensors="pt").to(self.device)
        with torch.no_grad():
            outputs = self.model.generate(
                **inputs,
                max_length=50,
                num_beams=5,
                early_stopping=True,
            )
        description = self.processor.decode(outputs[0], skip_special_tokens=True)
        return description.strip()
    def _analyze_content_features(self, description):
        description_lower = description.lower()
        content_categories = {
            "educational": ["tutorial", "lesson", "explain", "teach", "learn", "education"],
            "entertainment": ["funny", "comedy", "entertainment", "show", "performance"],
            "nature": ["outdoor", "nature", "landscape", "mountain", "forest", "animal"],
            "sports": ["sport", "game", "player", "team", "match", "competition"],
            "food": ["food", "cooking", "recipe", "meal", "restaurant", "kitchen"],
            "technology": ["computer", "tech", "device", "electronic", "software"],
            "people": ["person", "people", "man", "woman", "child", "group"],
        }
        detected_categories = []
        for category, keywords in content_categories.items():
            if any(keyword in description_lower for keyword in keywords):
                detected_categories.append(category)
        common_objects = [
            "person", "people", "man", "woman", "child", "car", "building",
            "tree", "house", "street", "water", "sky", "food", "animal",
        ]
        key_objects = [obj for obj in common_objects if obj in description_lower]
        if any(word in description_lower for word in ["indoors", "inside", "room"]):
            scene_context = "indoor"
        elif any(word in description_lower for word in ["outdoors", "outside", "park", "street"]):
            scene_context = "outdoor"
        else:
            scene_context = "unknown"
        return {
            "content_type": detected_categories[:2] if detected_categories else ["general"],
            "key_objects": key_objects[:5],
            "scene_context": scene_context,
        }

class VideoSummaryGenerator:
    def __init__(self, model):
        from transformers import pipeline
        import torch
        self.summarizer = pipeline(
            "text-generation",
            model=model,
            device=0 if torch.cuda.is_available() else -1,
        )
    def generate_summary(self, frame_analyses):
        all_descriptions = [analysis.get("description", "") for analysis in frame_analyses]
        if not all_descriptions:
            return "Unable to analyze the video content."
        content_analysis = self._analyze_video_content(frame_analyses)
        description_text = self._create_description_text(all_descriptions, content_analysis)
        summary = self._generate_detailed_summary(description_text, content_analysis)
        return summary
    def _analyze_video_content(self, frame_analyses):
        from collections import Counter
        content_types = []
        all_objects = []
        for analysis in frame_analyses:
            content_types.extend(analysis.get("content_type", []))
            all_objects.extend(analysis.get("key_objects", []))
        common_content_types = [item for item, count in Counter(content_types).most_common(2)]
        common_objects = [item for item, count in Counter(all_objects).most_common(5)]
        return {
            "primary_categories": common_content_types,
            "dominant_objects": common_objects,
            "total_frames_analyzed": len(frame_analyses),
        }
    def _create_description_text(self, descriptions, content_analysis):
        from collections import Counter
        desc_counter = Counter(descriptions)
        representative_descs = [desc for desc, count in desc_counter.most_common(3)]
        text = "Video Content Analysis:\n"
        text += f"Primary Categories: {', '.join(content_analysis['primary_categories'])}\n"
        text += f"Key Objects: {', '.join(content_analysis['dominant_objects'][:3])}\n"
        text += "Representative Scenes:\n"
        for i, desc in enumerate(representative_descs, 1):
            text += f"{i}. {desc}\n"
        return text
    def _generate_concise_summary(self, content_analysis):
        import random
        primary_category = content_analysis["primary_categories"][0] if content_analysis["primary_categories"] else "General content"
        main_objects = ", ".join(content_analysis["dominant_objects"][:2])
        templates = [
            f"This is a {primary_category} video that includes elements like {main_objects}.",
            f"The video presents a {primary_category} scenario, with its focus on {main_objects}.",
            f"The content centers on {primary_category}, highlighting elements such as {main_objects}.",
        ]
        return random.choice(templates)
    def _generate_detailed_summary(self, description_text, content_analysis):
        try:
            summary = self.summarizer(
                "summarize: " + description_text,
                max_length=150,
                min_length=50,
                do_sample=False,
            )[0]["generated_text"]
            return summary
        except Exception:
            return self._generate_concise_summary(content_analysis)

class VideoSummarySystem:
    def __init__(self, model="./t5-small"):
        self.summary_generator = VideoSummaryGenerator(model)
        self.frame_descriptions = []
    def accumulate(self, description: str) -> None:
        import json
        data = json.loads(description)
        self.frame_descriptions.append(data.get("description", data))
    def finish(self) -> str:
        import json
        summary = self.summary_generator.generate_summary(self.frame_descriptions)
        result = {
            "video_summary": summary,
            "frames_analyzed": len(self.frame_descriptions),
            "content_categories": list(
                set(cat for analysis in self.frame_descriptions for cat in analysis.get("content_type", []))
            ),
            "key_objects": list(
                set(obj for analysis in self.frame_descriptions for obj in analysis.get("key_objects", []))
            )[:8],
            "processing_details": {
                "total_frames": len(self.frame_descriptions),
                "successful_analyses": len(self.frame_descriptions),
            },
        }
        return json.dumps(result)
    @property
    def aggregate_state(self) -> typing.Dict[str, typing.Any]:
        return {"frame_descriptions": self.frame_descriptions}
    def merge(self, other_state: typing.Dict[str, typing.Any]) -> None:
        self.frame_descriptions += other_state.get("frame_descriptions")

with create_connect() as con:
    con.set_function_staging_workspace(
        obs_directory_base=os.getenv("obs_directory_base"),
        obs_bucket_name=os.getenv("obs_bucket_name"),
        obs_server=os.getenv("obs_server"),
        access_key=os.getenv("access_key"),
        secret_key=os.getenv("secret_key")
    )
    print("finish set_function_staging_workspace")
    con.delete_function("videocontentanalyzer", database=target_database, if_it_exists=True)
    con.create_scalar_function(
        VideoContentAnalyzer,
        database=target_database,
        packages=["transformers==5.3.0"],
        imports=["./blip-image-captioning-base"],
    )
    con.delete_function("videosummarysystem", database=target_database, if_it_exists=True)
    con.create_agg_function(
        VideoSummarySystem,
        database=target_database,
        packages=["transformers==5.3.0"],
        imports=["./t5-small"],
    )
    # Extract frames from a real video file through AV.
    import av
    import io
    from PIL import Image
    video_path = "test_video.mp4"
    container = av.open(video_path)
    stream = container.streams.video[0]
    frames = []
    frame_count = 0
    max_frames = 10
    for frame in container.decode(stream):
        if frame_count >= max_frames:
            break
        img = frame.to_image()
        buf = io.BytesIO()
        img.save(buf, format="JPEG")
        frames.append((frame_count, buf.getvalue()))
        frame_count += 1
    container.close()
    print(f"Extracted {len(frames)} frames from the video.")
    # Create a table and insert frame data.
    table_name = "video_frames"
    table_schema = ibis.schema({"frame_index": "int32", "frame_data": "binary"})
    con.sql(f'DROP TABLE IF EXISTS "{target_database}"."{table_name}";')
    con.create_table(
        table_name,
        schema=table_schema,
        database=target_database,
        table_format="orc",
        if_not_exists=True,
    )
    for frame_index, frame_bytes in frames:
        hex_str = frame_bytes.hex()
        con.sql(f'''
        INSERT INTO "{target_database}"."{table_name}" (frame_index, frame_data) VALUES
            ({frame_index}, '\\x{hex_str}'::bytea)
        ''')
    print("Video frame data has been written.")
    # Load the video frame dataset.
    ds = con.load_dataset("video_frames", database=target_database)
    ds.show(limit=1)
    # Use the scalar UDF to analyze each frame.
    udf = con.get_function("videocontentanalyzer", database=target_database)
    ds = ds.map_batches(
        fn=udf,
        on=[ds.frame_data, ds.frame_index],
        as_col="descriptions",
        num_cpus=2,
        memory=4096,
        arch="x86",
        model_name="./blip-image-captioning-base",
    )
    # ds.select_columns([ds.frame_index, ds.descriptions]).show(1)
    # Use UDAF to generate a video summary.
    udaf = con.get_function("videosummarysystem", database=target_database)
    agg_builder = AggregateFnBuilder(
        fn=udaf,
        on=[ds.descriptions],
        as_col="describe",
        num_cpus=1,
        memory=2048,
        arch="x86",
    )
    summary = ds.aggregate(agg_builder).execute()
    for row in summary.itertuples():
        print(row)