Ron

 
<<< Назад

Yandex TTS и голос Алисы на украинском, русском, английском

Используем весь потенциал Yandex SpeechKit Cloud.
Вру - турецкий не ставил, а накой он нам? )
Алиска разговаривает на явно указанном языке.

Напоминаю, что при очередном апдейте модуля из маркета все это слетит нахрен, если только Сергей код сам не исправит по образу и подобию в репозитарии модулей.

Короче лезем по 2-м путям и вместо того что там есть (весь код там) грохаем в теле и меняем на тот что тут положил

1-й путь - /var/www/html/templates/yandex_tts
Открываем в редакторе action_admin.html все грохаем и копи-пастом вставляем код

[#if VIEW_MODE="search_yandex_tts" || VIEW_MODE=""#]

[#if OK#]
   <div class="alert alert-success"><#LANG_DATA_SAVED#></div>
[#endif OK#]

<!-- table zwave_devices search -->
<div id='api_settings'>
<form action="/index.php?pd=bWVtYmVyczp7aWQ9MjcxMSx2aWV3X21vZGU9YmxvZ19pdGVtLGFjdGlvbj1wcm9maWxlfQ%3D%3Dpz_YXBwbGljYXRpb246e2FjdGlvbj1wcm9maWxlfQ%3D%3Dpz_&md=members&inst=&" method="post" enctype="multipart/form-data" name="frmEdit" class="form-horizontal">
<fieldset>
<div class="form-group">
 <label class="control-label"> Yandex API key: (*) </label>
 <div class="col-lg-6"><input type="text" class="form-control" name="access_key" value="[#ACCESS_KEY#]" class="input"></div>
</div>

<div class="form-group">
 <label class="control-label"> Выберите голос: </label>
 <div class="col-lg-6">
<select class="form-control" name="speaker">
 <optgroup label="Женские голоса">
    <option value="jane" [#if SPEAKER=="jane"#] selected[#endif#]>Джейн</option>
    <option value="oksana" [#if SPEAKER=="oksana"#] selected[#endif#]>Оксана</option>
    <option value="alyss" [#if SPEAKER=="alyss"#] selected[#endif#]>Алиса</option>
    <option value="omazh"[#if SPEAKER=="omazh"#] selected[#endif#]>Омаж</option>
</optgroup>
 <optgroup label="Мужские голоса">
    <option value="zahar" [#if SPEAKER=="zahar"#] selected[#endif#]>Захар</option>
    <option value="ermil" [#if SPEAKER=="ermil"#] selected[#endif#]>Ермил</option>
</optgroup>
   </select>
</div>
</div>
<div class="form-group">
 <label class="control-label">Эмоциональная окраска голоса: </label>
 <div class="col-lg-6">
<select class="form-control" name="emotion">
    <option value="good" [#if EMOTION=="good"#] selected[#endif#]>радостный, доброжелательный</option>
    <option value="evil" [#if EMOTION=="evil"#] selected[#endif#]>раздраженный</option>
    <option value="neutral" [#if EMOTION=="neutral"#] selected[#endif#]>нейтральный</option>
   </select>
</div>
</div>
<div class="form-group">
 <label class="control-label">Язык: </label>
<div class="col-lg-6">
<select class="form-control" name="lang">
    <option value="ru-RU" [#if LANG=="ru-RU"#] selected[#endif#]>Русский</option>
    <option value="uk-UK" [#if LANG=="uk-UK"#] selected[#endif#]>Украинский</option>
    <option value="en-US" [#if LANG=="en-US"#] selected[#endif#]>Английский</option>
   </select>
</div>
</div>

<div class="form-group">
 <label class="control-label"> Модуль: </label>
 <div class="col-lg-6">
 <input type="radio" name="disabled" value="0"[#if DISABLED!="1"#] checked[#endif#]><#LANG_ON#>
 <input type="radio" name="disabled" value="1"[#if DISABLED=="1"#] checked[#endif#]><#LANG_OFF#>
 </div>
</div>

<div class="form-actions">
<button type="submit" name="subm" value="Submit" class="btn btn-primary"><#LANG_UPDATE#></button>
<input type="hidden" name="view_mode" value="update_settings">
<input type="hidden" name="mode" value="update">
</div>
</fieldset>
</form>
<div class="pull-left"><a href="/index.php?pd=bWVtYmVyczp7aWQ9MjcxMSx2aWV3X21vZGU9YmxvZ19pdGVtLGFjdGlvbj1wcm9maWxlfQ%3D%3Dpz_YXBwbGljYXRpb246e2FjdGlvbj1wcm9maWxlfQ%3D%3Dpz_&md=members&inst=&clean=1" class="btn btn-default">Clear cache</a></div>
</div>
 [#endif VIEW_MODE#]

2-й путь - /var/www/html/modules/yandex_tts
Открываем в редакторе yandex_tts.class.php все грохаем и копи-пастом вставляем код:

<?php
class yandex_tts extends module {
function yandex_tts() {
  $this->name="yandex_tts";
  $this->title="Yandex TTS";
  $this->module_category="<#LANG_SECTION_APPLICATIONS#>";
  $this->checkInstalled();
}
/**
* saveParams
*
* Saving module parameters
*
* @access public
*/
function saveParams($data=0) {
 $p=array();
 if (IsSet($this->id)) {
  $p["id"]=$this->id;
 }
 if (IsSet($this->view_mode)) {
  $p["view_mode"]=$this->view_mode;
 }
 if (IsSet($this->edit_mode)) {
  $p["edit_mode"]=$this->edit_mode;
 }
 if (IsSet($this->tab)) {
  $p["tab"]=$this->tab;
 }
 return parent::saveParams($p);
}
/**
* getParams
*
* Getting module parameters from query string
*
* @access public
*/
function getParams() {
  global $id;
  global $mode;
  global $view_mode;
  global $edit_mode;
  global $tab;
  if (isset($id)) {
   $this->id=$id;
  }
  if (isset($mode)) {
   $this->mode=$mode;
  }
  if (isset($view_mode)) {
   $this->view_mode=$view_mode;
  }
  if (isset($edit_mode)) {
   $this->edit_mode=$edit_mode;
  }
  if (isset($tab)) {
   $this->tab=$tab;
  }
}
/**
* Run
*
* Description
*
* @access public
*/
function run() {
 global $session;
  $out=array();
  if ($this->action=='admin') {
   $this->admin($out);
  } else {
   $this->usual($out);
  }
  if (IsSet($this->owner->action)) {
   $out['PARENT_ACTION']=$this->owner->action;
  }
  if (IsSet($this->owner->name)) {
   $out['PARENT_NAME']=$this->owner->name;
  }
  $out['VIEW_MODE']=$this->view_mode;
  $out['EDIT_MODE']=$this->edit_mode;
  $out['MODE']=$this->mode;
  $out['ACTION']=$this->action;
  $this->data=$out;
  $p=new parser(DIR_TEMPLATES.$this->name."/".$this->name.".html", $this->data, $this);
  $this->result=$p->result;
}
/**
* BackEnd
*
* Module backend
*
* @access public
*/
function admin(&$out) {
    $this->getConfig();
    $out['ACCESS_KEY'] = $this->config['ACCESS_KEY'];
    $out['SPEAKER'] = $this->config['SPEAKER'];
    $out['LANG'] = $this->config['LANG'];
    $out['EMOTION'] = $this->config['EMOTION'];
    $out['EMPHASIS'] = $this->config['EMPHASIS'];
    $out['DISABLED'] = $this->config['DISABLED'];
    switch($this->view_mode) {
        case 'update_settings':
            global $access_key;
            $this->config['ACCESS_KEY'] = $access_key;
            global $speaker;
            $this->config['SPEAKER'] = $speaker;
            global $lang;
            $this->config['LANG'] = $lang;
            global $emotion;
            $this->config['EMOTION'] = $emotion;
            global $emphasis;
            $this->config['EMPHASIS'] = $emphasis;
            global $disabled;
            $this->config['DISABLED'] = $disabled;
            $this->saveConfig();
            $this->redirect('?view_mode=ok');
            break;
        case 'clear_cache':
            array_map('unlink', glob(ROOT.'cms/cached/voice/*_yandex.mp3'));
            $this->redirect('?view_mode=ok');
            break;
        case 'add_emphasis':
            global $search_str, $replace_str, $case;
            if(!empty($search_str) && !empty($replace_str)) {
                if($query = SQLSelectOne("SELECT * FROM `yandex_tts_emphasis` WHERE `search_str` LIKE '".DBSafe($search_str)."'")) {
                    $query['search_str'] = $search_str;
                    $query['replace_str'] = $replace_str;
                    $query['case'] = ($case=='1'?1:0);
                    if(SQLUpdate('yandex_tts_emphasis', $query)) {
                        $this->redirect('?view_mode=ok');
                    } else {
                        $this->redirect('?view_mode=err');
                    }
                } else {
                    $query = array();
                    $query['search_str'] = $search_str;
                    $query['replace_str'] = $replace_str;
                    $query['case'] = ($case=='1'?1:0);
                    if(SQLInsert('yandex_tts_emphasis', $query)) {
                        $this->redirect('?view_mode=ok');
                    } else {
                        $this->redirect('?view_mode=err');
                    }
                }
            } else {
                $this->redirect('?view_mode=err');
            }
            break;
        case 'delete_emphasis':
            global $id;
            if(SQLExec('DELETE FROM `yandex_tts_emphasis` WHERE `ID` = '.intval($id))) {
                $this->redirect('?view_mode=ok');
            } else {
                $this->redirect('?view_mode=err');
            }
            break;
        case 'emphasis_clear':
            if(SQLExec('TRUNCATE TABLE `yandex_tts_emphasis`')) {
                $this->redirect('?view_mode=ok');
            } else {
                $this->redirect('?view_mode=err');
            }
            break;
        case 'emphasis_import':
            if($this->mode == 'update') {
                $error = FALSE;
                global $file;
                if(file_exists($file)) {
                    $tmp = LoadFile($file);
                    $lines = mb_split("\n", $tmp);
                    foreach($lines as $line) {
                        $line = mb_split(':', $line);
                        $count = count($line);
                        if($count == 2 || $count == 3) {
                            $line[0] = str_replace('&#58;', ':', $line[0]);
                            $line[1] = str_replace('&#58;', ':', $line[1]);
                            $line[2] = ($count == 3?intval($line[2]):0);
                            if($query = SQLSelectOne("SELECT * FROM `yandex_tts_emphasis` WHERE `search_str` LIKE '".DBSafe($line[0])."'")) {
                                $query['search_str'] = $line[0];
                                $query['replace_str'] = $line[1];
                                $query['case'] = ($line[2]==1?1:0);
                                SQLUpdate('yandex_tts_emphasis', $query);
                            } else {
                                $query = array();
                                $query['search_str'] = $line[0];
                                $query['replace_str'] = $line[1];
                                $query['case'] = ($line[2]==1?1:0);
                                SQLInsert('yandex_tts_emphasis', $query);
                            }
                        }
                    }
                    $this->redirect('?view_mode=ok');
                } else {
                    $this->redirect('?view_mode=err');
                }
            }
            break;
        case 'emphasis_export':
            if($emphasis = SQLSelect('SELECT * FROM `yandex_tts_emphasis` ORDER BY `search_str`')) {
                $data = '';
                foreach($emphasis as $item) {
                    $item['search_str'] = str_replace(':', '&#58;', $item['search_str']);
                    $item['replace_str'] = str_replace(':', '&#58;', $item['replace_str']);
                    $item['case'] = intval($item['case']);
                    $data .= $item['search_str'].':'.$item['replace_str'].':'.$item['case'].PHP_EOL;
                }
                header('Content-Disposition: attachment; filename=yandex_tts_export_'.date('d-m-Y_H-i-s').'.dic');
                header('Content-Type: text/plain');
                die($data);
            } else {
                $this->redirect('?view_mode=err');
            }
            break;
        case 'ok':
            $out['OK'] = 1;
            break;
        case 'err':
            $out['ERR'] = 1;
            break;
    }
    // Show emphasis list
    $emphasis = SQLSelect('SELECT * FROM `yandex_tts_emphasis` ORDER BY `search_str`');
    foreach($emphasis as $item) {
        $out['EMPHASIS_LIST'][] = array(
            'ID'            => $item['ID'],
            'search_str'    => htmlspecialchars($item['search_str']),
            'replace_str'   => htmlspecialchars($item['replace_str']),
            'case'          => intval($item['case']),
        );
    }
}

/**
* FrontEnd
*
* Module frontend
*
* @access public
*/
function usual(&$out) {
 $this->admin($out);
}
 function processSubscription($event, &$details) {
  $this->getConfig();
  if ($event=='SAY' && !$this->config['DISABLED'] && !$details['ignoreVoice']) {
    $level=$details['level'];
    $message=$details['message'];

    if($this->config['EMPHASIS']) {
        $emphasis = SQLSelect('SELECT * FROM `yandex_tts_emphasis`');
        foreach($emphasis as $item) {
            if($item['case']) {
                $message = str_replace($item['search_str'], $item['replace_str'], $message);
            } else {
                $message = preg_replace_callback('/('.preg_quote($item['search_str'], '/').')/ui', function($match) use($item) {
                    return $item['replace_str'];
                }, $message);
            }
        }
    }

    $accessKey=$this->config['ACCESS_KEY'];
    $speaker=$this->config['SPEAKER'];
    $emotion=$this->config['EMOTION'];
    $lang=$this->config['LANG'];

    if ($level >= (int)getGlobal('minMsgLevel') && $accessKey!='')
    {
        $filename       = md5($message) . '_yandex.mp3';
        $cachedVoiceDir = ROOT . 'cms/cached/voice';
        $cachedFileName = $cachedVoiceDir . '/' . $filename;

        $base_url       = 'https://tts.voicetech.yandex.net/generate?';        

        if (!file_exists($cachedFileName))
        {

           $qs = http_build_query(array('format' => 'mp3', 'lang' => $lang, 'speaker' => $speaker, emotion => $emotion, 'key' => $accessKey, 'text' => $message));

           try
           {
              $contents = file_get_contents($base_url . $qs);
           }
           catch (Exception $e)
           {
              registerError('yandextts', get_class($e) . ', ' . $e->getMessage());
           }

           if (isset($contents))
           {
              CreateDir($cachedVoiceDir);
              SaveFile($cachedFileName, $contents);
           }
        } else {
         @touch($cachedFileName);
        }
        if (file_exists($cachedFileName)) {
          playSound($cachedFileName, 1, $level);
          $details['ignoreVoice']=1;
            processSubscriptions('SAY_CACHED_READY', array(
                'level' => $level,
                'tts_engine' => 'yandex',
                'message' => $message,
                'filename' => $cachedFileName,
                ));
        }
    }
  }
 }
/**
* Install
*
* Module installation routine
*
* @access private
*/
 function install($data='') {
  subscribeToEvent($this->name, 'SAY', '', 10);
  parent::install();
 }

 function dbInstall($data) {
$data = <<<EOD
 yandex_tts_emphasis: ID int(10) unsigned NOT NULL auto_increment
 yandex_tts_emphasis: search_str text
 yandex_tts_emphasis: replace_str text
 yandex_tts_emphasis: case boolean NOT NULL DEFAULT FALSE
EOD;
  parent::dbInstall($data);
 }

 function uninstall() {
  SQLExec('DROP TABLE IF EXISTS `yandex_tts_emphasis`');
  parent::uninstall();
 }

// --------------------------------------------------------------------
}

Идем в настройки модуля yandex_tts и там ставим чего надо.
Все )

Обсуждение (0) (4)

Смотрите так же:
03.11.2018 Как вылечить сломанный Dashboard (Панель)
29.10.2018 Как отключить размазанный BT и WI-FI на Raspberry PI

Los Angeles, США