User:Brion VIBBER/exif

From MediaWiki.org
Jump to navigation Jump to search
<?php

require "./commandLine.inc";

$fieldKeys = array();
$fieldFile = fopen("exif-fields.csv", "wt");

$dbr = wfGetDB(DB_SLAVE);
$dbr->bufferResults(false);
$result = $dbr->select('image',
    array('img_name', 'img_metadata'),
    array("img_metadata != '' and img_metadata != '0'"));

foreach ($result as $row) {
    $name = $row->img_name;
    $meta = @unserialize($row->img_metadata);
    
    if (is_array($meta) && !empty($meta)) {
        $out = array($row->img_name);
        foreach($meta as $field => $val) {
            if (!is_array($val)) {
                $num = fieldKey($field);
                $out[] = "$num:$val";
            }
        }
        print csvout($out);
    }
}

function csvout($args) {
    return implode(',', array_map('csvField', $args)) . "\n";
}

function csvField($val) {
    return '"' . str_replace('"', '""', $val) . '"';
}

function fieldKey($field) {
    global $fieldKeys, $fieldFile;
    if (!isset($fieldKeys[$field])) {
        $fieldKeys[$field] = count($fieldKeys);
        fwrite($fieldFile, csvOut(array($field, $fieldKeys[$field])));
    }
    return $fieldKeys[$field];
}


<?php

require "./commandLine.inc";

/*

create table exif_fields (
  ef_id int primary key,
  ef_name varchar(255) unique key
) default charset=utf8;
create table exif_image (
  ei_id int primary key auto_increment,
  ei_name varbinary(255) unique key
) default charset=utf8;
create table exif_metadata (
  em_img int comment 'foreign key exif_image.ei_id',
  em_field int comment 'foreign key exif_fields.ef_id',
  em_val varchar(255),
  key (em_img,em_field),
  key (em_field,em_img)
) default charset=utf8;

*/

$dbw = wfGetDB(DB_MASTER);
$infile = fopen("exif-fields.csv", "rt");
while(!feof($infile)) {
    $bits = fgetcsv($infile);
    if ($bits) {
        $dbw->insert('exif_fields',
            array(
                'ef_id' => $bits[1],
                'ef_name' => $bits[0],
            ));
    }
}
fclose($infile);

$count = 0;

$infile = fopen("exif.csv", "rt");
$dbw->begin();
while(!feof($infile)) {
    $bits = fgetcsv($infile);
    if ($bits) {
        $name = array_shift($bits);
        
        $dbw->insert('exif_image',
            array('ei_name' => $name));
        
        $id = $dbw->insertId();
        $data = array();
        foreach($bits as $item) {
            list($field, $val) = explode(':', $item, 2);
            if (!isset($val)) {
                var_dump($bits); die();
            }
            $data[] = array(
                'em_img' => $id,
                'em_field' => $field,
                'em_val' => $val,
            );
        }
        if ($data) {
            $dbw->insert('exif_metadata', $data);
        }
        
        $count++;
        if($count % 1000 == 0) {
            print "$count...\n";
            $dbw->commit();
        }
    }
}
$dbw->commit();
fclose($infile);