pythonsafe-tensors

Extract trigger words from safetensors file


With many .safetensors files associated to different LoRA authors sometimes specify "trigger words". I've been trying to extract find the way to extract them from .safetensors file but I cannot find them. They are not present in metadata section and according to documentation I cannot think of other place where those can be.

On the other hand, I know that those trigger words are working, because I am getting image generated when I'm providing them.

I thought that something like this will work: from safetensors import safe_open

tensors = {}
with safe_open("lora.safetensors", framework="pt") as f:
   print(f.metadata())

But it seems the access is more complicated. Any suggestion?


Solution

  • Adapting from https://huggingface.co/docs/safetensors/metadata_parsing#python:

    import json
    import struct
    
    with open("lora.safetensors", "rb") as f:
        length_of_header = struct.unpack('<Q', f.read(8))[0]
        header_data = f.read(length_of_header)
        header = json.loads(header_data)
    
    print(header)  # should be a dict that contains what you need