Compare commits

...

8 commits

Author SHA1 Message Date
martabal
920026fbc6
fix: use face thumbnail and not person face thumbnail when un-assigning face 2023-12-06 22:43:06 +01:00
martabal
8aede9e575
fix: reset re-assigning selected un-assigned face 2023-12-06 18:43:01 +01:00
martabal
5a08b7e25e
fix: reset un-assigned person 2023-12-06 16:08:40 +01:00
martabal
bbe86a4632
move the selected unassigned faces to the person side panel 2023-12-06 11:09:08 +01:00
martabal
b64dabd6f0
fix: un-assign when clicking on done 2023-12-06 01:25:49 +01:00
martabal
7e32f8b292
merge main 2023-12-06 00:11:15 +01:00
martabal
56ff252b2e
fix: e2e test 2023-12-06 00:04:49 +01:00
martabal
e23168810b
feat(web,server): unassign faces 2023-12-05 23:47:19 +01:00
33 changed files with 1190 additions and 180 deletions

View file

@ -978,10 +978,10 @@ export interface AssetResponseDto {
'ownerId': string; 'ownerId': string;
/** /**
* *
* @type {Array<PersonWithFacesResponseDto>} * @type {PeopleWithFacesResponseDto}
* @memberof AssetResponseDto * @memberof AssetResponseDto
*/ */
'people'?: Array<PersonWithFacesResponseDto>; 'people'?: PeopleWithFacesResponseDto | null;
/** /**
* *
* @type {boolean} * @type {boolean}
@ -2632,6 +2632,25 @@ export interface PeopleUpdateItem {
*/ */
'name'?: string; 'name'?: string;
} }
/**
*
* @export
* @interface PeopleWithFacesResponseDto
*/
export interface PeopleWithFacesResponseDto {
/**
*
* @type {number}
* @memberof PeopleWithFacesResponseDto
*/
'numberOfAssets': number;
/**
*
* @type {Array<PersonWithFacesResponseDto>}
* @memberof PeopleWithFacesResponseDto
*/
'people': Array<PersonWithFacesResponseDto>;
}
/** /**
* *
* @export * @export
@ -11635,6 +11654,48 @@ export const FaceApiAxiosParamCreator = function (configuration?: Configuration)
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(faceDto, localVarRequestOptions, configuration) localVarRequestOptions.data = serializeDataIfNeeded(faceDto, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
unassignFace: async (id: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'id' is not null or undefined
assertParamExists('unassignFace', 'id', id)
const localVarPath = `/face/{id}`
.replace(`{${"id"}}`, encodeURIComponent(String(id)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication cookie required
// authentication api_key required
await setApiKeyToObject(localVarHeaderParameter, "x-api-key", configuration)
// authentication bearer required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return { return {
url: toPathString(localVarUrlObj), url: toPathString(localVarUrlObj),
options: localVarRequestOptions, options: localVarRequestOptions,
@ -11671,6 +11732,16 @@ export const FaceApiFp = function(configuration?: Configuration) {
const localVarAxiosArgs = await localVarAxiosParamCreator.reassignFacesById(id, faceDto, options); const localVarAxiosArgs = await localVarAxiosParamCreator.reassignFacesById(id, faceDto, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
}, },
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async unassignFace(id: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<AssetFaceResponseDto>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.unassignFace(id, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
} }
}; };
@ -11699,6 +11770,15 @@ export const FaceApiFactory = function (configuration?: Configuration, basePath?
reassignFacesById(requestParameters: FaceApiReassignFacesByIdRequest, options?: AxiosRequestConfig): AxiosPromise<PersonResponseDto> { reassignFacesById(requestParameters: FaceApiReassignFacesByIdRequest, options?: AxiosRequestConfig): AxiosPromise<PersonResponseDto> {
return localVarFp.reassignFacesById(requestParameters.id, requestParameters.faceDto, options).then((request) => request(axios, basePath)); return localVarFp.reassignFacesById(requestParameters.id, requestParameters.faceDto, options).then((request) => request(axios, basePath));
}, },
/**
*
* @param {FaceApiUnassignFaceRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
unassignFace(requestParameters: FaceApiUnassignFaceRequest, options?: AxiosRequestConfig): AxiosPromise<AssetFaceResponseDto> {
return localVarFp.unassignFace(requestParameters.id, options).then((request) => request(axios, basePath));
},
}; };
}; };
@ -11737,6 +11817,20 @@ export interface FaceApiReassignFacesByIdRequest {
readonly faceDto: FaceDto readonly faceDto: FaceDto
} }
/**
* Request parameters for unassignFace operation in FaceApi.
* @export
* @interface FaceApiUnassignFaceRequest
*/
export interface FaceApiUnassignFaceRequest {
/**
*
* @type {string}
* @memberof FaceApiUnassignFace
*/
readonly id: string
}
/** /**
* FaceApi - object-oriented interface * FaceApi - object-oriented interface
* @export * @export
@ -11765,6 +11859,17 @@ export class FaceApi extends BaseAPI {
public reassignFacesById(requestParameters: FaceApiReassignFacesByIdRequest, options?: AxiosRequestConfig) { public reassignFacesById(requestParameters: FaceApiReassignFacesByIdRequest, options?: AxiosRequestConfig) {
return FaceApiFp(this.configuration).reassignFacesById(requestParameters.id, requestParameters.faceDto, options).then((request) => request(this.axios, this.basePath)); return FaceApiFp(this.configuration).reassignFacesById(requestParameters.id, requestParameters.faceDto, options).then((request) => request(this.axios, this.basePath));
} }
/**
*
* @param {FaceApiUnassignFaceRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FaceApi
*/
public unassignFace(requestParameters: FaceApiUnassignFaceRequest, options?: AxiosRequestConfig) {
return FaceApiFp(this.configuration).unassignFace(requestParameters.id, options).then((request) => request(this.axios, this.basePath));
}
} }

View file

@ -102,6 +102,7 @@ doc/PathType.md
doc/PeopleResponseDto.md doc/PeopleResponseDto.md
doc/PeopleUpdateDto.md doc/PeopleUpdateDto.md
doc/PeopleUpdateItem.md doc/PeopleUpdateItem.md
doc/PeopleWithFacesResponseDto.md
doc/PersonApi.md doc/PersonApi.md
doc/PersonResponseDto.md doc/PersonResponseDto.md
doc/PersonStatisticsResponseDto.md doc/PersonStatisticsResponseDto.md
@ -292,6 +293,7 @@ lib/model/path_type.dart
lib/model/people_response_dto.dart lib/model/people_response_dto.dart
lib/model/people_update_dto.dart lib/model/people_update_dto.dart
lib/model/people_update_item.dart lib/model/people_update_item.dart
lib/model/people_with_faces_response_dto.dart
lib/model/person_response_dto.dart lib/model/person_response_dto.dart
lib/model/person_statistics_response_dto.dart lib/model/person_statistics_response_dto.dart
lib/model/person_update_dto.dart lib/model/person_update_dto.dart
@ -459,6 +461,7 @@ test/path_type_test.dart
test/people_response_dto_test.dart test/people_response_dto_test.dart
test/people_update_dto_test.dart test/people_update_dto_test.dart
test/people_update_item_test.dart test/people_update_item_test.dart
test/people_with_faces_response_dto_test.dart
test/person_api_test.dart test/person_api_test.dart
test/person_response_dto_test.dart test/person_response_dto_test.dart
test/person_statistics_response_dto_test.dart test/person_statistics_response_dto_test.dart

View file

@ -135,6 +135,7 @@ Class | Method | HTTP request | Description
*AuthenticationApi* | [**validateAccessToken**](doc//AuthenticationApi.md#validateaccesstoken) | **POST** /auth/validateToken | *AuthenticationApi* | [**validateAccessToken**](doc//AuthenticationApi.md#validateaccesstoken) | **POST** /auth/validateToken |
*FaceApi* | [**getFaces**](doc//FaceApi.md#getfaces) | **GET** /face | *FaceApi* | [**getFaces**](doc//FaceApi.md#getfaces) | **GET** /face |
*FaceApi* | [**reassignFacesById**](doc//FaceApi.md#reassignfacesbyid) | **PUT** /face/{id} | *FaceApi* | [**reassignFacesById**](doc//FaceApi.md#reassignfacesbyid) | **PUT** /face/{id} |
*FaceApi* | [**unassignFace**](doc//FaceApi.md#unassignface) | **DELETE** /face/{id} |
*JobApi* | [**getAllJobsStatus**](doc//JobApi.md#getalljobsstatus) | **GET** /jobs | *JobApi* | [**getAllJobsStatus**](doc//JobApi.md#getalljobsstatus) | **GET** /jobs |
*JobApi* | [**sendJobCommand**](doc//JobApi.md#sendjobcommand) | **PUT** /jobs/{id} | *JobApi* | [**sendJobCommand**](doc//JobApi.md#sendjobcommand) | **PUT** /jobs/{id} |
*LibraryApi* | [**createLibrary**](doc//LibraryApi.md#createlibrary) | **POST** /library | *LibraryApi* | [**createLibrary**](doc//LibraryApi.md#createlibrary) | **POST** /library |
@ -299,6 +300,7 @@ Class | Method | HTTP request | Description
- [PeopleResponseDto](doc//PeopleResponseDto.md) - [PeopleResponseDto](doc//PeopleResponseDto.md)
- [PeopleUpdateDto](doc//PeopleUpdateDto.md) - [PeopleUpdateDto](doc//PeopleUpdateDto.md)
- [PeopleUpdateItem](doc//PeopleUpdateItem.md) - [PeopleUpdateItem](doc//PeopleUpdateItem.md)
- [PeopleWithFacesResponseDto](doc//PeopleWithFacesResponseDto.md)
- [PersonResponseDto](doc//PersonResponseDto.md) - [PersonResponseDto](doc//PersonResponseDto.md)
- [PersonStatisticsResponseDto](doc//PersonStatisticsResponseDto.md) - [PersonStatisticsResponseDto](doc//PersonStatisticsResponseDto.md)
- [PersonUpdateDto](doc//PersonUpdateDto.md) - [PersonUpdateDto](doc//PersonUpdateDto.md)

View file

@ -30,7 +30,7 @@ Name | Type | Description | Notes
**originalPath** | **String** | | **originalPath** | **String** | |
**owner** | [**UserResponseDto**](UserResponseDto.md) | | [optional] **owner** | [**UserResponseDto**](UserResponseDto.md) | | [optional]
**ownerId** | **String** | | **ownerId** | **String** | |
**people** | [**List<PersonWithFacesResponseDto>**](PersonWithFacesResponseDto.md) | | [optional] [default to const []] **people** | [**PeopleWithFacesResponseDto**](PeopleWithFacesResponseDto.md) | | [optional]
**resized** | **bool** | | **resized** | **bool** | |
**smartInfo** | [**SmartInfoResponseDto**](SmartInfoResponseDto.md) | | [optional] **smartInfo** | [**SmartInfoResponseDto**](SmartInfoResponseDto.md) | | [optional]
**stack** | [**List<AssetResponseDto>**](AssetResponseDto.md) | | [optional] [default to const []] **stack** | [**List<AssetResponseDto>**](AssetResponseDto.md) | | [optional] [default to const []]

View file

@ -11,6 +11,7 @@ Method | HTTP request | Description
------------- | ------------- | ------------- ------------- | ------------- | -------------
[**getFaces**](FaceApi.md#getfaces) | **GET** /face | [**getFaces**](FaceApi.md#getfaces) | **GET** /face |
[**reassignFacesById**](FaceApi.md#reassignfacesbyid) | **PUT** /face/{id} | [**reassignFacesById**](FaceApi.md#reassignfacesbyid) | **PUT** /face/{id} |
[**unassignFace**](FaceApi.md#unassignface) | **DELETE** /face/{id} |
# **getFaces** # **getFaces**
@ -125,3 +126,58 @@ Name | Type | Description | Notes
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **unassignFace**
> AssetFaceResponseDto unassignFace(id)
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: cookie
//defaultApiClient.getAuthentication<ApiKeyAuth>('cookie').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('cookie').apiKeyPrefix = 'Bearer';
// TODO Configure API key authorization: api_key
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key').apiKeyPrefix = 'Bearer';
// TODO Configure HTTP Bearer authorization: bearer
// Case 1. Use String Token
//defaultApiClient.getAuthentication<HttpBearerAuth>('bearer').setAccessToken('YOUR_ACCESS_TOKEN');
// Case 2. Use Function which generate token.
// String yourTokenGeneratorFunction() { ... }
//defaultApiClient.getAuthentication<HttpBearerAuth>('bearer').setAccessToken(yourTokenGeneratorFunction);
final api_instance = FaceApi();
final id = 38400000-8cf0-11bd-b23e-10b96e4ef00d; // String |
try {
final result = api_instance.unassignFace(id);
print(result);
} catch (e) {
print('Exception when calling FaceApi->unassignFace: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **String**| |
### Return type
[**AssetFaceResponseDto**](AssetFaceResponseDto.md)
### Authorization
[cookie](../README.md#cookie), [api_key](../README.md#api_key), [bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View file

@ -0,0 +1,16 @@
# openapi.model.PeopleWithFacesResponseDto
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**numberOfAssets** | **int** | |
**people** | [**List<PersonWithFacesResponseDto>**](PersonWithFacesResponseDto.md) | | [default to const []]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -135,6 +135,7 @@ part 'model/path_type.dart';
part 'model/people_response_dto.dart'; part 'model/people_response_dto.dart';
part 'model/people_update_dto.dart'; part 'model/people_update_dto.dart';
part 'model/people_update_item.dart'; part 'model/people_update_item.dart';
part 'model/people_with_faces_response_dto.dart';
part 'model/person_response_dto.dart'; part 'model/person_response_dto.dart';
part 'model/person_statistics_response_dto.dart'; part 'model/person_statistics_response_dto.dart';
part 'model/person_update_dto.dart'; part 'model/person_update_dto.dart';

View file

@ -119,4 +119,52 @@ class FaceApi {
} }
return null; return null;
} }
/// Performs an HTTP 'DELETE /face/{id}' operation and returns the [Response].
/// Parameters:
///
/// * [String] id (required):
Future<Response> unassignFaceWithHttpInfo(String id,) async {
// ignore: prefer_const_declarations
final path = r'/face/{id}'
.replaceAll('{id}', id);
// ignore: prefer_final_locals
Object? postBody;
final queryParams = <QueryParam>[];
final headerParams = <String, String>{};
final formParams = <String, String>{};
const contentTypes = <String>[];
return apiClient.invokeAPI(
path,
'DELETE',
queryParams,
postBody,
headerParams,
formParams,
contentTypes.isEmpty ? null : contentTypes.first,
);
}
/// Parameters:
///
/// * [String] id (required):
Future<AssetFaceResponseDto?> unassignFace(String id,) async {
final response = await unassignFaceWithHttpInfo(id,);
if (response.statusCode >= HttpStatus.badRequest) {
throw ApiException(response.statusCode, await _decodeBodyBytes(response));
}
// When a remote server returns no body with a status of 204, we shall not decode it.
// At the time of writing this, `dart:convert` will throw an "Unexpected end of input"
// FormatException when trying to decode an empty string.
if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) {
return await apiClient.deserializeAsync(await _decodeBodyBytes(response), 'AssetFaceResponseDto',) as AssetFaceResponseDto;
}
return null;
}
} }

View file

@ -357,6 +357,8 @@ class ApiClient {
return PeopleUpdateDto.fromJson(value); return PeopleUpdateDto.fromJson(value);
case 'PeopleUpdateItem': case 'PeopleUpdateItem':
return PeopleUpdateItem.fromJson(value); return PeopleUpdateItem.fromJson(value);
case 'PeopleWithFacesResponseDto':
return PeopleWithFacesResponseDto.fromJson(value);
case 'PersonResponseDto': case 'PersonResponseDto':
return PersonResponseDto.fromJson(value); return PersonResponseDto.fromJson(value);
case 'PersonStatisticsResponseDto': case 'PersonStatisticsResponseDto':

View file

@ -35,7 +35,7 @@ class AssetResponseDto {
required this.originalPath, required this.originalPath,
this.owner, this.owner,
required this.ownerId, required this.ownerId,
this.people = const [], this.people,
required this.resized, required this.resized,
this.smartInfo, this.smartInfo,
this.stack = const [], this.stack = const [],
@ -104,7 +104,7 @@ class AssetResponseDto {
String ownerId; String ownerId;
List<PersonWithFacesResponseDto> people; PeopleWithFacesResponseDto? people;
bool resized; bool resized;
@ -190,7 +190,7 @@ class AssetResponseDto {
(originalPath.hashCode) + (originalPath.hashCode) +
(owner == null ? 0 : owner!.hashCode) + (owner == null ? 0 : owner!.hashCode) +
(ownerId.hashCode) + (ownerId.hashCode) +
(people.hashCode) + (people == null ? 0 : people!.hashCode) +
(resized.hashCode) + (resized.hashCode) +
(smartInfo == null ? 0 : smartInfo!.hashCode) + (smartInfo == null ? 0 : smartInfo!.hashCode) +
(stack.hashCode) + (stack.hashCode) +
@ -240,7 +240,11 @@ class AssetResponseDto {
// json[r'owner'] = null; // json[r'owner'] = null;
} }
json[r'ownerId'] = this.ownerId; json[r'ownerId'] = this.ownerId;
if (this.people != null) {
json[r'people'] = this.people; json[r'people'] = this.people;
} else {
// json[r'people'] = null;
}
json[r'resized'] = this.resized; json[r'resized'] = this.resized;
if (this.smartInfo != null) { if (this.smartInfo != null) {
json[r'smartInfo'] = this.smartInfo; json[r'smartInfo'] = this.smartInfo;
@ -299,7 +303,7 @@ class AssetResponseDto {
originalPath: mapValueOfType<String>(json, r'originalPath')!, originalPath: mapValueOfType<String>(json, r'originalPath')!,
owner: UserResponseDto.fromJson(json[r'owner']), owner: UserResponseDto.fromJson(json[r'owner']),
ownerId: mapValueOfType<String>(json, r'ownerId')!, ownerId: mapValueOfType<String>(json, r'ownerId')!,
people: PersonWithFacesResponseDto.listFromJson(json[r'people']), people: PeopleWithFacesResponseDto.fromJson(json[r'people']),
resized: mapValueOfType<bool>(json, r'resized')!, resized: mapValueOfType<bool>(json, r'resized')!,
smartInfo: SmartInfoResponseDto.fromJson(json[r'smartInfo']), smartInfo: SmartInfoResponseDto.fromJson(json[r'smartInfo']),
stack: AssetResponseDto.listFromJson(json[r'stack']), stack: AssetResponseDto.listFromJson(json[r'stack']),

View file

@ -0,0 +1,106 @@
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.12
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
part of openapi.api;
class PeopleWithFacesResponseDto {
/// Returns a new [PeopleWithFacesResponseDto] instance.
PeopleWithFacesResponseDto({
required this.numberOfAssets,
this.people = const [],
});
int numberOfAssets;
List<PersonWithFacesResponseDto> people;
@override
bool operator ==(Object other) => identical(this, other) || other is PeopleWithFacesResponseDto &&
other.numberOfAssets == numberOfAssets &&
other.people == people;
@override
int get hashCode =>
// ignore: unnecessary_parenthesis
(numberOfAssets.hashCode) +
(people.hashCode);
@override
String toString() => 'PeopleWithFacesResponseDto[numberOfAssets=$numberOfAssets, people=$people]';
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
json[r'numberOfAssets'] = this.numberOfAssets;
json[r'people'] = this.people;
return json;
}
/// Returns a new [PeopleWithFacesResponseDto] instance and imports its values from
/// [value] if it's a [Map], null otherwise.
// ignore: prefer_constructors_over_static_methods
static PeopleWithFacesResponseDto? fromJson(dynamic value) {
if (value is Map) {
final json = value.cast<String, dynamic>();
return PeopleWithFacesResponseDto(
numberOfAssets: mapValueOfType<int>(json, r'numberOfAssets')!,
people: PersonWithFacesResponseDto.listFromJson(json[r'people']),
);
}
return null;
}
static List<PeopleWithFacesResponseDto> listFromJson(dynamic json, {bool growable = false,}) {
final result = <PeopleWithFacesResponseDto>[];
if (json is List && json.isNotEmpty) {
for (final row in json) {
final value = PeopleWithFacesResponseDto.fromJson(row);
if (value != null) {
result.add(value);
}
}
}
return result.toList(growable: growable);
}
static Map<String, PeopleWithFacesResponseDto> mapFromJson(dynamic json) {
final map = <String, PeopleWithFacesResponseDto>{};
if (json is Map && json.isNotEmpty) {
json = json.cast<String, dynamic>(); // ignore: parameter_assignments
for (final entry in json.entries) {
final value = PeopleWithFacesResponseDto.fromJson(entry.value);
if (value != null) {
map[entry.key] = value;
}
}
}
return map;
}
// maps a json object with a list of PeopleWithFacesResponseDto-objects as value to a dart map
static Map<String, List<PeopleWithFacesResponseDto>> mapListFromJson(dynamic json, {bool growable = false,}) {
final map = <String, List<PeopleWithFacesResponseDto>>{};
if (json is Map && json.isNotEmpty) {
// ignore: parameter_assignments
json = json.cast<String, dynamic>();
for (final entry in json.entries) {
map[entry.key] = PeopleWithFacesResponseDto.listFromJson(entry.value, growable: growable,);
}
}
return map;
}
/// The list of required keys that must be present in a JSON.
static const requiredKeys = <String>{
'numberOfAssets',
'people',
};
}

View file

@ -127,7 +127,7 @@ void main() {
// TODO // TODO
}); });
// List<PersonWithFacesResponseDto> people (default value: const []) // PeopleWithFacesResponseDto people
test('to test the property `people`', () async { test('to test the property `people`', () async {
// TODO // TODO
}); });

View file

@ -27,5 +27,10 @@ void main() {
// TODO // TODO
}); });
//Future<AssetFaceResponseDto> unassignFace(String id) async
test('test unassignFace', () async {
// TODO
});
}); });
} }

View file

@ -0,0 +1,32 @@
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.12
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
import 'package:openapi/api.dart';
import 'package:test/test.dart';
// tests for PeopleWithFacesResponseDto
void main() {
// final instance = PeopleWithFacesResponseDto();
group('test PeopleWithFacesResponseDto', () {
// int numberOfAssets
test('to test the property `numberOfAssets`', () async {
// TODO
});
// List<PersonWithFacesResponseDto> people (default value: const [])
test('to test the property `people`', () async {
// TODO
});
});
}

View file

@ -3266,6 +3266,46 @@
} }
}, },
"/face/{id}": { "/face/{id}": {
"delete": {
"operationId": "unassignFace",
"parameters": [
{
"name": "id",
"required": true,
"in": "path",
"schema": {
"format": "uuid",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AssetFaceResponseDto"
}
}
},
"description": ""
}
},
"security": [
{
"bearer": []
},
{
"cookie": []
},
{
"api_key": []
}
],
"tags": [
"Face"
]
},
"put": { "put": {
"operationId": "reassignFacesById", "operationId": "reassignFacesById",
"parameters": [ "parameters": [
@ -7012,10 +7052,12 @@
"type": "string" "type": "string"
}, },
"people": { "people": {
"items": { "allOf": [
"$ref": "#/components/schemas/PersonWithFacesResponseDto" {
}, "$ref": "#/components/schemas/PeopleWithFacesResponseDto"
"type": "array" }
],
"nullable": true
}, },
"resized": { "resized": {
"type": "boolean" "type": "boolean"
@ -8390,6 +8432,24 @@
], ],
"type": "object" "type": "object"
}, },
"PeopleWithFacesResponseDto": {
"properties": {
"numberOfAssets": {
"type": "integer"
},
"people": {
"items": {
"$ref": "#/components/schemas/PersonWithFacesResponseDto"
},
"type": "array"
}
},
"required": [
"numberOfAssets",
"people"
],
"type": "object"
},
"PersonResponseDto": { "PersonResponseDto": {
"properties": { "properties": {
"birthDate": { "birthDate": {

View file

@ -1,6 +1,6 @@
import { AssetEntity, AssetFaceEntity, AssetType } from '@app/infra/entities'; import { AssetEntity, AssetFaceEntity, AssetType } from '@app/infra/entities';
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { PersonWithFacesResponseDto } from '../../person/person.dto'; import { PeopleWithFacesResponseDto, PersonWithFacesResponseDto } from '../../person/person.dto';
import { TagResponseDto, mapTag } from '../../tag'; import { TagResponseDto, mapTag } from '../../tag';
import { UserResponseDto, mapUser } from '../../user/response-dto/user-response.dto'; import { UserResponseDto, mapUser } from '../../user/response-dto/user-response.dto';
import { ExifResponseDto, mapExif } from './exif-response.dto'; import { ExifResponseDto, mapExif } from './exif-response.dto';
@ -39,7 +39,7 @@ export class AssetResponseDto extends SanitizedAssetResponseDto {
exifInfo?: ExifResponseDto; exifInfo?: ExifResponseDto;
smartInfo?: SmartInfoResponseDto; smartInfo?: SmartInfoResponseDto;
tags?: TagResponseDto[]; tags?: TagResponseDto[];
people?: PersonWithFacesResponseDto[]; people?: PeopleWithFacesResponseDto | null;
/**base64 encoded sha1 hash */ /**base64 encoded sha1 hash */
checksum!: string; checksum!: string;
stackParentId?: string | null; stackParentId?: string | null;
@ -53,7 +53,7 @@ export type AssetMapOptions = {
withStack?: boolean; withStack?: boolean;
}; };
const peopleWithFaces = (faces: AssetFaceEntity[]): PersonWithFacesResponseDto[] => { const peopleWithFaces = (faces: AssetFaceEntity[]): PeopleWithFacesResponseDto => {
const result: PersonWithFacesResponseDto[] = []; const result: PersonWithFacesResponseDto[] = [];
if (faces) { if (faces) {
faces.forEach((face) => { faces.forEach((face) => {
@ -68,7 +68,7 @@ const peopleWithFaces = (faces: AssetFaceEntity[]): PersonWithFacesResponseDto[]
}); });
} }
return result; return { people: result, numberOfAssets: faces.length };
}; };
export function mapAsset(entity: AssetEntity, options: AssetMapOptions = {}): AssetResponseDto { export function mapAsset(entity: AssetEntity, options: AssetMapOptions = {}): AssetResponseDto {
@ -114,7 +114,7 @@ export function mapAsset(entity: AssetEntity, options: AssetMapOptions = {}): As
smartInfo: entity.smartInfo ? mapSmartInfo(entity.smartInfo) : undefined, smartInfo: entity.smartInfo ? mapSmartInfo(entity.smartInfo) : undefined,
livePhotoVideoId: entity.livePhotoVideoId, livePhotoVideoId: entity.livePhotoVideoId,
tags: entity.tags?.map(mapTag), tags: entity.tags?.map(mapTag),
people: peopleWithFaces(entity.faces), people: entity.faces ? peopleWithFaces(entity.faces) : null,
checksum: entity.checksum.toString('base64'), checksum: entity.checksum.toString('base64'),
stackParentId: entity.stackParentId, stackParentId: entity.stackParentId,
stack: withStack ? entity.stack?.map((a) => mapAsset(a, { stripMetadata })) ?? undefined : undefined, stack: withStack ? entity.stack?.map((a) => mapAsset(a, { stripMetadata })) ?? undefined : undefined,

View file

@ -78,6 +78,12 @@ export class PersonWithFacesResponseDto extends PersonResponseDto {
faces!: AssetFaceWithoutPersonResponseDto[]; faces!: AssetFaceWithoutPersonResponseDto[];
} }
export class PeopleWithFacesResponseDto {
people!: PersonWithFacesResponseDto[];
@ApiProperty({ type: 'integer' })
numberOfAssets!: number;
}
export class AssetFaceWithoutPersonResponseDto { export class AssetFaceWithoutPersonResponseDto {
@ValidateUUID() @ValidateUUID()
id!: string; id!: string;

View file

@ -491,6 +491,21 @@ describe(PersonService.name, () => {
}); });
}); });
describe('unassignFace', () => {
it('should unassign a face', async () => {
personMock.getFaceById.mockResolvedValue(faceStub.face1);
accessMock.person.checkOwnerAccess.mockResolvedValue(new Set([personStub.noName.id]));
accessMock.person.hasFaceOwnerAccess.mockResolvedValue(new Set([faceStub.face1.id]));
personMock.reassignFace.mockResolvedValue(1);
personMock.getRandomFace.mockResolvedValue(null);
personMock.getFaceById.mockResolvedValue(faceStub.unassignedFace);
await expect(sut.unassignFace(authStub.admin, faceStub.face1.id)).resolves.toStrictEqual(
mapFaces(faceStub.unassignedFace, authStub.admin),
);
});
});
describe('handlePersonDelete', () => { describe('handlePersonDelete', () => {
it('should stop if a person has not be found', async () => { it('should stop if a person has not be found', async () => {
personMock.getById.mockResolvedValue(null); personMock.getById.mockResolvedValue(null);

View file

@ -117,6 +117,21 @@ export class PersonService {
return result; return result;
} }
async unassignFace(authUser: AuthUserDto, id: string): Promise<AssetFaceResponseDto> {
let face = await this.repository.getFaceById(id);
await this.access.requirePermission(authUser, Permission.PERSON_CREATE, face.id);
if (face.personId) {
await this.access.requirePermission(authUser, Permission.PERSON_WRITE, face.personId);
}
await this.repository.reassignFace(face.id, null);
if (face.person && face.person.faceAssetId === face.id) {
await this.createNewFeaturePhoto([face.person.id]);
}
face = await this.repository.getFaceById(id);
return mapFaces(face, authUser);
}
async reassignFacesById(authUser: AuthUserDto, personId: string, dto: FaceDto): Promise<PersonResponseDto> { async reassignFacesById(authUser: AuthUserDto, personId: string, dto: FaceDto): Promise<PersonResponseDto> {
await this.access.requirePermission(authUser, Permission.PERSON_WRITE, personId); await this.access.requirePermission(authUser, Permission.PERSON_WRITE, personId);

View file

@ -18,7 +18,7 @@ export interface AssetFaceId {
export interface UpdateFacesData { export interface UpdateFacesData {
oldPersonId: string; oldPersonId: string;
newPersonId: string; newPersonId: string | null;
} }
export interface PersonStatistics { export interface PersonStatistics {
@ -49,7 +49,7 @@ export interface IPersonRepository {
getRandomFace(personId: string): Promise<AssetFaceEntity | null>; getRandomFace(personId: string): Promise<AssetFaceEntity | null>;
createFace(entity: Partial<AssetFaceEntity>): Promise<AssetFaceEntity>; createFace(entity: Partial<AssetFaceEntity>): Promise<AssetFaceEntity>;
getFaces(assetId: string): Promise<AssetFaceEntity[]>; getFaces(assetId: string): Promise<AssetFaceEntity[]>;
reassignFace(assetFaceId: string, newPersonId: string): Promise<number>; reassignFace(assetFaceId: string, newPersonId: string | null): Promise<number>;
getFaceById(id: string): Promise<AssetFaceEntity>; getFaceById(id: string): Promise<AssetFaceEntity>;
getFaceByIdWithAssets(id: string): Promise<AssetFaceEntity | null>; getFaceByIdWithAssets(id: string): Promise<AssetFaceEntity | null>;
} }

View file

@ -133,7 +133,7 @@ export class AssetService {
const data = mapAsset(asset, { withStack: true }); const data = mapAsset(asset, { withStack: true });
if (data.ownerId !== authUser.id) { if (data.ownerId !== authUser.id) {
data.people = []; data.people = null;
} }
if (authUser.isPublicUser) { if (authUser.isPublicUser) {

View file

@ -1,5 +1,5 @@
import { AssetFaceResponseDto, AuthUserDto, FaceDto, PersonResponseDto, PersonService } from '@app/domain'; import { AssetFaceResponseDto, AuthUserDto, FaceDto, PersonResponseDto, PersonService } from '@app/domain';
import { Body, Controller, Get, Param, Put, Query } from '@nestjs/common'; import { Body, Controller, Delete, Get, Param, Put, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger'; import { ApiTags } from '@nestjs/swagger';
import { AuthUser, Authenticated } from '../app.guard'; import { AuthUser, Authenticated } from '../app.guard';
import { UseValidation } from '../app.utils'; import { UseValidation } from '../app.utils';
@ -25,4 +25,9 @@ export class FaceController {
): Promise<PersonResponseDto> { ): Promise<PersonResponseDto> {
return this.service.reassignFacesById(authUser, id, dto); return this.service.reassignFacesById(authUser, id, dto);
} }
@Delete(':id')
unassignFace(@AuthUser() authUser: AuthUserDto, @Param() { id }: UUIDParamDto): Promise<AssetFaceResponseDto> {
return this.service.unassignFace(authUser, id);
}
} }

View file

@ -774,6 +774,8 @@ describe(`${AssetController.name} (e2e)`, () => {
expect(body).toMatchObject({ expect(body).toMatchObject({
id: asset1.id, id: asset1.id,
isFavorite: true, isFavorite: true,
people: {
numberOfAssets: 1,
people: [ people: [
{ {
birthDate: null, birthDate: null,
@ -783,6 +785,7 @@ describe(`${AssetController.name} (e2e)`, () => {
thumbnailPath: '', thumbnailPath: '',
}, },
], ],
},
}); });
}); });
}); });

View file

@ -17,6 +17,20 @@ export const faceStub = {
imageHeight: 1024, imageHeight: 1024,
imageWidth: 1024, imageWidth: 1024,
}), }),
unassignedFace: Object.freeze<AssetFaceEntity>({
id: 'assetFaceId',
assetId: assetStub.image.id,
asset: assetStub.image,
personId: null,
person: null,
embedding: [1, 2, 3, 4],
boundingBoxX1: 0,
boundingBoxY1: 0,
boundingBoxX2: 1,
boundingBoxY2: 1,
imageHeight: 1024,
imageWidth: 1024,
}),
primaryFace1: Object.freeze<AssetFaceEntity>({ primaryFace1: Object.freeze<AssetFaceEntity>({
id: 'assetFaceId', id: 'assetFaceId',
assetId: assetStub.image.id, assetId: assetStub.image.id,

View file

@ -67,7 +67,7 @@ const assetResponse: AssetResponseDto = {
exifInfo: assetInfo, exifInfo: assetInfo,
livePhotoVideoId: null, livePhotoVideoId: null,
tags: [], tags: [],
people: [], people: null,
checksum: 'ZmlsZSBoYXNo', checksum: 'ZmlsZSBoYXNo',
isTrashed: false, isTrashed: false,
libraryId: 'library-id', libraryId: 'library-id',

View file

@ -978,10 +978,10 @@ export interface AssetResponseDto {
'ownerId': string; 'ownerId': string;
/** /**
* *
* @type {Array<PersonWithFacesResponseDto>} * @type {PeopleWithFacesResponseDto}
* @memberof AssetResponseDto * @memberof AssetResponseDto
*/ */
'people'?: Array<PersonWithFacesResponseDto>; 'people'?: PeopleWithFacesResponseDto | null;
/** /**
* *
* @type {boolean} * @type {boolean}
@ -2632,6 +2632,25 @@ export interface PeopleUpdateItem {
*/ */
'name'?: string; 'name'?: string;
} }
/**
*
* @export
* @interface PeopleWithFacesResponseDto
*/
export interface PeopleWithFacesResponseDto {
/**
*
* @type {number}
* @memberof PeopleWithFacesResponseDto
*/
'numberOfAssets': number;
/**
*
* @type {Array<PersonWithFacesResponseDto>}
* @memberof PeopleWithFacesResponseDto
*/
'people': Array<PersonWithFacesResponseDto>;
}
/** /**
* *
* @export * @export
@ -11635,6 +11654,48 @@ export const FaceApiAxiosParamCreator = function (configuration?: Configuration)
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(faceDto, localVarRequestOptions, configuration) localVarRequestOptions.data = serializeDataIfNeeded(faceDto, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
unassignFace: async (id: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'id' is not null or undefined
assertParamExists('unassignFace', 'id', id)
const localVarPath = `/face/{id}`
.replace(`{${"id"}}`, encodeURIComponent(String(id)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication cookie required
// authentication api_key required
await setApiKeyToObject(localVarHeaderParameter, "x-api-key", configuration)
// authentication bearer required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return { return {
url: toPathString(localVarUrlObj), url: toPathString(localVarUrlObj),
options: localVarRequestOptions, options: localVarRequestOptions,
@ -11671,6 +11732,16 @@ export const FaceApiFp = function(configuration?: Configuration) {
const localVarAxiosArgs = await localVarAxiosParamCreator.reassignFacesById(id, faceDto, options); const localVarAxiosArgs = await localVarAxiosParamCreator.reassignFacesById(id, faceDto, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
}, },
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async unassignFace(id: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<AssetFaceResponseDto>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.unassignFace(id, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
} }
}; };
@ -11699,6 +11770,15 @@ export const FaceApiFactory = function (configuration?: Configuration, basePath?
reassignFacesById(requestParameters: FaceApiReassignFacesByIdRequest, options?: AxiosRequestConfig): AxiosPromise<PersonResponseDto> { reassignFacesById(requestParameters: FaceApiReassignFacesByIdRequest, options?: AxiosRequestConfig): AxiosPromise<PersonResponseDto> {
return localVarFp.reassignFacesById(requestParameters.id, requestParameters.faceDto, options).then((request) => request(axios, basePath)); return localVarFp.reassignFacesById(requestParameters.id, requestParameters.faceDto, options).then((request) => request(axios, basePath));
}, },
/**
*
* @param {FaceApiUnassignFaceRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
unassignFace(requestParameters: FaceApiUnassignFaceRequest, options?: AxiosRequestConfig): AxiosPromise<AssetFaceResponseDto> {
return localVarFp.unassignFace(requestParameters.id, options).then((request) => request(axios, basePath));
},
}; };
}; };
@ -11737,6 +11817,20 @@ export interface FaceApiReassignFacesByIdRequest {
readonly faceDto: FaceDto readonly faceDto: FaceDto
} }
/**
* Request parameters for unassignFace operation in FaceApi.
* @export
* @interface FaceApiUnassignFaceRequest
*/
export interface FaceApiUnassignFaceRequest {
/**
*
* @type {string}
* @memberof FaceApiUnassignFace
*/
readonly id: string
}
/** /**
* FaceApi - object-oriented interface * FaceApi - object-oriented interface
* @export * @export
@ -11765,6 +11859,17 @@ export class FaceApi extends BaseAPI {
public reassignFacesById(requestParameters: FaceApiReassignFacesByIdRequest, options?: AxiosRequestConfig) { public reassignFacesById(requestParameters: FaceApiReassignFacesByIdRequest, options?: AxiosRequestConfig) {
return FaceApiFp(this.configuration).reassignFacesById(requestParameters.id, requestParameters.faceDto, options).then((request) => request(this.axios, this.basePath)); return FaceApiFp(this.configuration).reassignFacesById(requestParameters.id, requestParameters.faceDto, options).then((request) => request(this.axios, this.basePath));
} }
/**
*
* @param {FaceApiUnassignFaceRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FaceApi
*/
public unassignFace(requestParameters: FaceApiUnassignFaceRequest, options?: AxiosRequestConfig) {
return FaceApiFp(this.configuration).unassignFace(requestParameters.id, options).then((request) => request(this.axios, this.basePath));
}
} }

View file

@ -59,7 +59,7 @@
// Get latest description from server // Get latest description from server
if (asset.id && !api.isSharedLink) { if (asset.id && !api.isSharedLink) {
api.assetApi.getAssetById({ id: asset.id }).then((res) => { api.assetApi.getAssetById({ id: asset.id }).then((res) => {
people = res.data?.people || []; people = res.data?.people?.people || [];
textarea.value = res.data?.exifInfo?.description || ''; textarea.value = res.data?.exifInfo?.description || '';
}); });
} }
@ -74,7 +74,8 @@
} }
})(); })();
$: people = asset.people || []; $: people = asset.people?.people || [];
$: numberOfFaces = asset.people?.numberOfAssets || 0;
$: showingHiddenPeople = false; $: showingHiddenPeople = false;
const unsubscribe = websocketStore.onAssetUpdate.subscribe((assetUpdate) => { const unsubscribe = websocketStore.onAssetUpdate.subscribe((assetUpdate) => {
@ -101,7 +102,8 @@
const handleRefreshPeople = async () => { const handleRefreshPeople = async () => {
await api.assetApi.getAssetById({ id: asset.id }).then((res) => { await api.assetApi.getAssetById({ id: asset.id }).then((res) => {
people = res.data?.people || []; people = res.data?.people?.people || [];
numberOfFaces = asset.people?.numberOfAssets || 0;
textarea.value = res.data?.exifInfo?.description || ''; textarea.value = res.data?.exifInfo?.description || '';
}); });
showEditFaces = false; showEditFaces = false;
@ -201,7 +203,7 @@
/> />
</section> </section>
{#if !api.isSharedLink && people.length > 0} {#if !api.isSharedLink && numberOfFaces > 0}
<section class="px-4 py-4 text-sm"> <section class="px-4 py-4 text-sm">
<div class="flex h-10 w-full items-center justify-between"> <div class="flex h-10 w-full items-center justify-between">
<h2>PEOPLE</h2> <h2>PEOPLE</h2>
@ -223,7 +225,7 @@
/> />
</div> </div>
</div> </div>
{#if people.length > 0}
<div class="mt-2 flex flex-wrap gap-2"> <div class="mt-2 flex flex-wrap gap-2">
{#each people as person, index (person.id)} {#each people as person, index (person.id)}
<div <div
@ -272,6 +274,7 @@
</div> </div>
{/each} {/each}
</div> </div>
{/if}
</section> </section>
{/if} {/if}

View file

@ -19,6 +19,7 @@
export let border = false; export let border = false;
export let preload = true; export let preload = true;
export let eyeColor: 'black' | 'white' = 'white'; export let eyeColor: 'black' | 'white' = 'white';
export let persistentBorder = false;
let complete = false; let complete = false;
let img: HTMLImageElement; let img: HTMLImageElement;
@ -42,7 +43,7 @@
{title} {title}
class="object-cover transition duration-300 {border class="object-cover transition duration-300 {border
? 'border-[3px] border-immich-dark-primary/80 hover:border-immich-primary' ? 'border-[3px] border-immich-dark-primary/80 hover:border-immich-primary'
: ''}" : ''} {persistentBorder ? 'border-[3px] border-immich-dark-primary/80 border-immich-primary' : ''}"
class:rounded-xl={curve} class:rounded-xl={curve}
class:shadow-lg={shadow} class:shadow-lg={shadow}
class:rounded-full={circle} class:rounded-full={circle}

View file

@ -7,13 +7,12 @@
import { mdiArrowLeftThin, mdiClose, mdiMagnify, mdiPlus } from '@mdi/js'; import { mdiArrowLeftThin, mdiClose, mdiMagnify, mdiPlus } from '@mdi/js';
import LoadingSpinner from '../shared-components/loading-spinner.svelte'; import LoadingSpinner from '../shared-components/loading-spinner.svelte';
import ImageThumbnail from '../assets/thumbnail/image-thumbnail.svelte'; import ImageThumbnail from '../assets/thumbnail/image-thumbnail.svelte';
import { getPersonNameWithHiddenValue, searchNameLocal } from '$lib/utils/person'; import { getPersonNameWithHiddenValue, searchNameLocal, zoomImageToBase64 } from '$lib/utils/person';
import { handleError } from '$lib/utils/handle-error'; import { handleError } from '$lib/utils/handle-error';
import { photoViewer } from '$lib/stores/assets.store'; import { photoViewer } from '$lib/stores/assets.store';
export let peopleWithFaces: AssetFaceResponseDto[]; export let personWithFace: AssetFaceResponseDto;
export let allPeople: PersonResponseDto[]; export let allPeople: PersonResponseDto[];
export let editedPersonIndex: number;
// loading spinners // loading spinners
let isShowLoadingNewPerson = false; let isShowLoadingNewPerson = false;
@ -30,51 +29,11 @@
const handleBackButton = () => { const handleBackButton = () => {
dispatch('close'); dispatch('close');
}; };
const zoomImageToBase64 = async (face: AssetFaceResponseDto): Promise<string | null> => {
if ($photoViewer === null) {
return null;
}
const { boundingBoxX1: x1, boundingBoxX2: x2, boundingBoxY1: y1, boundingBoxY2: y2 } = face;
const coordinates = {
x1: ($photoViewer.naturalWidth / face.imageWidth) * x1,
x2: ($photoViewer.naturalWidth / face.imageWidth) * x2,
y1: ($photoViewer.naturalHeight / face.imageHeight) * y1,
y2: ($photoViewer.naturalHeight / face.imageHeight) * y2,
};
const faceWidth = coordinates.x2 - coordinates.x1;
const faceHeight = coordinates.y2 - coordinates.y1;
const faceImage = new Image();
faceImage.src = $photoViewer.src;
await new Promise((resolve) => {
faceImage.onload = resolve;
faceImage.onerror = () => resolve(null);
});
const canvas = document.createElement('canvas');
canvas.width = faceWidth;
canvas.height = faceHeight;
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.drawImage(faceImage, coordinates.x1, coordinates.y1, faceWidth, faceHeight, 0, 0, faceWidth, faceHeight);
return canvas.toDataURL();
} else {
return null;
}
};
const handleCreatePerson = async () => { const handleCreatePerson = async () => {
const timeout = setTimeout(() => (isShowLoadingNewPerson = true), 100); const timeout = setTimeout(() => (isShowLoadingNewPerson = true), 100);
const personToUpdate = peopleWithFaces.find((person) => person.id === peopleWithFaces[editedPersonIndex].id);
const newFeaturePhoto = personToUpdate ? await zoomImageToBase64(personToUpdate) : null; const newFeaturePhoto = await zoomImageToBase64(personWithFace, $photoViewer);
dispatch('createPerson', newFeaturePhoto);
clearTimeout(timeout); clearTimeout(timeout);
isShowLoadingNewPerson = false; isShowLoadingNewPerson = false;
@ -111,7 +70,7 @@
<section <section
transition:fly={{ x: 360, duration: 100, easing: linear }} transition:fly={{ x: 360, duration: 100, easing: linear }}
class="absolute top-0 z-[2001] h-full w-[360px] overflow-x-hidden p-2 bg-immich-bg dark:bg-immich-dark-bg dark:text-immich-dark-fg" class="absolute top-0 z-[2002] h-full w-[360px] overflow-x-hidden p-2 bg-immich-bg dark:bg-immich-dark-bg dark:text-immich-dark-fg"
> >
<div class="flex place-items-center justify-between gap-2"> <div class="flex place-items-center justify-between gap-2">
{#if !searchFaces} {#if !searchFaces}
@ -193,7 +152,7 @@
<div class="immich-scrollbar mt-4 flex flex-wrap gap-2 overflow-y-auto"> <div class="immich-scrollbar mt-4 flex flex-wrap gap-2 overflow-y-auto">
{#if searchName == ''} {#if searchName == ''}
{#each allPeople as person (person.id)} {#each allPeople as person (person.id)}
{#if person.id !== peopleWithFaces[editedPersonIndex].person?.id} {#if person.id !== personWithFace.person?.id}
<div class="w-fit"> <div class="w-fit">
<button class="w-[90px]" on:click={() => dispatch('reassign', person)}> <button class="w-[90px]" on:click={() => dispatch('reassign', person)}>
<div class="relative"> <div class="relative">
@ -219,7 +178,7 @@
{/each} {/each}
{:else} {:else}
{#each searchedPeople as person (person.id)} {#each searchedPeople as person (person.id)}
{#if person.id !== peopleWithFaces[editedPersonIndex].person?.id} {#if person.id !== personWithFace.person?.id}
<div class="w-fit"> <div class="w-fit">
<button class="w-[90px]" on:click={() => dispatch('reassign', person)}> <button class="w-[90px]" on:click={() => dispatch('reassign', person)}>
<div class="relative"> <div class="relative">

View file

@ -7,31 +7,41 @@
import { createEventDispatcher, onMount } from 'svelte'; import { createEventDispatcher, onMount } from 'svelte';
import LoadingSpinner from '$lib/components/shared-components/loading-spinner.svelte'; import LoadingSpinner from '$lib/components/shared-components/loading-spinner.svelte';
import { NotificationType, notificationController } from '../shared-components/notification/notification'; import { NotificationType, notificationController } from '../shared-components/notification/notification';
import { mdiArrowLeftThin, mdiRestart } from '@mdi/js'; import { mdiAccountOff, mdiArrowLeftThin, mdiFaceMan, mdiRestart, mdiSelect } from '@mdi/js';
import Icon from '../elements/icon.svelte'; import Icon from '../elements/icon.svelte';
import { boundingBoxesArray } from '$lib/stores/people.store'; import { boundingBoxesArray } from '$lib/stores/people.store';
import { websocketStore } from '$lib/stores/websocket'; import { websocketStore } from '$lib/stores/websocket';
import AssignFaceSidePanel from './assign-face-side-panel.svelte'; import AssignFaceSidePanel from './assign-face-side-panel.svelte';
import { getPersonNameWithHiddenValue } from '$lib/utils/person'; import { getPersonNameWithHiddenValue, zoomImageToBase64 } from '$lib/utils/person';
import { photoViewer } from '$lib/stores/assets.store';
import UnassignedFacesSidePannel from './unassigned-faces-side-pannel.svelte';
import type { FaceWithGeneretedThumbnail } from '$lib/utils/people-utils';
export let assetId: string; export let assetId: string;
// keep track of the changes // keep track of the changes
let numberOfPersonToCreate: string[] = []; let idsOfPersonToCreate: string[] = [];
let numberOfAssetFaceGenerated: string[] = []; let idsOfAssetFaceGenerated: string[] = [];
// faces // faces
let peopleWithFaces: AssetFaceResponseDto[] = []; let peopleWithFaces: AssetFaceResponseDto[] = [];
let selectedPersonToReassign: (PersonResponseDto | null)[]; let selectedPersonToReassign: (PersonResponseDto | null)[];
let selectedPersonToCreate: (string | null)[]; let selectedPersonToCreate: (string | null)[];
let selectedPersonToAdd: FaceWithGeneretedThumbnail[] = [];
let selectedPersonToUnassign: FaceWithGeneretedThumbnail[] = [];
let selectedPersonToRemove: boolean[] = [];
let unassignedFaces: (FaceWithGeneretedThumbnail | null)[] = [];
let editedPersonIndex: number; let editedPersonIndex: number;
let shouldRefresh: boolean = false;
// loading spinners // loading spinners
let isShowLoadingDone = false; let isShowLoadingDone = false;
let isShowLoadingPeople = false; let isShowLoadingPeople = false;
// search people // other modals
let showSeletecFaces = false; let showSeletecFaces = false;
let showUnassignedFaces = false;
let isSelectingFaces = false;
let allPeople: PersonResponseDto[] = []; let allPeople: PersonResponseDto[] = [];
// timers // timers
@ -43,15 +53,17 @@
// Reset value // Reset value
$onPersonThumbnail = ''; $onPersonThumbnail = '';
$: numberOfFacesToUnassign = selectedPersonToRemove ? selectedPersonToRemove.filter((value) => value).length : 0;
$: { $: {
if ($onPersonThumbnail) { if ($onPersonThumbnail) {
numberOfAssetFaceGenerated.push($onPersonThumbnail); idsOfAssetFaceGenerated.push($onPersonThumbnail);
if ( if (
isEqual(numberOfAssetFaceGenerated, numberOfPersonToCreate) && isEqual(idsOfAssetFaceGenerated, idsOfPersonToCreate) &&
loaderLoadingDoneTimeout && loaderLoadingDoneTimeout &&
automaticRefreshTimeout && automaticRefreshTimeout &&
selectedPersonToCreate.filter((person) => person !== null).length === numberOfPersonToCreate.length selectedPersonToCreate.filter((person) => person !== null).length +
selectedPersonToAdd.filter((face) => face.person === null).length ===
idsOfPersonToCreate.length
) { ) {
clearTimeout(loaderLoadingDoneTimeout); clearTimeout(loaderLoadingDoneTimeout);
clearTimeout(automaticRefreshTimeout); clearTimeout(automaticRefreshTimeout);
@ -69,6 +81,17 @@
peopleWithFaces = result.data; peopleWithFaces = result.data;
selectedPersonToCreate = new Array<string | null>(peopleWithFaces.length); selectedPersonToCreate = new Array<string | null>(peopleWithFaces.length);
selectedPersonToReassign = new Array<PersonResponseDto | null>(peopleWithFaces.length); selectedPersonToReassign = new Array<PersonResponseDto | null>(peopleWithFaces.length);
selectedPersonToRemove = new Array<boolean>(peopleWithFaces.length);
unassignedFaces = await Promise.all(
peopleWithFaces.map(async (personWithFace) => {
if (personWithFace.person) {
return null;
} else {
const image = await zoomImageToBase64(personWithFace, $photoViewer);
return image ? { ...personWithFace, customThumbnail: image } : null;
}
}),
);
} catch (error) { } catch (error) {
handleError(error, "Can't get faces"); handleError(error, "Can't get faces");
} finally { } finally {
@ -82,6 +105,15 @@
}; };
const handleBackButton = () => { const handleBackButton = () => {
if (isSelectingFaces) {
isSelectingFaces = false;
selectedPersonToRemove = new Array<boolean>(peopleWithFaces.length);
return;
}
if (shouldRefresh) {
dispatch('refresh');
return;
}
dispatch('close'); dispatch('close');
}; };
@ -94,11 +126,67 @@
} }
}; };
const handleOpenAvailableFaces = () => {
showUnassignedFaces = true;
};
const handleSelectFaces = () => {
isSelectingFaces = !isSelectingFaces;
};
const handleSelectFace = (index: number) => {
if (!isSelectingFaces) {
return;
}
selectedPersonToRemove[index] = !selectedPersonToRemove[index];
};
const handleRemoveAddedFace = (indexToRemove: number) => {
$boundingBoxesArray = [];
selectedPersonToAdd = selectedPersonToAdd.filter((_, index) => index !== indexToRemove);
};
const handleAddRemovedFace = (indexToRemove: number) => {
$boundingBoxesArray = [];
unassignedFaces = unassignedFaces.map((obj) =>
obj && obj.id === selectedPersonToUnassign[indexToRemove].id ? null : obj,
);
selectedPersonToUnassign = selectedPersonToUnassign.filter((_, index) => index !== indexToRemove);
};
const handleUnassignFaces = async () => {
if (numberOfFacesToUnassign > 0) {
for (let i = 0; i < peopleWithFaces.length; i++) {
if (selectedPersonToRemove[i]) {
const image = await zoomImageToBase64(peopleWithFaces[i], $photoViewer);
if (image) {
selectedPersonToUnassign.push({ ...peopleWithFaces[i], customThumbnail: image });
// Trigger reactivity
selectedPersonToUnassign = selectedPersonToUnassign;
if (selectedPersonToReassign[i]) {
selectedPersonToReassign[i] = null;
}
if (selectedPersonToCreate[i]) {
selectedPersonToCreate[i] = null;
}
}
}
}
const uniqueIds = new Set(selectedPersonToUnassign.map((objA) => objA.id));
selectedPersonToAdd = selectedPersonToAdd.filter((objB) => !uniqueIds.has(objB.id));
}
selectedPersonToRemove = new Array<boolean>(peopleWithFaces.length);
isSelectingFaces = false;
};
const handleEditFaces = async () => { const handleEditFaces = async () => {
loaderLoadingDoneTimeout = setTimeout(() => (isShowLoadingDone = true), 100); loaderLoadingDoneTimeout = setTimeout(() => (isShowLoadingDone = true), 100);
const numberOfChanges = const numberOfChanges =
selectedPersonToCreate.filter((person) => person !== null).length + selectedPersonToCreate.filter((person) => person !== null).length +
selectedPersonToReassign.filter((person) => person !== null).length; selectedPersonToReassign.filter((person) => person !== null).length +
selectedPersonToAdd.length +
selectedPersonToUnassign.length;
if (numberOfChanges > 0) { if (numberOfChanges > 0) {
try { try {
for (let i = 0; i < peopleWithFaces.length; i++) { for (let i = 0; i < peopleWithFaces.length; i++) {
@ -111,13 +199,34 @@
}); });
} else if (selectedPersonToCreate[i]) { } else if (selectedPersonToCreate[i]) {
const { data } = await api.personApi.createPerson(); const { data } = await api.personApi.createPerson();
numberOfPersonToCreate.push(data.id); idsOfPersonToCreate.push(data.id);
await api.faceApi.reassignFacesById({ await api.faceApi.reassignFacesById({
id: data.id, id: data.id,
faceDto: { id: peopleWithFaces[i].id }, faceDto: { id: peopleWithFaces[i].id },
}); });
} }
} }
for (const face of selectedPersonToAdd) {
if (face.person) {
await api.faceApi.reassignFacesById({
id: face.person.id,
faceDto: { id: face.id },
});
} else {
const { data } = await api.personApi.createPerson();
idsOfPersonToCreate.push(data.id);
await api.faceApi.reassignFacesById({
id: data.id,
faceDto: { id: face.id },
});
}
}
for (const face of selectedPersonToUnassign) {
await api.faceApi.unassignFace({
id: face.id,
});
}
notificationController.show({ notificationController.show({
message: `Edited ${numberOfChanges} ${numberOfChanges > 1 ? 'people' : 'person'}`, message: `Edited ${numberOfChanges} ${numberOfChanges > 1 ? 'people' : 'person'}`,
@ -129,7 +238,7 @@
} }
isShowLoadingDone = false; isShowLoadingDone = false;
if (numberOfPersonToCreate.length === 0) { if (idsOfPersonToCreate.length === 0) {
clearTimeout(loaderLoadingDoneTimeout); clearTimeout(loaderLoadingDoneTimeout);
dispatch('refresh'); dispatch('refresh');
} else { } else {
@ -148,8 +257,14 @@
const handleReassignFace = (person: PersonResponseDto | null) => { const handleReassignFace = (person: PersonResponseDto | null) => {
if (person) { if (person) {
selectedPersonToReassign[editedPersonIndex] = person; selectedPersonToReassign[editedPersonIndex] = person;
showSeletecFaces = false;
} }
showSeletecFaces = false;
};
const handleCreateOrReassignFaceFromUnassignedFace = (face: FaceWithGeneretedThumbnail) => {
selectedPersonToAdd.push(face);
selectedPersonToAdd = selectedPersonToAdd;
showUnassignedFaces = false;
}; };
const handlePersonPicker = async (index: number) => { const handlePersonPicker = async (index: number) => {
@ -172,29 +287,78 @@
<Icon path={mdiArrowLeftThin} size="24" /> <Icon path={mdiArrowLeftThin} size="24" />
</div> </div>
</button> </button>
<p class="flex text-lg text-immich-fg dark:text-immich-dark-fg">Edit faces</p> <p class="flex text-lg text-immich-fg dark:text-immich-dark-fg">
{isSelectingFaces ? 'Select Faces' : 'Edit faces'}
</p>
</div> </div>
{#if !isShowLoadingDone} {#if !isShowLoadingDone}
<div class="flex items-center gap-2">
{#if !isSelectingFaces && unassignedFaces.length > 0}
<button <button
class="justify-self-end rounded-lg p-2 hover:bg-immich-dark-primary hover:dark:bg-immich-dark-primary/50" class="justify-self-end rounded-lg p-2 hover:bg-immich-dark-primary hover:dark:bg-immich-dark-primary/50"
on:click={() => handleEditFaces()} on:click={handleOpenAvailableFaces}
title="Faces available"
>
<div>
<Icon path={mdiFaceMan} />
</div>
</button>
{/if}
{#if !peopleWithFaces.every((item) => item.person === null)}
<button
class="justify-self-end rounded-lg p-2 hover:bg-immich-dark-primary hover:dark:bg-immich-dark-primary/50"
on:click={handleSelectFaces}
title="Select faces to unassign"
>
<div>
<Icon path={mdiSelect} />
</div>
</button>
{/if}
{#if !isSelectingFaces}
<button
class="justify-self-end rounded-lg p-2 hover:bg-immich-dark-primary hover:dark:bg-immich-dark-primary/50"
on:click={handleEditFaces}
> >
Done Done
</button> </button>
{/if}
</div>
{:else} {:else}
<LoadingSpinner /> <LoadingSpinner />
{/if} {/if}
</div> </div>
<div class="px-4 py-4 text-sm"> <div class="px-4 py-4 text-sm">
<div class="mt-4 flex flex-wrap gap-2"> <div class="flex items-center justify-between gap-2 h-10">
{#if peopleWithFaces.every((item) => item.person === null)}
<div class="flex items-center justify-center w-full">
<div class="grid place-items-center">
<Icon path={mdiAccountOff} size="3.5em" />
<p class="mt-5 font-medium">No faces visible</p>
</div>
</div>
{:else}
<div>Visible faces</div>
{/if}
{#if isSelectingFaces && selectedPersonToRemove && selectedPersonToRemove.filter((value) => value).length > 0}
<button
class="justify-self-end rounded-lg p-2 hover:bg-immich-dark-primary hover:dark:bg-immich-dark-primary/50"
on:click={handleUnassignFaces}
>
Unassign faces
</button>
{/if}
</div>
<div class="mt-2 flex flex-wrap gap-2">
{#if isShowLoadingPeople} {#if isShowLoadingPeople}
<div class="flex w-full justify-center"> <div class="flex w-full justify-center">
<LoadingSpinner /> <LoadingSpinner />
</div> </div>
{:else} {:else}
{#each peopleWithFaces as face, index} {#each peopleWithFaces as face, index}
{#if face.person} {#if face.person && unassignedFaces[index] === null && !selectedPersonToUnassign.some((unassignedFace) => unassignedFace.id === face.id)}
<div class="relative z-[20001] h-[115px] w-[95px]"> <div class="relative z-[20001] h-[115px] w-[95px]">
<div <div
role="button" role="button"
@ -203,6 +367,8 @@
on:focus={() => ($boundingBoxesArray = [peopleWithFaces[index]])} on:focus={() => ($boundingBoxesArray = [peopleWithFaces[index]])}
on:mouseover={() => ($boundingBoxesArray = [peopleWithFaces[index]])} on:mouseover={() => ($boundingBoxesArray = [peopleWithFaces[index]])}
on:mouseleave={() => ($boundingBoxesArray = [])} on:mouseleave={() => ($boundingBoxesArray = [])}
on:click={() => handleSelectFace(index)}
on:keydown={() => handleSelectFace(index)}
> >
<div class="relative"> <div class="relative">
<ImageThumbnail <ImageThumbnail
@ -223,11 +389,14 @@
widthStyle="90px" widthStyle="90px"
heightStyle="90px" heightStyle="90px"
thumbhash={null} thumbhash={null}
hidden={selectedPersonToReassign[index] hidden={!isSelectingFaces
? selectedPersonToReassign[index]
? selectedPersonToReassign[index]?.isHidden ? selectedPersonToReassign[index]?.isHidden
: selectedPersonToCreate[index] : selectedPersonToCreate[index]
? false ? false
: face.person?.isHidden} : face.person?.isHidden
: false}
persistentBorder={isSelectingFaces ? selectedPersonToRemove[index] : false}
/> />
</div> </div>
{#if !selectedPersonToCreate[index]} {#if !selectedPersonToCreate[index]}
@ -239,7 +408,7 @@
{/if} {/if}
</p> </p>
{/if} {/if}
{#if !isSelectingFaces}
<div class="absolute -right-[5px] -top-[5px] h-[20px] w-[20px] rounded-full bg-blue-700"> <div class="absolute -right-[5px] -top-[5px] h-[20px] w-[20px] rounded-full bg-blue-700">
{#if selectedPersonToCreate[index] || selectedPersonToReassign[index]} {#if selectedPersonToCreate[index] || selectedPersonToReassign[index]}
<button on:click={() => handleReset(index)} class="flex h-full w-full"> <button on:click={() => handleReset(index)} class="flex h-full w-full">
@ -257,22 +426,129 @@
</button> </button>
{/if} {/if}
</div> </div>
{/if}
</div> </div>
</div> </div>
{/if} {/if}
{/each} {/each}
{/if} {/if}
</div> </div>
{#if selectedPersonToAdd.length > 0}
<div class="mt-2">
<p>Faces to add</p>
<div class="mt-4 flex flex-wrap gap-2">
{#each selectedPersonToAdd as face, index}
{#if face}
<div class="relative z-[20001] h-[115px] w-[95px]">
<div
role="button"
tabindex={index}
class="absolute left-0 top-0 h-[90px] w-[90px] cursor-default"
on:focus={() => ($boundingBoxesArray = [peopleWithFaces[index]])}
on:mouseover={() => ($boundingBoxesArray = [peopleWithFaces[index]])}
on:mouseleave={() => ($boundingBoxesArray = [])}
>
<div class="relative">
<ImageThumbnail
curve
shadow
url={face.person && face.person.id
? api.getPeopleThumbnailUrl(face.person.id)
: face.customThumbnail}
altText={'New person'}
title={'New person'}
widthStyle="90px"
heightStyle="90px"
thumbhash={null}
/>
</div>
{#if face.person?.name}
<p class="relative mt-1 truncate font-medium" title={face.person?.name}>
{face.person?.name}
</p>{/if}
{#if !isSelectingFaces}
<div class="absolute -right-[5px] -top-[5px] h-[20px] w-[20px] rounded-full bg-red-700">
<button on:click={() => handleRemoveAddedFace(index)} class="flex h-full w-full">
<div
class="absolute left-1/2 top-1/2 h-[2px] w-[14px] translate-x-[-50%] translate-y-[-50%] transform bg-white"
/>
</button>
</div>
{/if}
</div>
</div>
{/if}
{/each}
</div>
</div>
{/if}
{#if selectedPersonToUnassign.length > 0}
<div class="mt-2">
<p>Faces to unassign</p>
<div class="mt-4 flex flex-wrap gap-2">
{#each selectedPersonToUnassign as face, index}
{#if face && face.person}
<div class="relative z-[20001] h-[115px] w-[95px]">
<div
role="button"
tabindex={index}
class="absolute left-0 top-0 h-[90px] w-[90px] cursor-default"
on:focus={() => ($boundingBoxesArray = [peopleWithFaces[index]])}
on:mouseover={() => ($boundingBoxesArray = [peopleWithFaces[index]])}
on:mouseleave={() => ($boundingBoxesArray = [])}
>
<div class="relative">
<ImageThumbnail
curve
shadow
url={face.customThumbnail}
altText={'New person'}
title={'New person'}
widthStyle="90px"
heightStyle="90px"
thumbhash={null}
/>
</div>
{#if face.person?.name}
<p class="relative mt-1 truncate font-medium" title={face.person?.name}>
{face.person?.name}
</p>{/if}
{#if !isSelectingFaces}
<div class="absolute -right-[5px] -top-[5px] h-[20px] w-[20px] rounded-full bg-red-700">
<button on:click={() => handleAddRemovedFace(index)} class="flex h-full w-full">
<div
class="absolute left-1/2 top-1/2 h-[2px] w-[14px] translate-x-[-50%] translate-y-[-50%] transform bg-white"
/>
</button>
</div>
{/if}
</div>
</div>
{/if}
{/each}
</div>
</div>
{/if}
</div> </div>
</section> </section>
{#if showSeletecFaces} {#if showSeletecFaces}
<AssignFaceSidePanel <AssignFaceSidePanel
{peopleWithFaces} personWithFace={peopleWithFaces[editedPersonIndex]}
{allPeople} {allPeople}
{editedPersonIndex}
on:close={() => (showSeletecFaces = false)} on:close={() => (showSeletecFaces = false)}
on:createPerson={(event) => handleCreatePerson(event.detail)} on:createPerson={(event) => handleCreatePerson(event.detail)}
on:reassign={(event) => handleReassignFace(event.detail)} on:reassign={(event) => handleReassignFace(event.detail)}
/> />
{/if} {/if}
{#if showUnassignedFaces}
<UnassignedFacesSidePannel
{allPeople}
{unassignedFaces}
{selectedPersonToAdd}
on:close={() => (showUnassignedFaces = false)}
on:createPerson={(event) => handleCreateOrReassignFaceFromUnassignedFace(event.detail)}
on:reassign={(event) => handleCreateOrReassignFaceFromUnassignedFace(event.detail)}
/>
{/if}

View file

@ -0,0 +1,122 @@
<script lang="ts">
import { fly } from 'svelte/transition';
import { linear } from 'svelte/easing';
import ImageThumbnail from '../assets/thumbnail/image-thumbnail.svelte';
import { mdiAccountOff, mdiArrowLeftThin } from '@mdi/js';
import Icon from '../elements/icon.svelte';
import { createEventDispatcher } from 'svelte';
import AssignFaceSidePanel from './assign-face-side-panel.svelte';
import type { PersonResponseDto } from '@api';
import type { FaceWithGeneretedThumbnail } from '$lib/utils/people-utils';
import { boundingBoxesArray } from '$lib/stores/people.store';
export let unassignedFaces: (FaceWithGeneretedThumbnail | null)[];
export let allPeople: PersonResponseDto[];
export let selectedPersonToAdd: FaceWithGeneretedThumbnail[];
let showSeletecFaces = false;
let personSelected: FaceWithGeneretedThumbnail;
const dispatch = createEventDispatcher();
const handleBackButton = () => {
dispatch('close');
};
const handleSelectedFace = (index: number) => {
const face = unassignedFaces[index];
if (face) {
personSelected = face;
showSeletecFaces = true;
}
};
const handleCreatePerson = (newFeaturePhoto: string | null) => {
showSeletecFaces = false;
if (newFeaturePhoto) {
personSelected.customThumbnail = newFeaturePhoto;
dispatch('createPerson', personSelected);
} else {
dispatch('close');
}
};
const handleReassignFace = (person: PersonResponseDto | null) => {
if (person) {
showSeletecFaces = false;
personSelected.person = person;
dispatch('reassign', personSelected);
} else {
dispatch('close');
}
};
</script>
<section
transition:fly={{ x: 360, duration: 100, easing: linear }}
class="absolute top-0 z-[2001] h-full w-[360px] overflow-x-hidden p-2 bg-immich-bg dark:bg-immich-dark-bg dark:text-immich-dark-fg"
>
<div class="flex place-items-center justify-between gap-2">
<div class="flex items-center gap-2">
<button
class="flex place-content-center rounded-full p-3 transition-colors hover:bg-gray-200 dark:text-immich-dark-fg dark:hover:bg-gray-900"
on:click={handleBackButton}
>
<div>
<Icon path={mdiArrowLeftThin} size="24" />
</div>
</button>
<p class="flex text-lg text-immich-fg dark:text-immich-dark-fg">Faces available</p>
</div>
</div>
{#if unassignedFaces.some((face) => face)}
<div class="px-4 py-4 text-sm">
<div class="mt-4 flex flex-wrap gap-2">
{#each unassignedFaces as face, index}
{#if face && !selectedPersonToAdd.some((faceToAdd) => face && faceToAdd.id === face.id)}
<div class="relative z-[20001] h-[115px] w-[95px]">
<button
tabindex={index}
class="absolute left-0 top-0 h-[90px] w-[90px] cursor-default"
on:focus={() => (face ? ($boundingBoxesArray = [face]) : '')}
on:mouseover={() => (face ? ($boundingBoxesArray = [face]) : '')}
on:mouseleave={() => ($boundingBoxesArray = [])}
on:click={() => handleSelectedFace(index)}
on:keydown={() => handleSelectedFace(index)}
>
<ImageThumbnail
curve
shadow
url={face.customThumbnail}
title="Available face"
altText="Available face"
widthStyle="90px"
heightStyle="90px"
thumbhash={null}
/>
</button>
</div>
{/if}
{/each}
</div>
</div>
{:else}
<div class="flex items-center justify-center">
<div class="grid place-items-center">
<Icon path={mdiAccountOff} size="3.5em" />
<p class="mt-5 font-medium">No faces available</p>
</div>
</div>
{/if}
</section>
{#if showSeletecFaces}
<AssignFaceSidePanel
personWithFace={personSelected}
{allPeople}
on:close={() => (showSeletecFaces = false)}
on:createPerson={(event) => handleCreatePerson(event.detail)}
on:reassign={(event) => handleReassignFace(event.detail)}
/>
{/if}

View file

@ -1,4 +1,5 @@
import type { Faces } from '$lib/stores/people.store'; import type { Faces } from '$lib/stores/people.store';
import type { AssetFaceResponseDto } from '@api';
import type { ZoomImageWheelState } from '@zoom-image/core'; import type { ZoomImageWheelState } from '@zoom-image/core';
const getContainedSize = (img: HTMLImageElement): { width: number; height: number } => { const getContainedSize = (img: HTMLImageElement): { width: number; height: number } => {
@ -19,6 +20,10 @@ export interface boundingBox {
height: number; height: number;
} }
export interface FaceWithGeneretedThumbnail extends AssetFaceResponseDto {
customThumbnail: string;
}
export const getBoundingBox = ( export const getBoundingBox = (
faces: Faces[], faces: Faces[],
zoom: ZoomImageWheelState, zoom: ZoomImageWheelState,

View file

@ -1,4 +1,4 @@
import type { PersonResponseDto } from '@api'; import type { AssetFaceResponseDto, PersonResponseDto } from '@api';
export const searchNameLocal = ( export const searchNameLocal = (
name: string, name: string,
@ -34,3 +34,44 @@ export const searchNameLocal = (
export const getPersonNameWithHiddenValue = (name: string, isHidden: boolean) => { export const getPersonNameWithHiddenValue = (name: string, isHidden: boolean) => {
return `${name ? name + (isHidden ? ' ' : '') : ''}${isHidden ? '(hidden)' : ''}`; return `${name ? name + (isHidden ? ' ' : '') : ''}${isHidden ? '(hidden)' : ''}`;
}; };
export const zoomImageToBase64 = async (
face: AssetFaceResponseDto,
photoViewer: HTMLImageElement | null,
): Promise<string | null> => {
if (photoViewer === null) {
return null;
}
const { boundingBoxX1: x1, boundingBoxX2: x2, boundingBoxY1: y1, boundingBoxY2: y2 } = face;
const coordinates = {
x1: (photoViewer.naturalWidth / face.imageWidth) * x1,
x2: (photoViewer.naturalWidth / face.imageWidth) * x2,
y1: (photoViewer.naturalHeight / face.imageHeight) * y1,
y2: (photoViewer.naturalHeight / face.imageHeight) * y2,
};
const faceWidth = coordinates.x2 - coordinates.x1;
const faceHeight = coordinates.y2 - coordinates.y1;
const faceImage = new Image();
faceImage.src = photoViewer.src;
await new Promise((resolve) => {
faceImage.onload = resolve;
faceImage.onerror = () => resolve(null);
});
const canvas = document.createElement('canvas');
canvas.width = faceWidth;
canvas.height = faceHeight;
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.drawImage(faceImage, coordinates.x1, coordinates.y1, faceWidth, faceHeight, 0, 0, faceWidth, faceHeight);
return canvas.toDataURL();
} else {
return null;
}
};