16 private $api_url =
'https://api-inference.huggingface.co/models/';
17 private $supported_languages = [
25 public function __construct($options)
31 if (is_array($options)) {
32 $this->api_token = $options[
'api_token'] ??
'';
33 }
else if (is_string($options)) {
34 $values = explode(
'|', $options);
35 $this->api_token = trim($values[0] ??
'');
39 if (!empty($this->api_token) && !preg_match(
'/^hf_/', $this->api_token)) {
46 public function processRequest($content, $type, $sourceLang =
'', $targetLang =
'')
48 if (empty($content)) {
49 throw new Exception(_MB_LEGACY_BLOCK_AI_NO_CONTENT);
56 $model =
"facebook/mbart-large-50-many-to-many-mmt";
59 $mbartSourceLang = $this->getMbartLangCode($sourceLang);
60 $mbartTargetLang = $this->getMbartLangCode($targetLang);
65 'src_lang' => $mbartSourceLang,
66 'tgt_lang' => $mbartTargetLang
74 $model =
"facebook/bart-large-cnn";
84 $model =
"facebook/bart-large-cnn";
87 'parameters' => [
'max_length' => 100]
91 $result = $this->callHuggingFace($model, $data);
97 if (is_array($result)) {
99 if (isset($result[
'generated_text'])) {
100 return $result[
'generated_text'];
103 if (isset($result[0])) {
104 foreach([
'summary_text',
'translation_text',
'generated_text'] as $key) {
105 if (isset($result[0][$key])) {
106 return $result[0][$key];
111 return json_encode($result);
115 return (
string)$result;
117 }
catch (Exception $e) {
120 throw new Exception(_MB_LEGACY_BLOCK_AI_ERROR .
': ' . $e->getMessage());
125 private function getMbartLangCode($langCode) {
134 return $mbartMap[$langCode] ??
'en_XX';
137 private function callHuggingFace($model, $data)
139 if (empty($this->api_token)) {
142 throw new Exception(_MB_LEGACY_BLOCK_AI_NO_TOKEN);
145 $url = $this->api_url . $model;
153 $ch = curl_init($url);
154 curl_setopt_array($ch, [
155 CURLOPT_RETURNTRANSFER =>
true,
156 CURLOPT_POST =>
true,
157 CURLOPT_POSTFIELDS => json_encode($data),
158 CURLOPT_HTTPHEADER => [
159 'Authorization: Bearer ' . $this->api_token,
160 'Content-Type: application/json',
161 'Accept: application/json',
162 'Origin: ' . (isset($_SERVER[
'HTTPS']) ?
'https://' :
'http://') . $_SERVER[
'HTTP_HOST']
165 CURLOPT_SSL_VERIFYPEER =>
false,
166 CURLOPT_SSL_VERIFYHOST => 0,
167 CURLOPT_TIMEOUT => 30,
169 CURLOPT_VERBOSE =>
true
173 $verbose = fopen(
'php://temp',
'w+');
174 curl_setopt($ch, CURLOPT_STDERR, $verbose);
176 $response = curl_exec($ch);
177 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
178 $error = curl_error($ch);
182 $verboseLog = stream_get_contents($verbose);
192 throw new Exception(
"cURL Error: " . $error);
196 if ($httpCode !== 200) {
201 throw new Exception(_MB_LEGACY_BLOCK_AI_ERROR);
204 throw new Exception(_MB_LEGACY_BLOCK_AI_ERROR);
207 throw new Exception(_MB_LEGACY_BLOCK_AI_ERROR);
210 throw new Exception(_MB_LEGACY_BLOCK_AI_ERROR);
214 $result = json_decode($response,
true);
215 if (json_last_error() !== JSON_ERROR_NONE) {
286 $result = $aiBlock->processRequest($content, $action, $sourceLang, $targetLang);