Skip to content

Instantly share code, notes, and snippets.

@ryantxr
Created May 20, 2024 10:55
Show Gist options
  • Save ryantxr/7be34ee99868b1f73f127fc66bd31ef4 to your computer and use it in GitHub Desktop.
Save ryantxr/7be34ee99868b1f73f127fc66bd31ef4 to your computer and use it in GitHub Desktop.
Extract mage.space meta data from jpg file
<?php
/*
May 20 2024 @ryantxr
This is intended to be used on images generated by mage.space.
Some images generated on mage.space have some meta data in the
actual image. If the meta data exists in the file this program will
output it as json.
NOTE: Mage does not put the model in the meta data.
NOTE: Your mileage may vary. This code was thrown together in
a hurry and what it does is very minimal.
Usage:
php extractMageMetaData.php myfile.jpg
*/
// Define the path to the JPEG file
$imagePath = $argv[1];
// Check if the file exists
if (!file_exists($imagePath)) {
die('File not found.');
}
// Read the EXIF data from the JPEG file
$exifData = exif_read_data($imagePath, 'IFD0');
// Check if EXIF data was read successfully
if ($exifData === false) {
die('No EXIF data found.');
}
// Extract the UserComment if it exists
if (isset($exifData['COMPUTED']['UserComment'])) {
$userComment = $exifData['COMPUTED']['UserComment'];
// Decode the UserComment if it's encoded
if (substr($userComment, 0, 8) === 'UNICODE\0') {
$userComment = mb_convert_encoding(substr($userComment, 8), 'UTF-8', 'UTF-16');
} elseif (substr($userComment, 0, 8) === 'ASCII\0\0\0') {
$userComment = substr($userComment, 8);
}
// echo $userComment . PHP_EOL;
// Initialize an array to hold the parsed data
$parsedComment = [];
// Use regex to extract the segments based on the known delimiters
$pattern = '/^(.*)(Negative prompt:\s*(.*))?(Steps:\s*(\d+))?,?\s*(Seed:\s*(\d+))?,?\s*(Sampler:\s*([\w]+))?,?\s*(CFG scale:\s*([\d.]+))?$/';
// $pattern = '/^(.*)(Negative prompt:\s*(.*))?/';
$arr = ['Negative prompt', 'Steps', 'Seed', 'Sampler', 'CFG scale'];
$parsedComment['Prompt'] = findParamValue($userComment, $arr);
foreach ( $arr as $key ) {
$p = strpos($userComment, $key . ': ');
if ( $p !== false ) {
$s = substr($userComment, $p + strlen($key)+2);
$parsedComment[$key] = findParamValue($s, $arr);
} else {
$parsedComment[$key] = false;
}
}
// Convert the associative array to an object (optional)
$commentObject = (object)$parsedComment;
// Output the structured data
// echo "User Comment (Array):\n";
// print_r($parsedComment);
// echo "\nUser Comment (Object):\n";
// print_r($commentObject);
echo json_encode($commentObject, JSON_PRETTY_PRINT);
echo PHP_EOL;
} else {
echo "User Comment not found.";
}
echo "\n";
function findParamValue($s, $arr)
{
foreach ( $arr as $key ) {
$k = $key . ': ';
$p = strpos($s, $k);
if ( $p !== false ) {
return trim(substr($s, 0, $p), " ,\n\r\t\v\0");
}
}
return $s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment