Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/save replacement terms #129

Draft
wants to merge 5 commits into
base: dev
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -280,6 +280,15 @@ const buildDocumentRepository = buildRepositoryBuilder<
const updatedDocument = await collection.findOne({ _id: filter._id });
return updatedDocument || undefined;
},

async updateReplacementTermsById(documentId, replacementTerms) {
await collection.updateOne(
{ _id: documentId },
{ $set: { replacementTerms: replacementTerms } },
);
const updatedDocument = await collection.findOne({ _id: documentId });
return updatedDocument || undefined;
},
}),
});

Original file line number Diff line number Diff line change
@@ -385,5 +385,24 @@ const buildFakeDocumentRepository = buildFakeRepositoryBuilder<

return updatedDocument;
},

async updateReplacementTermsById(documentId, replacementTerm) {
updateFakeCollection(
collection,
collection.map((document) =>
idModule.lib.equalId(documentId, document._id)
? {
...document,
replacementTerm,
}
: document,
),
);
const updatedDocument = collection.find((document) =>
idModule.lib.equalId(documentId, document._id),
);

return updatedDocument;
},
}),
});
Original file line number Diff line number Diff line change
@@ -110,4 +110,8 @@ type customDocumentRepositoryType = {
filter: { status: documentType['status']; _id: documentType['_id'] },
update: { status: documentType['status'] },
) => Promise<documentType | undefined>;
updateReplacementTermsById: (
_id: idType,
replacementTerms: Record<string, unknown>,
) => Promise<documentType | undefined>;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { errorHandlers } from 'sder-core';
import {
buildAnonymizer,
documentModule,
documentType,
idModule,
settingsModule,
treatmentModule,
} from '@label/core';
import { buildDocumentRepository } from '../../repository';
import { treatmentService } from '../../../../modules/treatment';
import { settingsLoader } from '../../../../lib/settingsLoader';

export { updateDocumentReplacementTerms };

async function updateDocumentReplacementTerms(_id: documentType['_id']) {
const documentRepository = buildDocumentRepository();

const document = await documentRepository.findById(_id);
const settings = settingsLoader.getSettings();

const treatments = await treatmentService.fetchTreatmentsByDocumentId(
document._id,
);
const annotations = treatmentModule.lib.computeAnnotations(treatments);
const seed = documentModule.lib.computeCaseNumber(document);
const settingsForDocument = settingsModule.lib.computeFilteredSettings(
settings,
document.decisionMetadata.categoriesToOmit,
document.decisionMetadata.additionalTermsToAnnotate,
document.decisionMetadata.computedAdditionalTerms,
document.decisionMetadata.additionalTermsParsingFailed,
document.decisionMetadata.motivationOccultation,
);
const anonymizer = buildAnonymizer(settingsForDocument, annotations, seed);

const updatedDocument = await documentRepository.updateReplacementTermsById(
_id,
anonymizer.extractReplacementTerms(),
);
if (!updatedDocument) {
throw errorHandlers.notFoundErrorHandler.build(
`The document ${idModule.lib.convertToString(
_id,
)} was not found in the document collection`,
);
}
return updatedDocument;
}
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ import { assignationService } from '../../../assignation';
import { buildDocumentRepository } from '../../repository';
import { resetDocument } from './resetDocument';
import { logger } from '../../../../utils';
import { updateDocumentReplacementTerms } from './updateDocumentReplacementTerms';

export { updateDocumentStatus };

@@ -25,6 +26,8 @@ async function updateDocumentStatus(
}
if (status === 'free') {
await assignationService.deleteAssignationsByDocumentId(_id);
} else if (status === 'done' || status === 'toBePublished') {
await updateDocumentReplacementTerms(_id);
} else if (status === 'loaded') {
await resetDocument(_id);
}
Original file line number Diff line number Diff line change
@@ -151,4 +151,41 @@ describe('buildAnonymizer', () => {
expect(anonymizedText).toEqual('Leon');
});
});

/* eslint-disable @typescript-eslint/no-unsafe-assignment */
describe('extractReplacementTerms', () => {
it('should extract replacementTerms mapping', () => {
const annotations = [
{ category: 'firstName', text: 'Tintin', start: 0, certaintyScore: 1 },
{ category: 'lastName', text: 'Archibald', start: 7, certaintyScore: 1 },
{ category: 'firstName', text: 'Tournesol', start: 37, certaintyScore: 1 },
{ category: 'adresse', text: 'Chateau de Moulinsart', start: 45, certaintyScore: 1 },
{ category: 'firstName', text: 'Ottokar', start: 77, certaintyScore: 1 },
{ category: 'lastName', text: 'Haddock', start: 84, certaintyScore: 1 },
].map(annotationModule.lib.buildAnnotation);
annotations[5] = annotationModule.lib.annotationLinker.link(annotations[5], annotations[1]);

const anonymizer = buildAnonymizer(settings, annotations, seed);

const replacementTerms = anonymizer.extractReplacementTerms();

const expectedReplacementTerms = {
firstName_tintin: { replacementTerm: '[FIRST_NAME 4]', instances: ['Tintin'], category: 'firstName' },
lastName_archibald: {
replacementTerm: '[LAST_NAME 1]',
instances: ['Archibald', 'Haddock'],
category: 'lastName',
},
firstName_tournesol: { replacementTerm: '[FIRST_NAME 5]', instances: ['Tournesol'], category: 'firstName' },
'adresse_chateau de moulinsart': {
replacementTerm: 'Chateau de Moulinsart',
instances: ['Chateau de Moulinsart'],
category: 'adresse',
},
firstName_ottokar: { replacementTerm: '[FIRST_NAME 3]', instances: ['Ottokar'], category: 'firstName' },
};

expect(replacementTerms).toEqual(expectedReplacementTerms);
});
});
});
Original file line number Diff line number Diff line change
@@ -9,9 +9,18 @@ export { buildAnonymizer };

export type { anonymizerType };

export type ReplacementTermDict = {
[key: string]: {
replacementTerm: string;
instances: string[];
category: string;
};
};

type anonymizerType<documentT extends fetchedDocumentType> = {
anonymizeDocument: (document: documentT) => documentT;
anonymize: (annotation: annotationType) => string;
extractReplacementTerms: () => any;
};

function buildAnonymizer<documentT extends fetchedDocumentType>(
@@ -23,9 +32,11 @@ function buildAnonymizer<documentT extends fetchedDocumentType>(
return {
anonymizeDocument,
anonymize,
extractReplacementTerms,
};

function anonymizeDocument(document: documentT): documentT {
extractReplacementTerms();
const splittedText = textSplitter.splitTextAccordingToAnnotations(document.text, annotations);
const splittedAnonymizedText = splittedText.map((chunk) => {
switch (chunk.type) {
@@ -53,4 +64,23 @@ function buildAnonymizer<documentT extends fetchedDocumentType>(

return anonymizedText;
}

function extractReplacementTerms(): ReplacementTermDict {
const replacementTerms: ReplacementTermDict = {};

annotations.forEach((annotation) => {
if (replacementTerms[annotation.entityId]) {
if (!replacementTerms[annotation.entityId].instances.includes(annotation.text)) {
replacementTerms[annotation.entityId].instances.push(annotation.text);
}
} else {
replacementTerms[annotation.entityId] = {
replacementTerm: anonymize(annotation),
instances: [annotation.text],
category: annotation.category,
};
}
});
return replacementTerms;
}
}
Loading