Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

516
LINES

< > BotCompany Repo | #1002944 // Pivo Bot English (multi-lingual)

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Libraryless. Click here for Pure Java version (2708L/22K/69K).

!752

!include #1002943 // Pivo Logic (include)

static S logName = "log";
static long requestID, logLength;

static L<S> showableFiles = litlist(logName); // ...

static new L<Entry> history;

static class Entry {
  long time;
  S cookie;
  S userSaid, botSaid;
  long logID;
}

static new L<Bot> bots;

static class Bot {
  // n = where new stuff starts
  void learnFrom(L<Entry> history, int n) {}

  S answer(S question) { ret null; }

  void load(LoadEnv env) {}
  void save(LoadEnv env) {}
}

p {
  pivoLoad();
  load("requestID");
  L<Map> log = scanMapLog(logName);
  logLength += l(log);
  addToHistory(makeHistory(log));
}

static S rawLink(S pageName) {
  ret "/" + parseSnippetID(getProgramID()) + "/raw/" + pageName;
}

static long newRequestID() {
  long id = ++requestID;
  save("requestID");
  ret id;
}

static S html(S uri, Map<S, S> params) {
  if (eq(uri, "/log"))
    ret htable(scanMapLog(logName));
  if (eq(uri, "/has-speech")) {
    O cookieHandler = call(getMainBot(), "getCookies");
    S cookieMD5 = md5((S) call(cookieHandler, "read", "cookie"));
  
    S language = getString(params, "language");
    long requestID = newRequestID();
    S s = params.get("q");
    Map logData = litmap("ip", getClientIP(), "thread", threadID(), "cookie", cookieMD5, "language", language, "heard", s);
    log(mapPlus(logData, "starting", now()));
    
    ((ThreadLocal<Boolean>) get(getMainBot(), "attn")).set(true);
    pivoMode.set(true);
    S text = //askSelf(s);
      callStaticAnswerMethod(mc(), s);
    if (empty(text)) {
      log(mapPlus(logData, "done", now(), "saying", "-"));
      ret "";
    }
    
    S voice = eq(language, "6") ? "William" : "Alex";
    S soundURL = getSoundURLCereproc(text, voice);
    S html = [[
    <audio controls autoplay>
      <source src="SRC" type="audio/mpeg">
      ! Kein Ton im Browser !
    </audio>
    ]];
    html = html.replace("SRC", htmlencode(soundURL));
    log(mapPlus(logData, "done", now(), "saying", text));
    ret "Speech (" + voice + "): " + htmlencode(text) + "<br>" + html;
  }
  
  if (eq(uri, "/empty")) {
    ret "";
  }
  
  if (eq(uri, "/upper")) {
 S html = [=[
<!DOCTYPE html>
<meta charset="utf-8">
<title>TinyBrain Speech Demo</title>
<style>
  * {
    font-family: Verdana, Arial, sans-serif;
  }
  a:link {
    color:#000;
    text-decoration: none;
  }
  a:visited {
    color:#000;
  }
  a:hover {
    color:#33F;
  }
  .button {
    background: -webkit-linear-gradient(top,#008dfd 0,#0370ea 100%);
    border: 1px solid #076bd2;
    border-radius: 3px;
    color: #fff;
    display: none;
    font-size: 13px;
    font-weight: bold;
    line-height: 1.3;
    padding: 8px 25px;
    text-align: center;
    text-shadow: 1px 1px 1px #076bd2;
    letter-spacing: normal;
  }
  .center {
    padding: 10px;
    text-align: center;
  }
  .final {
    color: black;
    padding-right: 3px; 
  }
  .interim {
    color: gray;
  }
  .info {
    font-size: 34px;
    text-align: center;
    color: #777;
    display: none;
  }
  .right {
    float: right;
  }
  .sidebyside {
    display: inline-block;
    width: 45%;
    min-height: 40px;
    text-align: left;
    vertical-align: top;
  }
  #headline {
    font-size: 80px;
    font-weight: 300;
  }
  #info {
    font-size: 50px;
    text-align: center;
    color: #777;
    visibility: hidden;
  }
  #results {
    font-size: 55px;
    font-weight: bold;
    border: 1px solid #ddd;
    padding: 15px;
    text-align: left;
    min-height: 50px;
  }
  #start_button {
    border: 0;    background-color:transparent;
    padding: 0;
  }
</style>

<div id="info">
  <p id="info_start">Click on the microphone icon and begin speaking.</p>
  <p id="info_speak_now">Speak after the bleep.</p>
  <p id="info_no_speech">No speech was detected</p>
  <p id="info_no_microphone" style="display:none">
    No microphone was found. Ensure that a microphone is installed and that
    <a href="//support.google.com/chrome/bin/answer.py?hl=en&amp;answer=1407892">
    microphone settings</a> are configured correctly.</p>
  <p id="info_allow">Click the "Allow" button.</p>
  <p id="info_denied">Permission to use microphone was denied.</p>
  <p id="info_blocked">Permission to use microphone is blocked. To change,
    go to chrome://settings/contentExceptions#media-stream</p>
  <p id="info_upgrade">Web Speech API is not supported by this browser.
     Upgrade to <a href="//www.google.com/chrome">Chrome</a>
     version 25 or later.</p>
</div>
<div class="right">
  <button id="start_button" onclick="startButton(event)">
    <img id="start_img" src="http://tinybrain.de:8080/speech/mic.gif" width="120" alt="Start"></button>
</div>
<div id="results">
  <span id="final_span" class="final"></span>
  <span id="interim_span" class="interim"></span>
  <p>
</div>
<div class="center">
  <p>
  <div id="div_language">
    <?= $mode ?>
    &nbsp;&nbsp;
    <select style="font-size: 30px" id="select_language" onchange="updateCountry()"></select>
    &nbsp;&nbsp;
    <select id="select_dialect"></select>
  </div>
</div>
<script>
var langs =
[['Afrikaans',       ['af-ZA']],
 ['Bahasa Indonesia',['id-ID']],
 ['Bahasa Melayu',   ['ms-MY']],
 ['Català',          ['ca-ES']],
 ['?eština',         ['cs-CZ']],
 ['Deutsch',         ['de-DE']],
 ['English',         ['en-AU', 'Australia'],
                     ['en-CA', 'Canada'],
                     ['en-IN', 'India'],
                     ['en-NZ', 'New Zealand'],
                     ['en-ZA', 'South Africa'],
                     ['en-GB', 'United Kingdom'],
                     ['en-US', 'United States']],
 ['Español',         ['es-AR', 'Argentina'],
                     ['es-BO', 'Bolivia'],
                     ['es-CL', 'Chile'],
                     ['es-CO', 'Colombia'],
                     ['es-CR', 'Costa Rica'],
                     ['es-EC', 'Ecuador'],
                     ['es-SV', 'El Salvador'],
                     ['es-ES', 'España'],
                     ['es-US', 'Estados Unidos'],
                     ['es-GT', 'Guatemala'],
                     ['es-HN', 'Honduras'],
                     ['es-MX', 'México'],
                     ['es-NI', 'Nicaragua'],
                     ['es-PA', 'Panamá'],
                     ['es-PY', 'Paraguay'],
                     ['es-PE', 'Perú'],
                     ['es-PR', 'Puerto Rico'],
                     ['es-DO', 'República Dominicana'],
                     ['es-UY', 'Uruguay'],
                     ['es-VE', 'Venezuela']],
 ['Euskara',         ['eu-ES']],
 ['Français',        ['fr-FR']],
 ['Galego',          ['gl-ES']],
 ['Hrvatski',        ['hr_HR']],
 ['IsiZulu',         ['zu-ZA']],
 ['Íslenska',        ['is-IS']],
 ['Italiano',        ['it-IT', 'Italia'],
                     ['it-CH', 'Svizzera']],
 ['Magyar',          ['hu-HU']],
 ['Nederlands',      ['nl-NL']],
 ['Norsk bokmål',    ['nb-NO']],
 ['Polski',          ['pl-PL']],
 ['Português',       ['pt-BR', 'Brasil'],
                     ['pt-PT', 'Portugal']],
 ['Român?',          ['ro-RO']],
 ['Sloven?ina',      ['sk-SK']],
 ['Suomi',           ['fi-FI']],
 ['Svenska',         ['sv-SE']],
 ['Türkçe',          ['tr-TR']],
 ['?????????',       ['bg-BG']],
 ['P??????',         ['ru-RU']],
 ['??????',          ['sr-RS']],
 ['???',            ['ko-KR']],
 ['??',             ['cmn-Hans-CN', '??? (????)'],
                     ['cmn-Hans-HK', '??? (??)'],
                     ['cmn-Hant-TW', '?? (??)'],
                     ['yue-Hant-HK', '?? (??)']],
 ['???',           ['ja-JP']],
 ['Lingua lat?na',   ['la']]];

for (var i = 0; i < langs.length; i++) {
  select_language.options[i] = new Option(langs[i][0], i);
}

// 6 = English

select_language.selectedIndex = 6;
updateCountry();
select_dialect.selectedIndex = 6;
showInfo('info_start');

function updateCountry() {
  for (var i = select_dialect.options.length - 1; i >= 0; i--) {
    select_dialect.remove(i);
  }
  var list = langs[select_language.selectedIndex];
  for (var i = 1; i < list.length; i++) {
    select_dialect.options.add(new Option(list[i][1], list[i][0]));
  }
  select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';
}

var final_transcript = '';
var recognizing = false;
var ignore_onend;
var ignore_result;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
  upgrade();
} else {
  var contentFrame = parent.contentframe;
  var lastText = "";

  start_button.style.display = 'inline-block';
  var recognition = new webkitSpeechRecognition();
  recognition.continuous = false; // TRUE
  recognition.interimResults = false;

  recognition.onstart = function() {
    recognizing = true;
    showInfo('info_speak_now');
    start_img.src = 'http://tinybrain.de:8080/speech/mic-animate.gif';
  };

  recognition.onerror = function(event) {
    if (event.error == 'no-speech') {
      start_img.src = 'http://tinybrain.de:8080/speech/mic.gif';
      showInfo('info_no_speech');
      ignore_onend = true;
    }
    if (event.error == 'audio-capture') {
      start_img.src = 'http://tinybrain.de:8080/speech/mic.gif';
      showInfo('info_no_microphone');
      ignore_onend = true;
    }
    if (event.error == 'not-allowed') {
      if (event.timeStamp - start_timestamp < 100) {
        showInfo('info_blocked');
      } else {
        showInfo('info_denied');
      }
      ignore_onend = true;
    }
  };

  recognition.onend = function() {
    recognizing = false;
    if (ignore_onend) {
      return;
    }
    start_img.src = 'http://tinybrain.de:8080/speech/mic.gif';
    
    //final_transcript = ""; // DEH HACK

    if (!final_transcript) {
      showInfo('info_start');
      return;
    }
    showInfo('');
    if (window.getSelection) {
      window.getSelection().removeAllRanges();
      var range = document.createRange();
      range.selectNode(document.getElementById('final_span'));
      window.getSelection().addRange(range);
    }
  };

  recognition.onresult = function(event) {
    var interim_transcript = '';
    if (ignore_result) {
      ignore_result = false;
      return;
    }
    for (var i = event.resultIndex; i < event.results.length; ++i) {
      if (event.results[i].isFinal) {
        var newData = event.results[i][0].transcript;
        //final_transcript += newData;
        final_transcript = newData;
        var frameURL = "LINK/has-speech?q=" + encodeURIComponent(newData) + "&language=" + select_language.selectedIndex + "&sublanguage=" + select_dialect.selectedIndex;
        if (contentFrame && lastText != newData) {
          lastText = newData;
          contentFrame.location.href = frameURL;
        }
      } else {
        interim_transcript += event.results[i][0].transcript;
      }
    }
    final_transcript = capitalize(final_transcript);
    final_span.innerHTML = linebreak(final_transcript);
    interim_span.innerHTML = linebreak(interim_transcript);
    if (/*final_transcript ||*/ interim_transcript) {
      showButtons('inline-block');
    }
  };
  
  startRecognition();
}

function upgrade() {
  start_button.style.visibility = 'hidden';
  showInfo('info_upgrade');
}

var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
  return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}

var first_char = /\S/;
function capitalize(s) {
  return s.replace(first_char, function(m) { return m.toUpperCase(); });
}

function copyButton() {
  if (recognizing) {
    recognizing = false;
    recognition.stop();
  }
  copy_button.style.display = 'none';
  copy_info.style.display = 'inline-block';
  showInfo('');
}

function startButton(event) {
  startRecognition();
}

function startRecognition() {
  if (recognizing) {
    recognition.stop();
    ignore_result = true;
    return;
  }
  final_transcript = '';
  recognition.lang = select_dialect.value;
  recognition.start();
  ignore_onend = false;
  final_span.innerHTML = '';
  interim_span.innerHTML = '';
  start_img.src = 'http://tinybrain.de:8080/speech/mic-slash.gif';
  showInfo('info_allow');
  showButtons('none');
  start_timestamp = event.timeStamp;
}

function showInfo(s) {
  if (s) {
    for (var child = info.firstChild; child; child = child.nextSibling) {
      if (child.style) {
        child.style.display = child.id == s ? 'inline' : 'none';
      }
    }
    info.style.visibility = 'visible';
  } else {
    info.style.visibility = 'hidden';
  }
}

var current_style;
function showButtons(style) {
  if (style == current_style) {
    return;
  }
  current_style = style;
  copy_button.style.display = style;
  copy_info.style.display = 'none';
}
</script>
]=];
    ret render(html);
  }
  
  // frame set
  
  ret render([[
<title>TITLE</title>

<frameset rows="280,*">
  <frame src="LINK/upper"></frame>
  <frame name="contentframe" src="LINK/empty"></frame>
</frameset>
]]);
}

static S render(S html) {
  ret html.replace("LINK/", rawLink("")).replace("TITLE", getProgramName());
}

static L<Entry> makeHistory(L<Map> log) {
  new L<Entry> history;
  for (Map map : log) {
    S in = cast map.get("heard");
    S out = cast map.get("saying");
    if (nempty(in) && nempty(out)) {
      new Entry e;
      e.userSaid = in;
      e.botSaid = out;
      e.time = toLong(map.get("done"));
      e.cookie = (S) map.get("cookie");
      e.logID = toLong(map.get("_id"));
      history.add(e);
    }
  }
  ret history;
}

static void addToHistory(L<Entry> l) {
  int n = l(history);
  history.addAll(l);
  learnFrom(n);
}

static void learnFrom(int n) {
  for (Bot bot : bots) pcall {
    bot.learnFrom(history, n);
  }
}

static void log(Map map) {
  map.put("_id", logLength+1);
  logMap(logName, map);
  ++logLength;
  addToHistory(makeHistory(litlist(map)));
}

Author comment

Began life as a copy of #1002922

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1002944
Snippet name: Pivo Bot English (multi-lingual)
Eternal ID of this version: #1002944/1
Text MD5: b2106d3e120b82e818e76a61d0bfa021
Transpilation MD5: e637af660ca0a1daab571c3c67cfb468
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-04-12 17:49:44
Source code size: 14202 bytes / 516 lines
Pitched / IR pitched: No / No
Views / Downloads: 856 / 867
Referenced in: #3000376 - Answer for stefanreich (>> list sub bots)
#3000380 - Answer for stefanreich (>> list sub bots)
#3000381 - Answer for speedforce (>> list sub bots)
#3000382 - Answer for ferdie (>> t = 1, f = 0)
#3000383 - Answer for funkoverflow (>> t=1, f=0 okay)