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

spell-service.js 2.6 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
  1. // The exported functions in this module makes a call to Bing Spell Check API that returns spelling corrections.
  2. // For more info, check out the API reference:
  3. // https://dev.cognitive.microsoft.com/docs/services/56e73033cf5ff80c2008c679/operations/56e73036cf5ff81048ee6727
  4. var request = require('request');
  5. var SPELL_CHECK_API_URL = 'https://api.cognitive.microsoft.com/bing/v5.0/spellcheck/?form=BCSSCK',
  6. SPELL_CHECK_API_KEY = process.env.BING_SPELL_CHECK_API_KEY;
  7. /**
  8. * Gets the correct spelling for the given text
  9. * @param {string} text The text to be corrected
  10. * @returns {Promise} Promise with corrected text if succeeded, error otherwise.
  11. */
  12. exports.getCorrectedText = function (text) {
  13. return new Promise(
  14. function (resolve, reject) {
  15. if (text) {
  16. var requestData = {
  17. url: SPELL_CHECK_API_URL,
  18. headers: {
  19. "Ocp-Apim-Subscription-Key": SPELL_CHECK_API_KEY
  20. },
  21. form: {
  22. text: text
  23. },
  24. json: true
  25. }
  26. request.post(requestData, function (error, response, body) {
  27. if (error) {
  28. reject(error);
  29. }
  30. else if (response.statusCode != 200) {
  31. reject(body);
  32. }
  33. else {
  34. var previousOffset = 0;
  35. var result = '';
  36. for (var i = 0; i < body.flaggedTokens.length; i++) {
  37. var element = body.flaggedTokens[i];
  38. // Append the text from the previous offset to the current misspelled word offset
  39. result += text.substring(previousOffset, element.offset);
  40. // Append the corrected word instead of the misspelled word
  41. result += element.suggestions[0].suggestion;
  42. // Increment the offset by the length of the misspelled word
  43. previousOffset = element.offset + element.token.length;
  44. }
  45. // Append the text after the last misspelled word.
  46. if (previousOffset < text.length) {
  47. result += text.substring(previousOffset);
  48. }
  49. resolve(result);
  50. }
  51. });
  52. } else {
  53. resolve(text);
  54. }
  55. }
  56. )
  57. }
Tip!

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

Comments

Loading...