Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

BingSpellCheckService.cs 2.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  1. namespace LuisBot.Services
  2. {
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net.Http;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Web.Configuration;
  9. using Newtonsoft.Json;
  10. public class BingSpellCheckService
  11. {
  12. /// <summary>
  13. /// The Bing Spell Check Api Url.
  14. /// </summary>
  15. private const string SpellCheckApiUrl = "https://api.cognitive.microsoft.com/bing/v5.0/spellcheck/?form=BCSSCK";
  16. /// <summary>
  17. /// Microsoft Bing Spell Check Api Key.
  18. /// </summary>
  19. private static readonly string ApiKey = WebConfigurationManager.AppSettings["BingSpellCheckApiKey"];
  20. /// <summary>
  21. /// Gets the correct spelling for the given text
  22. /// </summary>
  23. /// <param name="text">The text to be corrected</param>
  24. /// <returns>string with corrected text</returns>
  25. public async Task<string> GetCorrectedTextAsync(string text)
  26. {
  27. if (string.IsNullOrEmpty(text))
  28. {
  29. return text;
  30. }
  31. using (var client = new HttpClient())
  32. {
  33. client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ApiKey);
  34. var values = new Dictionary<string, string>
  35. {
  36. { "text", text }
  37. };
  38. var content = new FormUrlEncodedContent(values);
  39. var response = await client.PostAsync(SpellCheckApiUrl, content);
  40. var responseString = await response.Content.ReadAsStringAsync();
  41. var spellCheckResponse = JsonConvert.DeserializeObject<BingSpellCheckResponse>(responseString);
  42. StringBuilder sb = new StringBuilder();
  43. int previousOffset = 0;
  44. foreach (var flaggedToken in spellCheckResponse.FlaggedTokens)
  45. {
  46. // Append the text from the previous offset to the current misspelled word offset
  47. sb.Append(text.Substring(previousOffset, flaggedToken.Offset - previousOffset));
  48. // Append the corrected word instead of the misspelled word
  49. sb.Append(flaggedToken.Suggestions.First().Suggestion);
  50. // Increment the offset by the length of the misspelled word
  51. previousOffset = flaggedToken.Offset + flaggedToken.Token.Length;
  52. }
  53. // Append the text after the last misspelled word.
  54. if (previousOffset < text.Length)
  55. {
  56. sb.Append(text.Substring(previousOffset));
  57. }
  58. return sb.ToString();
  59. }
  60. }
  61. }
  62. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...