def getMeta(self, files): et = ExifTool() et.start() a = et.get_metadata_batch(files) et.terminate() meta = self._removeErrors(a) return meta
def make_plan(self): """Create a mapping to know which input files go where in the output""" plan = collections.defaultdict(list) destinations = set() input_paths = self.get_files() with ExifTool() as exiftool: for input_path in tqdm(input_paths, desc='Reading input', dynamic_ncols=True): output_path = self.get_output_path(input_path, exiftool) if output_path in destinations: raise Exception( f'Multiple files have the same destination!\n {input_path}\t→\t{output_path}.' ) if output_path.is_file(): raise Exception( f'A file already exists at destination path!\n {input_path}\t→\t{output_path}.' ) destinations.add(output_path) plan[output_path.parent].append( Map( source=input_path, destination=output_path, )) return plan
def _setup_and_add_path(self, parent_id, path): with ExifTool() as exif_tool: try: self._power_manager.acquire() self._add_path(parent_id, path, exif_tool) finally: self._power_manager.release()
def run(self): results = {} results["magic"] = magic.from_file(self.filepath) results["mimetype"] = magic.from_file(self.filepath, mime=True) binary = get_binary(self.job_id) results["md5"] = hashlib.md5(binary).hexdigest() results["sha1"] = hashlib.sha1(binary).hexdigest() results["sha256"] = hashlib.sha256(binary).hexdigest() results["ssdeep"] = pydeep.hash_file(self.filepath).decode() try: with ExifTool(self.exiftool_path) as et: exif_report = et.execute_json(self.filepath) if exif_report: exif_single_report = exif_report[0] exif_report_cleaned = { key: value for key, value in exif_single_report.items() if not (key.startswith("File") or key.startswith("SourceFile")) } # compatibility with the previous version of this analyzer results["filetype"] = exif_single_report.get("File:FileType", "") results["exiftool"] = exif_report_cleaned except Exception as e: logger.exception(e) return results
def analyze(self, file_path): with ExifTool() as et: metadata = et.get_metadata(file_path) result = {key:value for key, value in metadata.items() if key not in ['SourceFile', 'File:Directory']} self.file_details = result return result
def exiftool_tags(*paths): with ExifTool() as tool: tags_list = tool.get_tags_batch([], paths) tags_dict = {} for tags in tags_list: file = tags.pop('SourceFile') tags_dict[file] = tags return tags_dict
def open(self): """Creates an Exiftool process. Not recommended, use `with:` context manager instead. """ if self._exiftool is not None: raise Exception("ExifTool was already initialized.") self._exiftool = ExifTool(executable_=str(self.exiftoolpath)) self._exiftool.start()
def create_image_doc(date, flight_name, image_loc): """Add a new image to the database""" with ExifTool() as et: metadata = et.get_metadata(image_loc) image_doc = { "date": date, "flight_name": flight_name, "image_loc": image_loc, "metadata": metadata, "annotated": False, } return image_doc
def _import_original(self, path: str): d = self.components['original'] = {} d['accession_path'] = realpath(expanduser(expandvars(normpath(path)))) d['filename'] = basename(d['accession_path']) fn, ext = splitext(d['filename']) target_path = join(self.path, 'data', d['filename']) shutil.copy2(d['accession_path'], target_path) with ExifTool() as et: meta = et.get_metadata(target_path) pprint(meta) xmp = XMPFiles(file_path=target_path).get_xmp() pprint(xmp) self._update(manifests=True)
def get_metadata(filepath): """ Get Exchangeable image file format information from an image .. code:: python filepath = './IMG_001.jpg' metadata = get_metadata(filepath) """ with ExifTool() as et: metadata = et.get_metadata(filepath) return metadata
def extract_info(image_file): """Extract necessary data from metadata dictionary.""" image_file = image_file.replace("'", "") with ExifTool() as et: metadata = et.get_metadata(image_file) data = {} data["field_of_view"] = metadata["Composite:FOV"] data["camera_yaw"] = metadata["MakerNotes:CameraYaw"] data["relative_altitude"] = float(metadata["XMP:RelativeAltitude"]) data["img_lat"] = metadata["Composite:GPSLatitude"] data["img_lon"] = metadata["Composite:GPSLongitude"] data["img_width"] = metadata["File:ImageWidth"] data["img_height"] = metadata["File:ImageHeight"] return data
def setUp(self): self.image_path = Path( __file__).parent.parent / 'demo/source/APL_082158.NEF' with ExifTool() as exiftool: self.info = file_info.FileInfo(self.image_path, exiftool)
pconn = sqlite3.connect(placesDbPath) pconn.row_factory = sqlite3.Row pdb = pconn.cursor() ldb = conn.cursor() pdb.execute("SELECT COUNT(*) FROM RKPlace") numPlaces = pdb.fetchone()[0] print("Found %d places." % numPlaces) # No images? if numImages == 0: sys.exit(0) if args.exif: et = ExifTool() et.start() index = 0 copied = 0 ignored = 0 stack = [] stack_timestamp = "" places_freq = dict() # Iterate over the photos. for row in db.execute(''' SELECT m.imagePath, m.fileName, v.imageDate AS date, v.imageTimeZoneOffsetSeconds AS offset, v.uuid, v.modelId FROM RKMaster AS m INNER JOIN RKVersion AS v ON v.masterId = m.modelId
"Exiftool executable, eg '/usr/bin/exiftool'. By default, we'll assume exiftool is on the PATH" ) args = parser.parse_args() # print(args.files[0]) # print('exiftool', args.exiftool) files = args.files # if we're on windows the glob won't be pre-evaluated if len(files) == 1 and "*" in files[0]: files = glob.glob(files[0]) exiftool = 'exiftool' if args.exiftool != None: exiftool = args.exiftool with ExifTool(exiftool) as e: metadatas = e.get_tags_batch(interestingTags, files) for fileName, metadata in zip(files, metadatas): with open(fileName, 'rb') as imageFile: md5 = hashlib.md5() sha1 = hashlib.sha1() buffer = imageFile.read() md5.update(buffer) sha1.update(buffer) metadata['md5'] = md5.hexdigest() metadata['sha1'] = sha1.hexdigest() print json.dumps(metadatas)
from exiftool import ExifTool img = "DJI_0063.JPG" with ExifTool() as et: metadata = et.get_metadata(img)
def get_metadata(self,img): with ExifTool() as et: md = et.get_metadata(img) return md
def setUp(self): if not os.path.exists(TestExifManager.staging_dir): os.mkdir(TestExifManager.staging_dir) self._exiftool = ExifTool()
def __init__(self): self._exiftool = ExifTool() self._tempfiles = set()
def edit_metadata(original_files_path: str, compressed_files_path: str): # Rebuild paths original_files_path = rebuild_dirpath( original_files_path ) compressed_files_path = rebuild_dirpath( compressed_files_path ) original_files = dict() # Run through original files with os.scandir( original_files_path ) as file_list: for file in file_list: filename_full = file.name filepath = file.path filename, extension = os.path.splitext( filename_full ) # Skip iteration if wrong extension if extension.lower() [1:] not in ORIGINAL_FILE_EXTENSIONS: continue # Write to dictionary (overwrite any previous filename) original_files[filename] = filepath # Run through compressed files with os.scandir( compressed_files_path ) as file_list: for file in file_list: filename_full = file.name filepath = file.path filename, extension = os.path.splitext( filename_full ) # Skip iteration if wrong extension if extension.lower() [1:] not in COMPRESSED_FILE_EXTENSIONS: continue # Create original filename filename_original = filename.split( COMPRESSED_MARKER ) [0] # Retrieve original file extension try: filepath_original = original_files [filename_original] except FileNotFoundError: print(f'{filename_full} - {ERROR_ORIGINAL_NOT_FOUND}') continue # Retrieve original file's creation date with ExifTool() as e: metadata = e.get_metadata( filepath_original ) modify_date = metadata [0] ['File:FileModifyDate'] # Here can retrieve more metadata to later write using subprocess # Edit compressed file's EXIF creation date process = subprocess.Popen( [ EXIFTOOL_PATH, f'-AllDates={modify_date}', '-overwrite_original', filepath ], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE ) stdout, stderr = process.communicate() # Change file's modification time date_time_obj = datetime.datetime.strptime(modify_date, '%Y:%m:%d %H:%M:%S%z') mod_time = time.mktime( date_time_obj.timetuple() ) os.utime(filepath, (mod_time, mod_time)) return True