Last active
August 29, 2015 14:20
-
-
Save MatiasArriola/8d1711d2f2be6ee08f1a to your computer and use it in GitHub Desktop.
Extract text values from PSD files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from psd_tools import PSDImage, Group | |
import json | |
import os | |
def extract_text_from_psd(psd): | |
""" | |
Receives a path to a psd file. | |
Returns a dict of layer_id:text. | |
Nested dicts are also included if there are groups in the psd file | |
""" | |
result = {} | |
psd = PSDImage.load(psd) | |
for layer in psd.layers: | |
extracted_layer = extract_layer(layer) | |
if extracted_layer: | |
result[layer.layer_id] = extracted_layer | |
return result | |
def extract_text_from_psd_list(psds): | |
return [dict(file=psd, value=extract_text_from_psd(psd)) for psd in psds] | |
def extract_layer(layer): | |
if isinstance(layer, Group): | |
result = {} | |
for sublayer in layer.layers: | |
extracted_layer = extract_layer(sublayer) | |
if extracted_layer: | |
result[sublayer.layer_id] = extracted_layer | |
return result | |
else: | |
if layer.text_data is None: | |
return None | |
else: | |
return layer.text_data.text | |
def get_psd_files_in_dir(dir): | |
psd_files = [] | |
for root, dirs, files in os.walk(dir): | |
for file in files: | |
if file.endswith(".psd"): | |
psd_files.append(os.path.join(root, file)) | |
return psd_files | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser(description='Extract text from PSD files') | |
parser.add_argument('--input', '-i', dest='inputfile', required=False, default='.', help='PSD file or directory to extract text layers from') | |
args = parser.parse_args() | |
if not os.path.exists(args.inputfile): | |
raise ValueError('File or directory does not exist: {0}'.format(args.inputfile)) | |
if os.path.isfile(args.inputfile): | |
print json.dumps(extract_text_from_psd(args.inputfile), indent=4) | |
else: | |
psds = get_psd_files_in_dir(".") | |
print json.dumps(extract_text_from_psd_list(psds), indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment