pymediainfo

repository·master·Indexed 18 days ago

https://github.com/sbraz/pymediainfo

A Python wrapper for the MediaInfo library used to programmatically extract detailed multimedia metadata from video, audio, and image files. It provides the MediaInfo.parse() method to retrieve metadata as MediaInfo objects, JSON, XML, or text reports, and includes utilities to convert tracks to dictionaries and handle dynamic attributes safely.

Tokens
2.6K
Snippets
11
Records
13
Agent score
63%

What's inside pymediainfo

  1. Handle missing track attributes safely

    master

    Track attributes are dynamic. To prevent AttributeError when accessing a property that doesn't exist for a specific track, pymediainfo overrides __getattribute__ to return None instead of raising an error. You can check for existence using a simple is None check.

    from pymediainfo import MediaInfo
    
    media_info = MediaInfo.parse("my_video_file.mp4")
    for track in media_info.tracks:
        if track.bit_rate is None:
            print(f"{track.track_type} tracks do not have a bit rate")
        else:
            print(f"Bit rate: {track.bit_rate}")
  2. How pymediainfo performs library autodetection

    master

    By default, pymediainfo uses library_file=None to automatically locate the required MediaInfo shared library. The autodetection process follows these steps:

    1. Filename Determination: The library filename is chosen based on the operating system:

      • Linux: libmediainfo.so.0
      • macOS: Searches for libmediainfo.0.dylib first, then libmediainfo.dylib.
      • Windows: MediaInfo.dll
    2. Local Search: The library first looks in the same directory as pymediainfo/__init__.py. If you installed via a wheel, the bundled library is typically found here.

    3. System Search: If not found locally, the library attempts to load the determined filename from standard system paths using ctypes.CDLL (Linux/macOS) or ctypes.WinDLL (Windows).

  3. Install pymediainfo

    master

    pymediainfo is a wrapper for the MediaInfo library. Crucially, you must have the MediaInfo library installed on your system for pymediainfo to parse media files. Without it, you can only process pre-generated XML output.

    Using PyPI (Linux, macOS, Windows)

    Install via pip to get wheels that include a bundled version of the MediaInfo library:

    python -m pip install pymediainfo

    If you prefer to use a system-wide MediaInfo library instead of the bundled one, install without binaries:

    python -m pip install pymediainfo --no-binary pymediainfo

    Linux Distribution Packages

    On Linux, it is often preferred to use your distribution's package manager (e.g., apt, dnf) to install pymediainfo. This allows for independent updates to both the wrapper and the underlying MediaInfo library.

    python -m pip install pymediainfo
  4. Parse pre-generated MediaInfo XML output

    master

    If you have an existing XML string (for example, generated via mediainfo --output=OLDXML), you can create a MediaInfo object by passing the XML string directly to the MediaInfo constructor.

    from pymediainfo import MediaInfo
    
    raw_xml_string = """<?xml version="1.0" encoding="UTF-8"?>
    <Mediainfo version="24.11">
    <File>
    <track type="General">
    <Complete_name>binary_file</Complete_name>
    <File_size>1.00 Byte</File_size>
    </track>
    </File>
    </Mediainfo>"""
    
    media_info = MediaInfo(raw_xml_string)
    print(f"File name is: {media_info.general_tracks[0].complete_name}")
  5. Get media information from a file

    master

    Use the MediaInfo.parse() method to extract metadata from a file path. This returns a MediaInfo object containing various tracks.

    Tracks can be accessed via the .tracks attribute or through type-specific shorthands like .image_tracks, .audio_tracks, .video_tracks, or .general_tracks.

    from pymediainfo import MediaInfo
    
    media_info = MediaInfo.parse("/home/user/image.jpg")
    # Accessing tracks via shorthands
    general_track = media_info.general_tracks[0]
    image_track = media_info.image_tracks[0]
    
    print(f"{image_track.format} of {image_track.width}×{image_track.height} pixels")
  6. Convert MediaInfo tracks to a dictionary

    master

    Because track attributes are dynamically created during parsing, you may not know all available keys at runtime. Use the .to_data() method on a Track object to return a dict containing all its attributes. This is useful for inspecting unknown metadata.

    from pymediainfo import MediaInfo
    
    media_info = MediaInfo.parse("my_video_file.mp4")
    for track in media_info.tracks:
        if track.track_type == "Audio":
            # Returns a dictionary of all available attributes
            print(track.to_data())
  7. Generate a text report similar to the MediaInfo CLI

    master

    To get a human-readable text report instead of a MediaInfo object, call MediaInfo.parse() with output="text".

    • Use full=True (default) for verbose output.
    • Use full=False for a more concise report.
    from pymediainfo import MediaInfo
    
    # Returns a string instead of a MediaInfo object
    report = MediaInfo.parse("my_video_file.mp4", output="text", full=False)
    print(report)
  8. Extract attributes from a Track object

    master

    Each Track object represents a specific media stream (e.g., Video, Audio). Attributes are mapped from MediaInfo's output and are accessed using lowercase names (e.g., track.duration, track.codec).

    Handling Repeated Attributes: If an attribute appears multiple times in the metadata (like Duration), the primary attribute is set to an integer value if possible. The other human-readable versions are stored in a list under a new attribute prefixed with other_ (e.g., track.other_duration).

    Missing Attributes: If you access an attribute that does not exist for that track, None is returned instead of raising an AttributeError.

    t = mi.tracks[0]
    print(t.duration)          # e.g., 3000
    print(t.other_duration)    # e.g., ['3 s 0 ms', '00:00:03.000']
    print(t.non_existing)      # returns None
  9. Check if MediaInfo can be used

    master

    Use MediaInfo.can_parse() to verify if the libmediainfo library is correctly installed and accessible on your system. This is useful for pre-flight checks in your application.

    if pymediainfo.MediaInfo.can_parse():
        print("MediaInfo is ready to use!")
    else:
        print("MediaInfo library not found.")
  10. Access media tracks via MediaInfo

    master

    A MediaInfo object contains a list of Track objects accessible via the tracks attribute. You can also use convenience properties to filter tracks by type:

    • general_tracks
    • video_tracks
    • audio_tracks
    • text_tracks
    • image_tracks
    • menu_tracks
    • other_tracks
    mi = pymediainfo.MediaInfo.parse("video.mp4")
    for track in mi.video_tracks:
        print(track.codec)
  11. Convert MediaInfo and Track data to dictionaries or JSON

    master

    You can export the metadata extracted by MediaInfo or Track objects into standard Python formats:

    • Track.to_data(): Returns a dict of all attributes for a single track.
    • MediaInfo.to_data(): Returns a dict containing a list of all tracks: {"tracks": [...]}.
    • MediaInfo.to_json(): Returns a JSON string representation of the entire MediaInfo object.
    # For a single track
    data = track.to_data()
    
    # For the whole MediaInfo object
    json_str = mi.to_json()
  12. Analyze a media file with MediaInfo.parse()

    master

    Use MediaInfo.parse() to extract metadata from a media file. You can pass a file path, a pathlib.Path object, or a file-like object (opened in binary mode).

    By default, it returns a MediaInfo object containing Track objects. If you specify an output format (like "JSON" or "XML"), it returns a str instead.

    Important Threading Note: Do not call parse() simultaneously from multiple threads with different parameters (especially when using mediainfo_options), as this can cause inconsistencies in the shared underlying library.

    import pymediainfo
    
    # Returns a MediaInfo object
    mi = pymediainfo.MediaInfo.parse("tests/data/sample.mkv")
    
    # Returns a JSON string
    json_output = pymediainfo.MediaInfo.parse("tests/data/sample.mkv", output="JSON")