-
Notifications
You must be signed in to change notification settings - Fork 168
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #8 from Azure-Samples/distinct-skill
Add a distinct skill to de-duplicate a list of terms
- Loading branch information
Showing
13 changed files
with
485 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
// Licensed under the MIT License. See LICENSE file in the project root for full license information. | ||
|
||
using Microsoft.VisualStudio.TestTools.UnitTesting; | ||
using AzureCognitiveSearch.PowerSkills.Text.Distinct; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System; | ||
using System.IO; | ||
|
||
namespace AzureCognitiveSearch.PowerSkills.Tests.DistinctTests | ||
{ | ||
[TestClass] | ||
public class DistinctTests | ||
{ | ||
[DataTestMethod] | ||
[DataRow("Case insensitive díàcrïtiçs señsîtive AaBbCcÉéeÀàaÇçcÑñn", "caseinsensitivedíàcrïtiçsseñsîtiveaabbccééeààaççcññn")] | ||
[DataRow("Spaces are removed", "spacesareremoved")] | ||
[DataRow("Punctuation, as well; that is good...", "punctuationaswellthatisgood")] | ||
public void NormalizeLowersCaseRemovesPunctuationAndSpaces(string word, string expectedNormalized) | ||
=> Assert.AreEqual(expectedNormalized.Normalize(), Thesaurus.Normalize(word)); | ||
|
||
private static readonly string[][] _synonyms | ||
= new[] | ||
{ | ||
new[] { "A.C.R.O.N.Y.M", "acornym", "acronyms" }, | ||
new[] { "Microsoft", "Microsoft Corporation", "Microsoft corp.", "MSFT" } | ||
}; | ||
|
||
[DataTestMethod] | ||
[DataRow(new[] { "Acronym", "acornym", "a cro:n y.m "}, "A.C.R.O.N.Y.M")] | ||
[DataRow(new[] { "miCrosoft", "microsoft Corp;", "M.S.F.T."}, "Microsoft")] | ||
[DataRow(new[] { "Not found" }, "Not found")] | ||
public void ThesaurusReturnsCanonicalFormOrWordIfNotFound(IEnumerable<string> words, string expectedCanonical) | ||
{ | ||
foreach (string word in words) | ||
{ | ||
Assert.AreEqual(expectedCanonical, new Thesaurus(_synonyms).Dedupe(new[] { word }).First()); | ||
} | ||
} | ||
|
||
[DataTestMethod] | ||
[DataRow( | ||
"It is true that many acronyms are used at Microsoft. MSFT is no different as it's just an acronym for Microsoft.", | ||
"It is true that many A.C.R.O.N.Y.M are used at Microsoft no different as it's just an for")] | ||
public void DeduplicateYieldsListOfDistinctCanonicalForms(string text, string expectedDeduplicated) | ||
{ | ||
var expectedTerms = expectedDeduplicated.Split(' ').OrderBy(term => term); | ||
var deduped = new Thesaurus(_synonyms).Dedupe(text.Split(' ')).OrderBy(term => term); | ||
|
||
Assert.IsTrue(expectedTerms.SequenceEqual(deduped), $"Expected [{ string.Join(", ", expectedTerms) }] but was [{ string.Join(", ", deduped) }]."); | ||
} | ||
|
||
[TestMethod] | ||
public void ThesaurusBuildsNormalizedSynonymToCanonicalFormDictionaryAndIgnoresEmptyLemmas() | ||
{ | ||
const string canonicalAcronym = "acronym"; | ||
const string canonicalMicrosoft = "Microsoft"; | ||
var synonyms = new Thesaurus(new[] | ||
{ | ||
new[] { canonicalAcronym, "acornym", "acronyms" }, | ||
Array.Empty<string>(), | ||
new[] { canonicalMicrosoft, "Microsoft Corporation", "Microsoft corp.", "MSFT" } | ||
}).Synonyms; | ||
|
||
Assert.AreEqual(7, synonyms.Count()); | ||
Assert.AreEqual(canonicalAcronym, synonyms["acronym"]); | ||
Assert.AreEqual(canonicalAcronym, synonyms["acornym"]); | ||
Assert.AreEqual(canonicalAcronym, synonyms["acronyms"]); | ||
Assert.AreEqual(canonicalMicrosoft, synonyms["microsoft"]); | ||
Assert.AreEqual(canonicalMicrosoft, synonyms["microsoftcorporation"]); | ||
Assert.AreEqual(canonicalMicrosoft, synonyms["microsoftcorp"]); | ||
Assert.AreEqual(canonicalMicrosoft, synonyms["msft"]); | ||
} | ||
|
||
[TestMethod] | ||
public void ThesaurusConstructorThrowsForDuplicateLemmas() | ||
{ | ||
Assert.ThrowsException<InvalidDataException>(() => { | ||
_ = new Thesaurus(new[] | ||
{ | ||
new[] {"foo", "bar"}, | ||
new[] {"baz", "bar"} | ||
}); | ||
}); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
// Licensed under the MIT License. See LICENSE file in the project root for full license information. | ||
|
||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.Azure.WebJobs; | ||
using Microsoft.Azure.WebJobs.Extensions.Http; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Logging; | ||
using System.Collections.Generic; | ||
using AzureCognitiveSearch.PowerSkills.Common; | ||
using Newtonsoft.Json.Linq; | ||
using System; | ||
|
||
namespace AzureCognitiveSearch.PowerSkills.Text.Distinct | ||
{ | ||
public static class Distinct | ||
{ | ||
[FunctionName("distinct")] | ||
public static async Task<IActionResult> RunDistinct( | ||
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, | ||
ILogger log, | ||
ExecutionContext executionContext) | ||
{ | ||
log.LogInformation("Distinct Custom Skill: C# HTTP trigger function processed a request."); | ||
|
||
string skillName = executionContext.FunctionName; | ||
IEnumerable<WebApiRequestRecord> requestRecords = WebApiSkillHelpers.GetRequestRecords(req); | ||
if (requestRecords == null) | ||
{ | ||
return new BadRequestObjectResult($"{skillName} - Invalid request record array."); | ||
} | ||
|
||
try | ||
{ | ||
Thesaurus thesaurus = new Thesaurus(executionContext.FunctionAppDirectory); | ||
} | ||
catch(Exception e) | ||
{ | ||
throw new Exception("Failed to read and parse thesaurus.json.", e); | ||
} | ||
WebApiSkillResponse response = WebApiSkillHelpers.ProcessRequestRecords(skillName, requestRecords, | ||
(inRecord, outRecord) => | ||
{ | ||
JArray wordsParameter = inRecord.Data.TryGetValue("words", out object wordsParameterObject) ? | ||
wordsParameterObject as JArray : null; | ||
if (wordsParameter is null) | ||
{ | ||
throw new ArgumentException("Input data is missing a `words` array of words to de-duplicate.", "words"); | ||
} | ||
var words = wordsParameter.Values<string>(); | ||
outRecord.Data["distinct"] = thesaurus.Dedupe(words); | ||
return outRecord; | ||
}); | ||
|
||
return new OkObjectResult(response); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<PropertyGroup> | ||
<TargetFramework>netcoreapp2.1</TargetFramework> | ||
<AzureFunctionsVersion>v2</AzureFunctionsVersion> | ||
</PropertyGroup> | ||
<ItemGroup> | ||
<None Remove="thesaurus.json" /> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<Content Include="thesaurus.json"> | ||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> | ||
</Content> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.29" /> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<ProjectReference Include="..\..\Common\Common.csproj" /> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<None Update="host.json"> | ||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> | ||
</None> | ||
<None Update="local.settings.json"> | ||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> | ||
<CopyToPublishDirectory>Never</CopyToPublishDirectory> | ||
</None> | ||
</ItemGroup> | ||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
--- | ||
page_type: sample | ||
languages: | ||
- csharp | ||
products: | ||
- azure | ||
- azure-search | ||
name: Distinct sample skill for cognitive search | ||
description: This custom skill removes duplicates from a list of terms. | ||
azureDeploy: https://raw.githubusercontent.com/Azure-Samples/azure-search-power-skills/master/Text/Distinct/azuredeploy.json | ||
--- | ||
|
||
# Distinct | ||
|
||
This custom skill removes duplicates from a list of terms. | ||
|
||
Terms are considered the same if they only differ by casing, separators such as spaces, or punctuation, or if they have a common entry in the thesaurus. | ||
|
||
[![Deploy to Azure](https://azuredeploy.net/deploybutton.svg)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure-Samples%2Fazure-search-power-skills%2Fmaster%2FText%2FDistinct%2Fazuredeploy.json) | ||
|
||
## Requirements | ||
|
||
This skill has no additional requirements than the ones described in [the root `README.md` file](../../README.md). | ||
|
||
## Settings | ||
|
||
This function uses a JSON file called [`thesaurus.json`](./thesaurus.json) that can be found at the root of this project, and that will be deployed with the function. This file contains a simple list of lists of synonyms. For each list of synonyms, the first is considered the canonical form. Please replace this file with your own data. | ||
|
||
## link-acronyms | ||
|
||
### Sample Input: | ||
|
||
```json | ||
{ | ||
"values": [ | ||
{ | ||
"recordId": "foobar2", | ||
"data": | ||
{ | ||
"words": [ | ||
"MSFT", | ||
"U.S.A", | ||
"word", | ||
"United states", | ||
"WOrD", | ||
"Microsoft Corp." | ||
] | ||
} | ||
} | ||
] | ||
} | ||
``` | ||
|
||
### Sample Output: | ||
|
||
```json | ||
{ | ||
"values": [ | ||
{ | ||
"recordId": "foobar2", | ||
"data": { | ||
"distinct": { | ||
"value": [ | ||
"Microsoft", | ||
"USA", | ||
"word" | ||
] | ||
} | ||
}, | ||
"errors": [], | ||
"warnings": [] | ||
} | ||
] | ||
} | ||
``` | ||
|
||
## Sample Skillset Integration | ||
|
||
In order to use this skill in a cognitive search pipeline, you'll need to add a skill definition to your skillset. | ||
Here's a sample skill definition for this example (inputs and outputs should be updated to reflect your particular scenario and skillset environment): | ||
|
||
```json | ||
{ | ||
"@odata.type": "#Microsoft.Skills.Custom.WebApiSkill", | ||
"description": "Distinct entities", | ||
"uri": "[AzureFunctionEndpointUrl]/api/link-acronyms-list?code=[AzureFunctionDefaultHostKey]", | ||
"batchSize": 1, | ||
"context": "/document/merged_content", | ||
"inputs": [ | ||
{ | ||
"name": "words", | ||
"source": "/document/merged_content/organizations" | ||
} | ||
], | ||
"outputs": [ | ||
{ | ||
"name": "distinct", | ||
"targetName": "distinct_organizations" | ||
} | ||
] | ||
} | ||
``` |
Oops, something went wrong.