-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSharpApiService.php
More file actions
838 lines (765 loc) · 25.2 KB
/
SharpApiService.php
File metadata and controls
838 lines (765 loc) · 25.2 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
<?php
declare(strict_types=1);
namespace SharpAPI\SharpApiService;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use SharpAPI\SharpApiService\Dto\JobDescriptionParameters;
use SharpAPI\SharpApiService\Dto\SharpApiJob;
use SharpAPI\SharpApiService\Dto\SharpApiSubscriptionInfo;
use SharpAPI\SharpApiService\Enums\SharpApiJobStatusEnum;
use SharpAPI\SharpApiService\Enums\SharpApiJobTypeEnum;
use Spatie\Url\Url;
/**
* Main Service to dispatch AI jobs to SharpAPI.com
* @api
*/
class SharpApiService
{
protected string $apiBaseUrl;
protected string $apiKey;
// how many seconds the client should wait between each result request
// usually Retry-After header is used (default 10s), this value won't have an effect unless
// $useCustomInterval is set to TRUE
protected int $apiJobStatusPollingInterval = 10;
protected bool $useCustomInterval = false;
// how long (in seconds) the client should wait in polling mode for results
protected int $apiJobStatusPollingWait = 180;
protected string $userAgent;
/**
* Initializes a new instance of the class.
*
* @throws InvalidArgumentException if the API key is empty.
*/
public function __construct(string $apiKey, ?string $apiBaseUrl = null, ?string $userAgent = null)
{
$this->setApiKey($apiKey);
if (empty($this->apiKey)) {
throw new InvalidArgumentException('API key is required.');
}
$this->setApiBaseUrl($apiBaseUrl ?? 'https://sharpapi.com/api/v1');
$this->setUserAgent($userAgent ?? 'SharpAPIPHPAgent/1.2.0');
}
/**
* Fetch the main API URL
* @return string
*/
public function getApiBaseUrl(): string
{
return $this->apiBaseUrl;
}
/**
* Might come in handy if case some API mocking is needed
* @param string $apiBaseUrl
* @return void
*/
public function setApiBaseUrl(string $apiBaseUrl): void
{
$this->apiBaseUrl = $apiBaseUrl;
}
public function getApiKey(): string
{
return $this->apiKey;
}
public function setApiKey(string $apiKey): void
{
$this->apiKey = $apiKey;
}
public function getUserAgent(): string
{
return $this->userAgent;
}
/**
* Handy method to set custom User-Agent header for Affiliate Program members.
*
* More at: https://sharpapi.com/affiliate_program
*/
public function setUserAgent(string $userAgent): void
{
$this->userAgent = $userAgent;
}
public function getApiJobStatusPollingInterval(): int
{
return $this->apiJobStatusPollingInterval;
}
/**
* @param int $apiJobStatusPollingInterval
* @return void
* @api
*/
public function setApiJobStatusPollingInterval(int $apiJobStatusPollingInterval): void
{
$this->apiJobStatusPollingInterval = $apiJobStatusPollingInterval;
}
public function isUseCustomInterval(): bool
{
return $this->useCustomInterval;
}
/**
* @param bool $useCustomInterval
* @return void
* @api
*/
public function setUseCustomInterval(bool $useCustomInterval): void
{
$this->useCustomInterval = $useCustomInterval;
}
public function getApiJobStatusPollingWait(): int
{
return $this->apiJobStatusPollingWait;
}
/**
* @param int $apiJobStatusPollingWait
* @return void
* @api
*/
public function setApiJobStatusPollingWait(int $apiJobStatusPollingWait): void
{
$this->apiJobStatusPollingWait = $apiJobStatusPollingWait;
}
/**
* Generic request method to run Guzzle client
*
* @throws GuzzleException
*/
private function makeRequest(
string $method,
string $url,
array $data = [],
string $filePath = null
): ResponseInterface
{
$client = new Client();
$options = [
'headers' => $this->getHeaders(),
];
if ($method === 'POST') {
if (is_string($filePath) && strlen($filePath)) {
$options['multipart'][] =
[
'name' => 'file',
'contents' => file_get_contents($filePath),
'filename' => basename($filePath),
];
} else {
$options['json'] = $data;
}
}
return $client->request($method, $this->getApiBaseUrl() . $url, $options);
}
private function parseStatusUrl(ResponseInterface $response)
{
return json_decode($response->getBody()->__toString(), true)['status_url'];
}
/**
* Generic method to check job status in polling mode and then fetch results of the dispatched job
*
* @throws ClientException|GuzzleException
*
* @api
*/
public function fetchResults(string $statusUrl): SharpApiJob
{
$client = new Client();
$waitingTime = 0;
do {
$response = $client->request(
'GET',
$statusUrl,
['headers' => $this->getHeaders()]
);
$jobStatus = json_decode($response->getBody()->__toString(), true)['data']['attributes'];
if (
$jobStatus['status'] === SharpApiJobStatusEnum::SUCCESS->value
||
$jobStatus['status'] === SharpApiJobStatusEnum::FAILED->value
) {
break;
} // it's still `pending` status, let's wait a bit more
$retryAfter = isset($response->getHeader('Retry-After')[0])
? (int)$response->getHeader('Retry-After')[0]
: $this->getApiJobStatusPollingInterval(); // fallback if no Retry-After header
if ($this->isUseCustomInterval()) {
// let's force to use the value from config
$retryAfter = $this->getApiJobStatusPollingInterval();
}
$waitingTime = $waitingTime + $retryAfter;
if ($waitingTime >= $this->getApiJobStatusPollingWait()) {
break;
} // otherwise wait a bit more and try again
sleep($retryAfter);
} while (true);
$data = json_decode($response->getBody()->__toString(), true)['data'];
$url = Url::fromString($statusUrl);
if (count($url->getSegments()) == 5) { // shared job result URL
$result = (object) json_decode($data['attributes']['result']);
} else { // 7 segments, 1-to-1 job to result url
$result = (object) $data['attributes']['result'];
}
return new SharpApiJob(
id: $data['id'],
type: $data['attributes']['type'],
status: $data['attributes']['status'],
result: $result ?? null
);
}
/**
* Prepare shared headers
*
* @return string[]
*/
private function getHeaders(): array
{
return [
'Authorization' => 'Bearer ' . $this->getApiKey(),
'Accept' => 'application/json',
'User-Agent' => $this->getUserAgent()
];
}
/**
* Simple PING endpoint to check the availability of the API and its internal time zone (timestamp).
* {
* "ping": "pong",
* "timestamp": "2024-03-12T08:50:11.188308Z"
* }
*
* @throws GuzzleException
*
* @api
*/
public function ping(): ?array
{
$response = $this->makeRequest('GET', '/ping');
return json_decode($response->getBody()->__toString(), true);
}
/**
* Endpoint to check details regarding the subscription's current period
*
* "subscription_words_used_percentage" is a percentage of current monthly quota usage
* and might serve as an alert to the user of the depleted credits.
* With a value above 80%, it's advised to subscribe to more credits
* at https://sharpapi.com/dashboard/credits to avoid service disruption.
*
* These values are also available in the Dashboard at https://sharpapi.com/dashboard
*
* @throws GuzzleException
*
* @api
*/
public function quota(): ?SharpApiSubscriptionInfo
{
$response = $this->makeRequest('GET', '/quota');
$info = json_decode($response->getBody()->__toString(), true);
if (!array_key_exists('timestamp', $info)) {
return null;
}
return new SharpApiSubscriptionInfo(
timestamp: new Carbon($info['timestamp']),
on_trial: $info['on_trial'],
trial_ends: new Carbon($info['trial_ends']),
subscribed: $info['subscribed'],
current_subscription_start: new Carbon($info['current_subscription_start']),
current_subscription_end: new Carbon($info['current_subscription_end']),
subscription_words_quota: $info['subscription_words_quota'],
subscription_words_used: $info['subscription_words_used'],
subscription_words_used_percentage: $info['subscription_words_used_percentage']
);
}
/**
* Parses a resume (CV) file from multiple formats (PDF/DOC/DOCX/TXT/RTF)
* and returns an extensive JSON object of data points.
*
* An optional language parameter can also be provided (`English` value is set as the default one) .
*
* @param string $filePath The path to the resume file.
* @param string|null $language The language of the resume file. Defaults to 'English'.
* @return string The parsed data or an error message.
*
* @throws GuzzleException
*
* @api
*/
public function parseResume(
string $filePath,
?string $language = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::HR_PARSE_RESUME->url(),
['language' => $language],
$filePath
);
return $this->parseStatusUrl($response);
}
/**
* Generates a job description based on a set of parameters
* provided via JobDescriptionParameters DTO object.
* This endpoint provides concise job details in the response format,
* including the short description, job requirements, and job responsibilities.
*
* Only the job position `name` parameter is required inside $jobDescriptionParameters
*
* @throws GuzzleException
*
* @api
*/
public function generateJobDescription(JobDescriptionParameters $jobDescriptionParameters): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::HR_JOB_DESCRIPTION->url(),
$jobDescriptionParameters->toArray());
return $this->parseStatusUrl($response);
}
/**
* Generates a list of related skills with their weights as a float value (1.0-10.0)
* where 10 equals 100%, the highest relevance score.
*
* @throws GuzzleException
*
* @api
*/
public function relatedSkills(
string $skillName,
?string $language = null,
?int $maxQuantity = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::HR_RELATED_SKILLS->url(),
[
'content' => $skillName,
'language' => $language,
'max_quantity' => $maxQuantity,
]);
return $this->parseStatusUrl($response);
}
/**
* Generates a list of related job positions with their weights as float value (1.0-10.0)
* where 10 equals 100%, the highest relevance score.
*
* @throws GuzzleException
*
* @api
*/
public function relatedJobPositions(
string $jobPositionName,
?string $language = null,
?int $maxQuantity = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::HR_RELATED_JOB_POSITIONS->url(),
[
'content' => $jobPositionName,
'language' => $language,
'max_quantity' => $maxQuantity,
]);
return $this->parseStatusUrl($response);
}
/**
* Parses the customer's product review and provides its sentiment (POSITIVE/NEGATIVE/NEUTRAL)
* with a score between 0-100%. Great for sentiment report processing for any online store.
*
* @throws GuzzleException
*
* @api
*/
public function productReviewSentiment(string $review): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::ECOMMERCE_REVIEW_SENTIMENT->url(),
['content' => $review]
);
return $this->parseStatusUrl($response);
}
/**
* Generates a list of suitable categories for the product with relevance weights as a float value (1.0-10.0)
* where 10 equals 100%, the highest relevance score. Provide the product name and its parameters
* to get the best category matches possible. Comes in handy with populating
* product catalogue data and bulk products' processing.
*
* @throws GuzzleException
*
* @api
*/
public function productCategories(
string $productName,
?string $language = null,
?int $maxQuantity = null,
?string $voiceTone = null,
?string $context = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::ECOMMERCE_PRODUCT_CATEGORIES->url(),
[
'content' => $productName,
'language' => $language,
'max_quantity' => $maxQuantity,
'voice_tone' => $voiceTone,
'context' => $context,
]);
return $this->parseStatusUrl($response);
}
/**
* Generates a shorter version of the product description.
* Provide as many details and parameters of the product to get the best marketing introduction possible.
* Comes in handy with populating product catalog data and bulk products processing.
*
* @throws GuzzleException
*
* @api
*/
public function generateProductIntro(
string $productData,
?string $language = null,
?int $maxLength = null,
?string $voiceTone = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::ECOMMERCE_PRODUCT_INTRO->url(),
[
'content' => $productData,
'language' => $language,
'max_length' => $maxLength,
'voice_tone' => $voiceTone,
]);
return $this->parseStatusUrl($response);
}
/**
* Generates a personalized thank-you email to the customer after the purchase.
* The response content does not contain the title, greeting or sender info at the end,
* so you can personalize the rest of the email easily.
*
* @throws GuzzleException
*
* @api
*/
public function generateThankYouEmail(
string $productName,
?string $language = null,
?int $maxLength = null,
?string $voiceTone = null,
?string $context = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::ECOMMERCE_THANK_YOU_EMAIL->url(),
[
'content' => $productName,
'language' => $language,
'max_length' => $maxLength,
'voice_tone' => $voiceTone,
'context' => $context,
]);
return $this->parseStatusUrl($response);
}
/**
* Parses the provided text for any phone numbers and returns the original detected version and its E.164 format.
* Might come in handy in the case of processing and validating big chunks of data against phone numbers
* or f.e. if you want to detect phone numbers in places where they're not supposed to be.
*
* @throws GuzzleException
*
* @api
*/
public function detectPhones(string $text): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::CONTENT_DETECT_PHONES->url(),
['content' => $text]
);
return $this->parseStatusUrl($response);
}
/**
* Parses the provided text for any possible emails. Might come in handy in case of processing and validating
* big chunks of data against email addresses or f.e. if you want to detect emails in places
* where they're not supposed to be.
*
* @throws GuzzleException
*
* @api
*/
public function detectEmails(string $text): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::CONTENT_DETECT_EMAILS->url(),
['content' => $text]
);
return $this->parseStatusUrl($response);
}
/**
* Parses the provided text for any possible spam content.
* It returns
*
* @throws GuzzleException
*
* @api
*/
public function detectSpam(string $text): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::CONTENT_DETECT_SPAM->url(),
['content' => $text]
);
return $this->parseStatusUrl($response);
}
/**
* Generates a summarized version of the provided content.
* Perfect for generating marketing introductions of longer texts.
*
* @throws GuzzleException
*
* @api
*/
public function summarizeText(
string $text,
?string $language = null,
?int $maxLength = null,
?string $voiceTone = null,
?string $context = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::CONTENT_SUMMARIZE->url(),
[
'content' => $text,
'language' => $language,
'max_length' => $maxLength,
'voice_tone' => $voiceTone,
'context' => $context,
]);
return $this->parseStatusUrl($response);
}
/**
* Generates a list of unique keywords/tags based on the provided content.
*
* @throws GuzzleException
*
* @api
*/
public function generateKeywords(
string $text,
?string $language = null,
?int $maxQuantity = null,
?string $voiceTone = null,
?string $context = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::CONTENT_KEYWORDS->url(),
[
'content' => $text,
'language' => $language,
'max_quantity' => $maxQuantity,
'voice_tone' => $voiceTone,
'context' => $context,
]);
return $this->parseStatusUrl($response);
}
/**
* Translates the provided text into selected language
* Perfect for generating marketing introductions of longer texts.
*
* @throws GuzzleException
*
* @api
*/
public function translate(
string $text,
string $language,
?string $voiceTone = null,
?string $context = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::CONTENT_TRANSLATE->url(),
[
'content' => $text,
'language' => $language,
'voice_tone' => $voiceTone,
'context' => $context,
]);
return $this->parseStatusUrl($response);
}
/**
* Generates a paraphrased version of the provided text.
* Only the `content` parameter is required. You can define the output language,
* maximum character length, and tone of voice. Additional instructions
* on how to process the text can be provided in the context parameter.
* Please keep in mind that `max_length` serves as a strong suggestion
* for the Language Model, rather than a strict requirement,
* to maintain the general sense of the outcome.
* You can set your preferred writing style by providing an optional `voice_tone` parameter.
* It can be adjectives like `funny` or `joyous`, or even the name of a famous writer.
* This API method also provides an optional context parameter,
* which can be used to supply additional flexible instructions for content processing.
*
* @throws GuzzleException
*
* @api
*/
public function paraphrase(
string $text,
?string $language = null,
?int $maxLength = null,
?string $voiceTone = null,
?string $context = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::CONTENT_PARAPHRASE->url(),
[
'content' => $text,
'language' => $language,
'max_length' => $maxLength,
'voice_tone' => $voiceTone,
'context' => $context,
]);
return $this->parseStatusUrl($response);
}
/**
* Proofreads (and checks grammar) of the provided text.
*
* @throws GuzzleException
*
* @api
*/
public function proofread(string $text): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::CONTENT_PROOFREAD->url(),
['content' => $text]
);
return $this->parseStatusUrl($response);
}
/**
* Generates all most important META tags based on the content provided.
* Make sure to include link to the website and pictures URL to get as many tags populated as possible.
*
* @throws GuzzleException
*
* @api
*/
public function generateSeoTags(
string $text,
?string $language = null,
?string $voiceTone = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::SEO_GENERATE_TAGS->url(),
[
'content' => $text,
'language' => $language,
'voice_tone' => $voiceTone,
]);
return $this->parseStatusUrl($response);
}
/**
* Parses the Travel/Hospitality product review and provides its sentiment (POSITIVE/NEGATIVE/NEUTRAL)
* with a score between 0-100%. Great for sentiment report processing for any online store.
*
* @throws GuzzleException
*
* @api
*/
public function travelReviewSentiment(string $text): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::TTH_REVIEW_SENTIMENT->url(),
['content' => $text]
);
return $this->parseStatusUrl($response);
}
/**
* Generates a list of suitable categories for the Tours & Activities product
* with relevance weights as float value (1.0-10.0) where 10 equals 100%, the highest relevance score.
* Provide the product name and its parameters to get the best category matches possible.
* Comes in handy with populating product catalogue data and bulk product processing.
*
* @throws GuzzleException
*
* @api
*/
public function toursAndActivitiesProductCategories(
string $productName,
?string $city = null,
?string $country = null,
?string $language = null,
?int $maxQuantity = null,
?string $voiceTone = null,
?string $context = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::TTH_TA_PRODUCT_CATEGORIES->url(),
[
'content' => $productName,
'city' => $city,
'country' => $country,
'language' => $language,
'max_quantity' => $maxQuantity,
'voice_tone' => $voiceTone,
'context' => $context,
]);
return $this->parseStatusUrl($response);
}
/**
* Generates a list of suitable categories for the Hospitality type product
* with relevance weights as float value (1.0-10.0) where 10 equals 100%, the highest relevance score.
* Provide the product name and its parameters to get the best category matches possible.
* Comes in handy with populating products catalogs data and bulk products' processing.
*
* @throws GuzzleException
*
* @api
*/
public function hospitalityProductCategories(
string $productName,
?string $city = null,
?string $country = null,
?string $language = null,
?int $maxQuantity = null,
?string $voiceTone = null,
?string $context = null
): string
{
$response = $this->makeRequest(
'POST',
SharpApiJobTypeEnum::TTH_HOSPITALITY_PRODUCT_CATEGORIES->url(),
[
'content' => $productName,
'city' => $city,
'country' => $country,
'language' => $language,
'max_quantity' => $maxQuantity,
'voice_tone' => $voiceTone,
'context' => $context,
]);
return $this->parseStatusUrl($response);
}
}