sapling-py 4.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sapling/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """Sapling Python Client"""
2
+
3
+ from .client import SaplingClient, SaplingError
4
+ from .version import __version__
5
+
6
+ __all__ = [
7
+ "SaplingClient",
8
+ "SaplingError",
9
+ ]
sapling/client.py ADDED
@@ -0,0 +1,743 @@
1
+ import requests
2
+ import uuid
3
+
4
+
5
+ class SaplingError(Exception):
6
+ '''
7
+ Raised when the Sapling API returns a non-2xx response.
8
+
9
+ :ivar status_code: HTTP status code returned by the API.
10
+ :ivar body: Raw response body returned by the API (may be empty).
11
+ '''
12
+
13
+ def __init__(self, status_code, body=None):
14
+ self.status_code = status_code
15
+ self.body = body
16
+ super().__init__(f'HTTP {status_code}: {body}')
17
+
18
+
19
+ class SaplingClient:
20
+ '''
21
+ Sapling client class. Provides a mapping of Python functions to Sapling HTTP REST APIs.
22
+
23
+ :param api_key: 32-character API key
24
+ :type api_key: str
25
+ :param timeout: Timeout for API call in seconds. Defaults to 120 seconds.
26
+ :type timeout: int
27
+ :param hostname: Hostname override for SDK and self-hosted deployments.
28
+ :type hostname: str
29
+ :param pathname: Pathname override for SDK and self-hosted deployments as well as version requirements.
30
+ :type pathname: str
31
+ '''
32
+
33
+ def __init__(
34
+ self,
35
+ api_key,
36
+ timeout=120,
37
+ hostname=None,
38
+ pathname=None,
39
+ ):
40
+ self.api_key = api_key
41
+ self.timeout = timeout
42
+ self.hostname = hostname or 'https://api.sapling.ai'
43
+ self.pathname = pathname or '/api/v1/'
44
+ self.url_endpoint = self.hostname + self.pathname
45
+ self.default_session_id = str(uuid.uuid4())
46
+ self.session = requests.Session()
47
+
48
+ def _request(self, url, data):
49
+ '''
50
+ Issues a POST request to the Sapling API and returns the parsed JSON body.
51
+
52
+ :param url: Fully-qualified endpoint URL.
53
+ :type url: str
54
+ :param data: JSON-serializable request body.
55
+ :type data: dict
56
+ :rtype: dict, list, or None
57
+ :raises SaplingError: If the API responds with a non-2xx status code.
58
+ '''
59
+ resp = self.session.post(
60
+ url,
61
+ json=data,
62
+ timeout=self.timeout,
63
+ )
64
+ if not 200 <= resp.status_code < 300:
65
+ raise SaplingError(resp.status_code, resp.text)
66
+ if not resp.content:
67
+ return None
68
+ try:
69
+ return resp.json()
70
+ except ValueError:
71
+ return None
72
+
73
+ def edits(
74
+ self,
75
+ text,
76
+ session_id=None,
77
+ lang=None,
78
+ variety=None,
79
+ medical=None,
80
+ auto_apply=False,
81
+ advanced_edits=None,
82
+ user_id=None,
83
+ is_anon_user=None,
84
+ ):
85
+ '''
86
+ Fetches edits (including for grammar and spelling) for provided text.
87
+
88
+ :param text: Text to process for edits.
89
+ :type text: str
90
+ :param session_id: Unique name or UUID of document or portion of text that is being checked
91
+ :type session_id: str
92
+ :param lang: 2 letter ISO 639-1 language code
93
+ :type lang: str
94
+ :param variety: Specifies regional English variety preference. Defaults to the configuration in the user Sapling dashboard.
95
+ :type variety: str
96
+ :param medical: If true, the backend will apply Sapling's medical dictionary.
97
+ :type medical: bool
98
+ :param auto_apply: Whether to return a field with edits applied to the text
99
+ :type auto_apply: bool
100
+ :param advanced_edits: Additional edit configurations
101
+ :type advanced_edits: dict
102
+ :param user_id: Track IDs representing your end users
103
+ :type user_id: str
104
+ :param is_anon_user: If user_id represents a logged-in or anonymous user
105
+ :type is_anon_user: bool
106
+ :rtype: dict
107
+ :return:
108
+ - edits: List of Edits:
109
+ - sentence: Unedited sentence
110
+ - sentence_start: Offset of sentence from start of text
111
+ - start: Offset of edit start relative to sentence
112
+ - end: Offset of edit end relative to sentence
113
+ - replacement: Suggested replacement
114
+ - error_type: Error type
115
+ - general_error_type: General Error type
116
+ - applied_text: Transformed text if auto_apply is set.
117
+
118
+ Supported languages:
119
+ - `de`: German (Deutsch)
120
+ - `el`: Greek (Ελληνικά)
121
+ - `en`: English (US/UK/CA/AU)
122
+ - `es`: Spanish (Español)
123
+ - `fr`: French (Français) (`fr-fr` and `fr-ca` coming soon)
124
+ - `it`: Italian (Italiano)
125
+ - `jp`: Japanese (日本語)
126
+ - `ko`: Korean (한국어)
127
+ - `nl`: Dutch (Nederlands)
128
+ - `pl`: Polish (Polski)
129
+ - `pt`: Portuguese (Português) (`pt-pt` and `pt-br` coming soon)
130
+ - `sv`: Swedish (Svenska)
131
+ - `tl`: Tagalog
132
+ - `zh`: Chinese (中文)
133
+
134
+ Supported varieties:
135
+ - `us-variety`: American English
136
+ - `gb-variety`: British English
137
+ - `au-variety`: Australian English
138
+ - `ca-variety`: Canadian English
139
+ - `null-variety`: Don't suggest changes based on English variety
140
+
141
+ Supported advanced_edit options:
142
+ - advanced_edits
143
+ - adverbs
144
+ - simplifications
145
+ - hard_to_read
146
+ - qualifiers
147
+ - voice
148
+ - dei
149
+ - gender
150
+ - gender_pronoun
151
+ - gender_noun
152
+ - gender_id
153
+ - sensitivity
154
+ - disability
155
+ - age
156
+ - race
157
+ - social_class
158
+ - violence
159
+ '''
160
+
161
+ url = self.url_endpoint + 'edits'
162
+ session_id = session_id or self.default_session_id
163
+ data = {
164
+ 'key': self.api_key,
165
+ 'text': text,
166
+ 'session_id': session_id,
167
+ }
168
+ if lang is not None:
169
+ data['lang'] = lang
170
+ if variety is not None:
171
+ data['variety'] = variety
172
+ if medical is not None:
173
+ data['medical'] = medical
174
+ if auto_apply is not None:
175
+ data['auto_apply'] = auto_apply
176
+ if advanced_edits is not None:
177
+ data['advanced_edits'] = advanced_edits
178
+
179
+ if user_id is not None:
180
+ data['user_id'] = user_id
181
+ if is_anon_user is not None:
182
+ data['is_anon_user'] = is_anon_user
183
+
184
+ return self._request(url, data)
185
+
186
+ def accept_edit(
187
+ self,
188
+ edit_uuid,
189
+ session_id=None,
190
+ user_id=None,
191
+ ):
192
+ '''
193
+ Use this API endpoint to have Sapling adapt its system over time.
194
+
195
+ Each suggested edit has an edit UUID. You can pass this information back to Sapling to
196
+ indicate the edit suggestion was helpful.
197
+ For each unique edit in each document, use the accept or reject API endpoint only once in total.
198
+
199
+ :param edit_uuid: Opaque UUID of the edit returned from the edits endpoint
200
+ :type edit_uuid: str, uuid
201
+ :param session_id: Unique name or UUID of text that is being processed
202
+ :type session_id: str
203
+ :param user_id: Track IDs representing your end users
204
+ :type user_id: str
205
+ '''
206
+ url = f'{self.url_endpoint}edits/{edit_uuid}/accept'
207
+ session_id = session_id or self.default_session_id
208
+ data = {
209
+ 'key': self.api_key,
210
+ 'session_id': session_id,
211
+ }
212
+
213
+ if user_id is not None:
214
+ data['user_id'] = user_id
215
+
216
+ self._request(url, data)
217
+
218
+ def reject_edit(
219
+ self,
220
+ edit_uuid,
221
+ session_id=None,
222
+ user_id=None,
223
+ ):
224
+ '''
225
+ Use this API endpoint to have Sapling not recommend the same edit anymore.
226
+
227
+ Each suggested edit has an edit UUID. You can pass this information back to Sapling to
228
+ indicate the edit suggestion was not helpful.
229
+ For each unique edit in each document, use the accept or reject API endpoint only once in total.
230
+
231
+ :param edit_uuid: Opaque UUID of the edit returned from the edits endpoint
232
+ :type edit_uuid: str, uuid
233
+ :param session_id: Unique name or UUID of text that is being processed
234
+ :type session_id: str
235
+ :param user_id: Track IDs representing your end users
236
+ :type user_id: str
237
+ '''
238
+ url = f'{self.url_endpoint}edits/{edit_uuid}/reject'
239
+ session_id = session_id or self.default_session_id
240
+ data = {
241
+ 'key': self.api_key,
242
+ 'session_id': session_id,
243
+ }
244
+
245
+ if user_id is not None:
246
+ data['user_id'] = user_id
247
+
248
+ self._request(url, data)
249
+
250
+ def spellcheck(
251
+ self,
252
+ text,
253
+ session_id=None,
254
+ min_length=None,
255
+ multiple_edits=None,
256
+ lang=None,
257
+ auto_apply=False,
258
+ variety=None,
259
+ user_data=None,
260
+ user_id=None,
261
+ is_anon_user=None
262
+ ):
263
+ '''
264
+ Fetches spelling (no grammar or phrase level) edits for provided text.
265
+
266
+ :param text: Text to process for edits.
267
+ :type text: str
268
+ :param session_id: Unique name or UUID of document or portion of text that is being checked
269
+ :type session_id: str
270
+ :param min_length: Default is 3. Minimum character length of words to suggest corrections for. Setting this too low will result in much higher false positives.
271
+ :type min_length: int
272
+ :param multiple_edits: Default is false. If true, will return `candidates` field containing list of other potential corrections for each error.
273
+ :type multiple_edits: bool
274
+ :param lang: Default is English. Specify a language to spellcheck the text against.
275
+ :type lang: str
276
+ :param auto_apply: Whether to return a field with edits applied to the text. Cannot be set with multiple_edits option.
277
+ :type auto_apply: bool
278
+ :param user_data: Optional custom data (e.g. a personal dictionary) to inform spellchecking.
279
+ :type user_data: dict
280
+ :param variety: Specifies regional English variety preference. Defaults to the configuration in the user Sapling dashboard.
281
+ :type variety: str
282
+ :param user_id: Track IDs representing your end users
283
+ :type user_id: str
284
+ :param is_anon_user: If user_id represents a logged-in or anonymous user
285
+ :type is_anon_user: bool
286
+
287
+ :rtype: list[dict]
288
+
289
+ Supported languages:
290
+ - `en`: English
291
+ - `ar`: عربي
292
+ - `bg`: български
293
+ - `ca`: català
294
+ - `cs`: čeština
295
+ - `da`: dansk
296
+ - `de`: Deutsch
297
+ - `el`: Ελληνικά
298
+ - `es`: español
299
+ - `et`: eesti keel
300
+ - `fa`: فارسی
301
+ - `fi`: suomi
302
+ - `fr`: français (`fr-fr` and `fr-ca` coming soon)
303
+ - `he`: עִבְרִית
304
+ - `hi`: हिन्दी",
305
+ - `hr`: hrvatski,
306
+ - `hu`: magyar nyelv
307
+ - `id`: bahasa Indonesia
308
+ - `is`: íslenska
309
+ - `it`: italiano
310
+ - `jp/ja`: 日本語
311
+ - `ko`: 한국어
312
+ - `lt`: lietuvių kalba
313
+ - `lv`: latviešu valoda
314
+ - `nl`: Nederlands
315
+ - `no`: norsk
316
+ - `pl`: polski
317
+ - `pt`: português
318
+ - `ro`: limba română
319
+ - `ru`: русский
320
+ - `sk`: slovenčina
321
+ - `sq`: shqip
322
+ - `sr`: srpski
323
+ - `sv`: svenska
324
+ - `th`: ภาษาไทย
325
+ - `tl`: Tagalog / ᜆᜄᜎᜓᜄ᜔
326
+ - `tr`: Türkçe
327
+ - `uk`: Українська мова
328
+ - `vi`: Tiếng Việt
329
+ - `zh`: 中文
330
+
331
+
332
+ Supported varieties:
333
+ - `us-variety`: American English
334
+ - `gb-variety`: British English
335
+ - `au-variety`: Australian English
336
+ - `ca-variety`: Canadian English
337
+ - `null-variety`: Don't suggest changes based on English variety
338
+
339
+ '''
340
+ url = self.url_endpoint + 'spellcheck'
341
+ session_id = session_id or self.default_session_id
342
+ data = {
343
+ 'key': self.api_key,
344
+ 'text': text,
345
+ 'session_id': session_id,
346
+ }
347
+
348
+ if min_length is not None:
349
+ data['min_length'] = min_length
350
+ if multiple_edits is not None:
351
+ data['multiple_edits'] = multiple_edits
352
+ if lang is not None:
353
+ data['lang'] = lang
354
+ if auto_apply is not None:
355
+ data['auto_apply'] = auto_apply
356
+ if variety is not None:
357
+ data['variety'] = variety
358
+ if user_data is not None:
359
+ data['user_data'] = user_data
360
+
361
+ if user_id is not None:
362
+ data['user_id'] = user_id
363
+ if is_anon_user is not None:
364
+ data['is_anon_user'] = is_anon_user
365
+
366
+ return self._request(url, data)
367
+
368
+
369
+ def complete(
370
+ self,
371
+ query,
372
+ session_id=None,
373
+ ):
374
+ '''
375
+ Provides predictions of the next few characters or words
376
+
377
+ :param query: Text to get completions against.
378
+ :type query: str
379
+ :param session_id: Unique name or UUID of document or portion of text that is being checked
380
+ :type session_id: str
381
+ '''
382
+ url = self.url_endpoint + 'complete'
383
+ session_id = session_id or self.default_session_id
384
+ data = {
385
+ 'key': self.api_key,
386
+ 'query': query,
387
+ 'session_id': session_id,
388
+ }
389
+
390
+ return self._request(url, data)
391
+
392
+ def accept_complete(
393
+ self,
394
+ complete_uuid,
395
+ query,
396
+ completion,
397
+ session_id=None,
398
+ ):
399
+ '''
400
+ Use this API endpoint to have Sapling improve completions over time.
401
+
402
+ Each suggested autocomplete has a UUID. You can pass this information back to Sapling to
403
+ indicate the suggestion was helpful.
404
+
405
+ :param complete_uuid: Opaque UUID of the edit returned from the complete endpoint.
406
+ :type complete_uuid: str, uuid
407
+ :param query: The query text passed to the complete endpoint.
408
+ :type query: str
409
+ :param completion: The suggested completion text returned from the complete endpoint.
410
+ :type completion: str
411
+ '''
412
+ url = f'{self.url_endpoint}complete/{complete_uuid}/accept'
413
+ session_id = session_id or self.default_session_id
414
+ data = {
415
+ 'key': self.api_key,
416
+ 'session_id': session_id,
417
+ 'context': {
418
+ 'query': query,
419
+ 'completion': completion,
420
+ }
421
+ }
422
+ self._request(url, data)
423
+
424
+ def aidetect(
425
+ self,
426
+ text,
427
+ sent_scores=None,
428
+ ):
429
+ '''
430
+ Score a piece of text on how likely it was generated by AI.
431
+
432
+ :param text: Text to score for AI-generated content.
433
+ :type text: str
434
+ :param sent_scores: If true, each sentence will also be scored individually.
435
+ :type sent_scores: bool
436
+
437
+ :rtype: dict
438
+ :return:
439
+ - score: float between 0 and 1, probability that text is AI generated
440
+ - sentence_scores: If sent_scores is set, will return a list of scores per sentence.
441
+ - text: text that was processed
442
+
443
+ '''
444
+ url = f'{self.url_endpoint}aidetect'
445
+ data = {
446
+ 'key': self.api_key,
447
+ 'text': text,
448
+ }
449
+ if sent_scores is not None:
450
+ data['sent_scores'] = sent_scores
451
+ return self._request(url, data)
452
+
453
+ def chunk_text(
454
+ self,
455
+ text,
456
+ max_length,
457
+ step_size=None,
458
+ ):
459
+ '''
460
+ Break an input text into blocks of length of most max_length. When splitting the text, the API follows the following preference stack:
461
+
462
+ page break > paragraph breaks > line breaks > tabs > punctuation > all other whitespace
463
+
464
+ :param text: Text to be chunked
465
+ :type text: str
466
+ :param max_length: Maximum length of text segments.
467
+ :type max_length: integer
468
+ :param step_size: Size of window to look for split points.
469
+ :type step_size: integer
470
+ :rtype: dict
471
+ :return:
472
+ - chunks: List of resulting chunks
473
+ '''
474
+ url = f'{self.url_endpoint}ingest/chunk_text'
475
+ data = {
476
+ 'key': self.api_key,
477
+ 'text': text,
478
+ 'max_length': max_length
479
+ }
480
+ if step_size is not None:
481
+ data['step_size'] = step_size
482
+ return self._request(url, data)
483
+
484
+ def chunk_html(
485
+ self,
486
+ html,
487
+ max_length,
488
+ step_size=None,
489
+ ):
490
+ '''
491
+ Break an input text into blocks of length of most max_length. When splitting the text, the API follows the following preference stack:
492
+
493
+ page break > paragraph breaks > line breaks > tabs > punctuation > all other whitespace
494
+
495
+ Note: This endpoint not only breaks up the HTML but also discards all HTML tags, resulting in plain text.
496
+
497
+ :param html: HTML to be chunked
498
+ :type html: str
499
+ :param max_length: Maximum length of text segments.
500
+ :type max_length: integer
501
+ :param step_size: Size of window to look for split points.
502
+ :type step_size: integer
503
+ :rtype: dict
504
+ :return:
505
+ - chunks: List of resulting chunks representing the segmented text contained within the HTML
506
+ '''
507
+ url = f'{self.url_endpoint}ingest/chunk_html'
508
+ data = {
509
+ 'key': self.api_key,
510
+ 'html': html,
511
+ 'max_length': max_length
512
+ }
513
+ if step_size is not None:
514
+ data['step_size'] = step_size
515
+ return self._request(url, data)
516
+
517
+ def postprocess(
518
+ self,
519
+ text,
520
+ session_id,
521
+ operations,
522
+ ):
523
+ '''
524
+ Performs a variety of operations that are useful for working with the outputs of an NLP (whether human or AI) system. These include:
525
+ - Fixing or restoring punctuation
526
+ - Fixing capitalization
527
+ - Fixing or restoring whitespace
528
+
529
+ Example use cases include repairing transcriptions or captions.
530
+
531
+ :param text: Text to postprocess
532
+ :type text: str
533
+ :param session_id: Unique name or UUID of document or portion of text that is being chunked
534
+ :type text: str
535
+ :param operations: Operations to apply. The currently accepted operations are:
536
+ - capitalize
537
+ - punctuate
538
+ - fixspaces
539
+
540
+ :type operations: list[str]
541
+ :rtype: list[dict]
542
+ :return:
543
+ Same as the edits endpoint:
544
+ - sentence: Unedited sentence
545
+ - sentence_start: Offset of sentence from start of text
546
+ - start: Offset of edit start relative to sentence
547
+ - end: Offset of edit end relative to sentence
548
+ - replacement: Suggested replacement
549
+ - error_type: Error type
550
+ - general_error_type: General Error type
551
+ '''
552
+ url = f'{self.url_endpoint}postprocess'
553
+ data = {
554
+ 'key': self.api_key,
555
+ 'text': text,
556
+ 'session_id': session_id,
557
+ 'operations': operations,
558
+ }
559
+ return self._request(url, data)
560
+
561
+ def rephrase(
562
+ self,
563
+ text,
564
+ mapping=None,
565
+ tone_mapping=None,
566
+ tense_mapping=None,
567
+ num_results=None,
568
+ session_id=None,
569
+ ):
570
+ '''
571
+ Rephrases the input text, optionally applying a style transformation.
572
+
573
+ Given an input sentence, returns output sentences that preserve meaning
574
+ but use alternative phrasings or styles.
575
+
576
+ :param text: Text to rephrase. Current maximum length is 400 characters.
577
+ :type text: str
578
+ :param mapping: The transformation to apply. Defaults to `paraphrase`.
579
+ Options include: `paraphrase`, `informal_to_formal`, `passive_to_active`,
580
+ `active_to_passive`, `sentence_split`, `expand`, and `switch_tone`.
581
+ :type mapping: str
582
+ :param tone_mapping: Target tone when `mapping` is `switch_tone`. Options
583
+ include: `straightforward`, `confident`, `friendly`, and `empathetic`.
584
+ :type tone_mapping: str
585
+ :param tense_mapping: Target tense transformation, when applicable.
586
+ :type tense_mapping: str
587
+ :param num_results: Number of results to return (currently only for
588
+ `paraphrase`). Minimum 1, maximum 8. Defaults to 5.
589
+ :type num_results: int
590
+ :param session_id: Unique name or UUID of document or portion of text that is being processed
591
+ :type session_id: str
592
+ :rtype: dict
593
+ :return:
594
+ - results: List of rephrases, each with `original`, `replacement`,
595
+ `rephrase_type`, `model_version`, and `hash`.
596
+ '''
597
+ url = self.url_endpoint + 'rephrase'
598
+ session_id = session_id or self.default_session_id
599
+ data = {
600
+ 'key': self.api_key,
601
+ 'text': text,
602
+ 'session_id': session_id,
603
+ }
604
+ if mapping is not None:
605
+ data['mapping'] = mapping
606
+ if tone_mapping is not None:
607
+ data['tone_mapping'] = tone_mapping
608
+ if tense_mapping is not None:
609
+ data['tense_mapping'] = tense_mapping
610
+ if num_results is not None:
611
+ data['num_results'] = num_results
612
+ return self._request(url, data)
613
+
614
+ def summarize(
615
+ self,
616
+ text,
617
+ ):
618
+ '''
619
+ Summarizes a longer document into a shorter, more digestible one.
620
+
621
+ :param text: Input document to summarize.
622
+ :type text: str
623
+ :rtype: dict
624
+ :return:
625
+ - result: The summarized text.
626
+ '''
627
+ url = self.url_endpoint + 'summarize'
628
+ data = {
629
+ 'key': self.api_key,
630
+ 'text': text,
631
+ }
632
+ return self._request(url, data)
633
+
634
+ def tone(
635
+ self,
636
+ text,
637
+ ):
638
+ '''
639
+ Detects the tone of the provided text across 28 fine-grained categories.
640
+
641
+ The overall tone is returned along with the tone for each sentence.
642
+
643
+ :param text: Text to analyze the tone for.
644
+ :type text: str
645
+ :rtype: dict
646
+ :return:
647
+ - sents: The sentences the text contains.
648
+ - overall: List of ``(probability, tone, emoji)`` tuples for the whole text.
649
+ - results: For each sentence, a list of ``(probability, tone, emoji)`` tuples.
650
+ '''
651
+ url = self.url_endpoint + 'tone'
652
+ data = {
653
+ 'key': self.api_key,
654
+ 'text': text,
655
+ }
656
+ return self._request(url, data)
657
+
658
+ def sentiment(
659
+ self,
660
+ text,
661
+ ):
662
+ '''
663
+ Detects the sentiment (positive, negative, or neutral) of the provided text.
664
+
665
+ The overall sentiment is returned along with the sentiment for each sentence.
666
+
667
+ :param text: Text to analyze the sentiment for.
668
+ :type text: str
669
+ :rtype: dict
670
+ :return:
671
+ - sents: The sentences the text contains.
672
+ - overall: List of ``(probability, sentiment)`` tuples for the whole text.
673
+ - results: For each sentence, a list of ``(probability, sentiment)`` tuples.
674
+ '''
675
+ url = self.url_endpoint + 'sentiment'
676
+ data = {
677
+ 'key': self.api_key,
678
+ 'text': text,
679
+ }
680
+ return self._request(url, data)
681
+
682
+ def quality(
683
+ self,
684
+ text,
685
+ ):
686
+ '''
687
+ Computes a quality score for the provided text based on how "surprising"
688
+ the text is to the model. Lower surprisal corresponds to higher scores.
689
+
690
+ :param text: Text to compute a quality score for.
691
+ :type text: str
692
+ :rtype: dict
693
+ :return:
694
+ - score: A score from 1 (low quality) to 5 (high quality).
695
+ '''
696
+ url = self.url_endpoint + 'quality'
697
+ data = {
698
+ 'key': self.api_key,
699
+ 'text': text,
700
+ }
701
+ return self._request(url, data)
702
+
703
+ def langdetect(
704
+ self,
705
+ text,
706
+ ):
707
+ '''
708
+ Identifies the language of the provided text.
709
+
710
+ :param text: Text to identify the language for.
711
+ :type text: str
712
+ :rtype: dict
713
+ :return:
714
+ - lang: The detected language code.
715
+ - conf: Confidence score for the detection result.
716
+ '''
717
+ url = self.url_endpoint + 'langdetect'
718
+ data = {
719
+ 'key': self.api_key,
720
+ 'text': text,
721
+ }
722
+ return self._request(url, data)
723
+
724
+ def profanity(
725
+ self,
726
+ text,
727
+ ):
728
+ '''
729
+ Checks the provided text for profanity, returning a 0/1 label per token.
730
+
731
+ :param text: Text to check for profanity.
732
+ :type text: str
733
+ :rtype: dict
734
+ :return:
735
+ - toks: The tokens (words) detected in the text.
736
+ - labels: For each token, 0 (not profanity) or 1 (profanity).
737
+ '''
738
+ url = self.url_endpoint + 'profanity'
739
+ data = {
740
+ 'key': self.api_key,
741
+ 'text': text,
742
+ }
743
+ return self._request(url, data)
sapling/version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = '4.1.0'
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: sapling-py
3
+ Version: 4.1.0
4
+ Summary: Sapling Python Client
5
+ Home-page: https://sapling.ai
6
+ Author: Sapling Intelligence
7
+ Author-email: info@sapling.ai
8
+ License: Apache License 2.0
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Requires-Python: >=3.7
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: requests
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest; extra == "test"
19
+ Requires-Dist: responses; extra == "test"
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: description-content-type
25
+ Dynamic: home-page
26
+ Dynamic: license
27
+ Dynamic: license-file
28
+ Dynamic: provides-extra
29
+ Dynamic: requires-dist
30
+ Dynamic: requires-python
31
+ Dynamic: summary
32
+
33
+ # Sapling Python Client
34
+
35
+ Python SDK wrapper for the [Sapling.ai API](https://sapling.ai/docs).
36
+
37
+ Try our [grammar check demo](https://sapling.ai/grammar-check).
38
+ Compare against leading grammar checking tools and APIs like Grammarly (Grammerly), LanguageTool, ProWritingAid and Ginger.
39
+
40
+ ## Overview
41
+
42
+ Sapling is a toolkit for helping developers build language model-powered applications.
43
+ The API provides spelling and grammar checking, autocomplete, tone detection, rephrasing, AI detection, and more.
44
+
45
+ Key Features:
46
+ - **60% More Corrections**: Outperforms [competing solutions](https://sapling.ai/comparison/api#sapling) at similar accuracy levels using state-of-the-art generative AI models.
47
+ - **Real-Time Performance**: Experience the same low-latency corrections as Sapling's native integrations.
48
+ - **Comprehensive Error Detection**: Identifies over 20 error types including prepositions, noun forms, verb tense, with both high-level and fine-grained error information.
49
+ - **Domain-Specific Models**: Get corrections optimized for your content type, from academic writing, to doctors notes, to user-generated reviews.
50
+ - **Enterprise-Grade Security**: Features include no data retention policies, [self-hosted/on-premises](https://sapling.ai/onprem) deployment options, and enterprise-grade [security policies and procedures](https://sapling.ai/security).
51
+ - **Rich Text Editor Integration**: Supports TinyMCE, CKEditor, QuillJS, Trix, ProseMirror, WordPress, Draft.js, Froala, Lexical and more. For web-based editors, consider using our [JavaScript SDK](https://sapling.ai/docs/sdk/JavaScript/quickstart) for display UI components.
52
+
53
+ ## Installation
54
+
55
+ Install the `sapling-py` package with [pip](https://pip.pypa.io/en/stable/installation/)
56
+
57
+ ```
58
+ python -m pip install sapling-py
59
+ ```
60
+
61
+ ## Documentation
62
+ Documentation for the client is available at [Read the Docs](https://sapling.readthedocs.io/) and
63
+ documentation for the HTTP API is available at [Sapling.ai](https://sapling.ai/docs).
64
+
65
+ ## Quickstart
66
+
67
+ - Register for an account at [Sapling.ai](https://sapling.ai).
68
+ - After registering and signing in, generate a development API key in your [dashboard](https://sapling.ai/user_settings).
69
+ - Install the Python client by following the installation steps above.
70
+
71
+ ```python
72
+ from sapling import SaplingClient
73
+
74
+ API_KEY = '<YOUR_API_KEY>'
75
+ client = SaplingClient(api_key=API_KEY)
76
+ edits = client.edits('Lets get started!', session_id='test_session')
77
+ ```
78
+
79
+ The result should be an array of edits of this form:
80
+
81
+ ```json
82
+ [{
83
+ "id": "aa5ee291-a073-5146-8ebc-c9c899d01278",
84
+ "sentence": "Lets get started!",
85
+ "sentence_start": 0,
86
+ "start": 0,
87
+ "end": 4,
88
+ "replacement": "Let's",
89
+ "error_type": "R:OTHER",
90
+ "general_error_type": "Other",
91
+ }]
92
+ ```
93
+
94
+ Get a production key by following [this documentation](https://sapling.ai/docs/api/api-access).
95
+
96
+ Here's some more information on [request options and response structure](https://sapling.ai/docs/api/edits-overview).
97
+
98
+ ## License
99
+
100
+ Copyright 2024--present Sapling Intelligence, Inc.
101
+
102
+ Licensed under the Apache License, Version 2.0.
@@ -0,0 +1,8 @@
1
+ sapling/__init__.py,sha256=Fbgr7l2gvBTdhNUp_gLr8GAgFA-5dot1IpBsURxmRY8,162
2
+ sapling/client.py,sha256=GQDup8fLwExrGuGUvoO2ork13HvPXRZFWDow3GMfYFc,24994
3
+ sapling/version.py,sha256=_fosQb59FTQQCtQqbaLmneA_xX6SrQbaKaEobCMMzGk,22
4
+ sapling_py-4.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
5
+ sapling_py-4.1.0.dist-info/METADATA,sha256=9k6Y6ZsB7YLHntz9iOXQ1okpfVMQwSY0yUrOUbpSMnQ,3957
6
+ sapling_py-4.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
7
+ sapling_py-4.1.0.dist-info/top_level.txt,sha256=MHKGXD8i2vBIWWvWyRgPzoT15juqU2qsCfabvBSRw2E,8
8
+ sapling_py-4.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ sapling