memories/lib/Db/TimelineQueryFaces.php

138 lines
5.4 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace OCA\Memories\Db;
use OCP\IDBConnection;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Files\Folder;
trait TimelineQueryFaces {
protected IDBConnection $connection;
2022-10-08 06:46:08 +00:00
public function transformFaceFilter(IQueryBuilder &$query, string $userId, string $faceStr) {
2022-10-08 06:26:09 +00:00
// Get title and uid of face user
2022-10-08 06:46:08 +00:00
$faceNames = explode('/', $faceStr);
if (count($faceNames) !== 2) throw new \Exception("Invalid face query");
2022-10-08 06:26:09 +00:00
$faceUid = $faceNames[0];
$faceName = $faceNames[1];
// Get cluster ID
$sq = $query->getConnection()->getQueryBuilder();
2022-10-11 00:17:42 +00:00
$idQuery = $sq->select('id')->from('recognize_face_clusters')
->where($query->expr()->eq('user_id', $sq->createNamedParameter($faceUid)));
// If name is a number then it is an ID
$nameField = is_numeric($faceName) ? 'id' : 'title';
$idQuery->andWhere($query->expr()->eq($nameField, $sq->createNamedParameter($faceName)));
$id = $idQuery->executeQuery()->fetchOne();
2022-10-08 06:46:08 +00:00
if (!$id) throw new \Exception("Unknown person: $faceStr");
2022-10-08 06:26:09 +00:00
// Join with cluster
$query->innerJoin('m', 'recognize_face_detections', 'rfd', $query->expr()->andX(
$query->expr()->eq('rfd.file_id', 'm.fileid'),
2022-10-08 06:26:09 +00:00
$query->expr()->eq('rfd.cluster_id', $query->createNamedParameter($id)),
));
}
public function getFaces(Folder $folder) {
$query = $this->connection->getQueryBuilder();
// SELECT all face clusters
$count = $query->func()->count($query->createFunction('DISTINCT m.fileid'), 'count');
2022-10-08 06:26:09 +00:00
$query->select('rfc.id', 'rfc.user_id', 'rfc.title', $count)->from('recognize_face_clusters', 'rfc');
// WHERE there are faces with this cluster
$query->innerJoin('rfc', 'recognize_face_detections', 'rfd', $query->expr()->eq('rfc.id', 'rfd.cluster_id'));
// WHERE these items are memories indexed photos
$query->innerJoin('rfd', 'memories', 'm', $query->expr()->eq('m.fileid', 'rfd.file_id'));
// WHERE these photos are in the user's requested folder recursively
$query->innerJoin('m', 'filecache', 'f', $this->getFilecacheJoinQuery($query, $folder, true, false));
// GROUP by ID of face cluster
$query->groupBy('rfc.id');
// ORDER by number of faces in cluster
$query->orderBy($query->createFunction("rfc.title <> ''"), 'DESC');
$query->addOrderBy('count', 'DESC');
2022-10-16 23:46:37 +00:00
$query->addOrderBy('rfc.id'); // tie-breaker
// FETCH all faces
$faces = $query->executeQuery()->fetchAll();
// Post process
foreach($faces as &$row) {
2022-10-08 00:57:48 +00:00
$row['id'] = intval($row['id']);
$row["name"] = $row["title"];
unset($row["title"]);
$row["count"] = intval($row["count"]);
}
return $faces;
}
2022-10-17 17:41:58 +00:00
public function getFacePreviewDetection(Folder &$folder, int $id) {
$query = $this->connection->getQueryBuilder();
// SELECT face detections for ID
2022-10-08 02:00:55 +00:00
$query->select(
2022-10-17 17:41:58 +00:00
'rfd.file_id', // Needed to get the actual file
'rfd.x', 'rfd.y', 'rfd.width', 'rfd.height', // Image cropping
'm.w as image_width', 'm.h as image_height', // Scoring
'm.fileid', 'm.datetaken', // Just in case, for postgres
2022-10-08 02:00:55 +00:00
)->from('recognize_face_detections', 'rfd');
2022-10-17 17:41:58 +00:00
$query->where($query->expr()->eq('rfd.cluster_id', $query->createNamedParameter($id)));
// WHERE these photos are memories indexed
$query->innerJoin('rfd', 'memories', 'm', $query->expr()->eq('m.fileid', 'rfd.file_id'));
// WHERE these photos are in the user's requested folder recursively
$query->innerJoin('m', 'filecache', 'f', $this->getFilecacheJoinQuery($query, $folder, true, false));
2022-10-17 17:41:58 +00:00
// LIMIT results
$query->setMaxResults(15);
// Sort by date taken so we get recent photos
$query->orderBy('m.datetaken', 'DESC');
$query->addOrderBy('m.fileid', 'DESC'); // tie-breaker
// FETCH face detections
$previews = $query->executeQuery()->fetchAll();
if (empty($previews)) {
return null;
}
// Score the face detections
foreach ($previews as &$p) {
// Get actual pixel size of face
$iw = min(intval($p["image_width"] ?: 512), 2048);
$ih = min(intval($p["image_height"] ?: 512), 2048);
$w = floatval($p["width"]) * $iw;
$h = floatval($p["height"]) * $ih;
// Get center of face
$x = floatval($p["x"]) + floatval($p["width"]) / 2;
$y = floatval($p["y"]) + floatval($p["height"]) / 2;
// 3D normal distribution - if the face is closer to the center, it's better
$positionScore = exp(-pow($x - 0.5, 2) * 4) * exp(-pow($y - 0.5, 2) * 4);
// Root size distribution - if the face is bigger, it's better,
// but it doesn't matter beyond a certain point, especially 256px ;)
$sizeScore = pow($w * 100, 1/4) * pow($h * 100, 1/4);
// Combine scores
$p["score"] = $positionScore * $sizeScore;
}
2022-10-17 17:41:58 +00:00
// Sort previews by score descending
usort($previews, function($a, $b) {
return $b["score"] <=> $a["score"];
});
return $previews;
}
}