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

329
LINES

< > BotCompany Repo | #1018442 // New Woody Web Interface [dev.]

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

Download Jar. Libraryless. Compilation Failed (14599L/107K).

!7

set flag NoAI.

sS imagesPath = "http://web-woody-lab.de/Botbilder/";
sS botURL = "http://www.web-woody-lab.de/bot.php";
sS defaultEmotion = "01", loadingEmotion = "14";
static long conversationTimeOutMS = 1000*60*30;
sbool enableDynamic = false, alwaysIframe = false;

static NewWoody bot;
static volatile bool loaded;
static new ThreadLocal<Conversation> conversation;
static new LS imageNames;

static LS suggestions = tlft([[
  Fragen Sie zum Beispiel, wie ein Chatbot installiert wird.
  Fragen Sie zum Beispiel, ob Ihr Logo als Chatbot taugt.
  Fragen Sie zum Beispiel, nach welchem Prinzip ein Chatbot agiert.
  Fragen Sie zum Beispiel, wie ein Bot auf hre Website kommt.
  Fragen Sie zum Beispiel, welche Ausbildung ein Chatbot braucht.
  Fragen Sie zum Beispiel, was das hier soll.
  Fragen Sie zum Beispiel, welchen Nutzen ein Chatbot bringt.
  Fragen Sie zum Beispiel, ob ein Chatbot mehr Erfolg verspricht.
  Fragen Sie zum Beispiel, wie wir es mit der Moral halten.
  Fragen Sie zum Beispiel, was ein virtueller Mitarbeiter bringt.
  Fragen Sie zum Beispiel, ob wir überhaupt Ahnung haben.
  Fragen Sie zum Beispiel, wer hier die Chefs sind.
]]);

sclass Msg semiauto {
  long time
  bool fromUser
  S text
  S newURL
  
  *() {}
  *(bool *fromUser, S *text) { time = now(); }
}

concept Conversation semiauto {
  S cookie
  new LL<Msg> oldDialogs
  new L<Msg> msgs

  void add(Msg m) { msgs.add(m); change(); }

  //SS vars = new HashMap;
  
  NewWoody woody;
}

p {
  db();
  thread { loadMe(); }
  loadImages();
}

svoid loadImages {
  imageNames.clear();
  for (S file : toLinesFullTrim(loadPage(imagesPath + "list.php")))
    if (ewic(file, ".jpg")) {
      print("Found image: " + file);
      imageNames.add(file);
    }
}

static CtxContext newContext(S cookie) {
  setConversation(cookie);
  Msg m = last(conversation->msgs);
  if (m != null && now() > m.time+conversationTimeOutMS) {
    NEU();
    ret ctxContext();
  }
  CtxContext ctx = woodyNewContext(bot);
  copyFields(conversation!, ctx, 'activeRule, 'activeAnalyzer, 'vars);
  ctx.conversationLength = l(conversation->msgs);
  ret ctx;
}

svoid doneContext {
  copyFields(ctxContext(), conversation!, 'activeRule, 'activeAnalyzer);
  //conversation->vars = dropKeysStartingWith("MATCH", ctxContext().vars);
  ctxContext(null);
}

sbool newUser;
sS answer(S s) {
  if (!isMainProgram()) null;
  time {
    newContext('default);
    
    if (eq(trim(s), "NEU")) {
      NEU();
      s = "";
      newUser = true;
    }
    
    if (newUser) {
      ctxNewUser();
      newUser = false;
    } else {
      print("Input: " + s);
      ctxProcessInput(s);
    }
    
    ctxDefaultOnEmptyOutput();
    
    for (S url : unnull(ctxContext().urlsToOpen)) print(">> " + url);
    S out = ctxGetOutput();
    print("Emotion: " + ctxGetLastEmotion(out));
    doneContext();
    ret out;
  }
}

svoid selfTest {}

svoid loadMe autosemi {
  bot = new NewWoody;

  // Bot is loaded now.
  if (isMainProgram()) selfTest()
  
  // Done loading. Make console bot if main program
  
  loaded = true
  if (isMainProgram()) makeBot(
}

svoid setConversation(S cookie) {
  conversation.set(uniq_sync(Conversation, +cookie));
}

svoid clearConversation(S cookie) {
  deleteConcepts(Conversation, +cookie);
}
 
svoid processActiveRule() {
  ctxProcessRule(ctxContext().activeRule);
}

// for webChatBotLogsHTML
static S formatDateAndTime(long time) {
  ret formatGermanDateAndTime(time);
}

html {
  registerVisitor();
  
  lock dbLock();
  
  if (eq(uri, "/logs"))
    ret webChatBotLogsHTML2(relativeRawBotLink(programID(), "logs"), params);
  
  S referer = subBot_referer();
  S message = trim(params.get('message));
  S text = "Programm lädt,\nbin gleich wieder da.";
  S page = params.get("uri");
  bool _loaded = loaded;
  Msg msg = null, msgMade = null;
  if (_loaded) {
    S cookie = params.get("session");
    if (empty(cookie)) cookie = cookieSent();
    if (empty(page)) page = referer;
    newContext(cookie);
    Conversation conv = conversation!;
    
    print("Conv ID: " + conv.id + ", cookie: " + conv.cookie + ", msgs: " + structForUser(conv.msgs));
    
    if (eq(message, "NEU")) {
      NEU();
      message = null;
    }

    if (empty(conv.msgs)) {
      ctxNewUser();
      conv.add(msgMade = botAnswerMsg());
    }
    
    // empty user input
    if (eq(message, "")) message = "-";
      
    if (nempty(message) && !lastUserMessageWas(conv, message))
      conv.add(new Msg(true, message));
  
    if (nempty(conv.msgs) && last(conv.msgs).fromUser) {
      L<S> buttons = null;
      pcall {
        ctxProcessInput(last(conv.msgs).text);
      }
      conv.add(msgMade = botAnswerMsg());
    }
    
    doneContext();
    
    msg = last(conv.msgs);
    text = msg.text;
  }
  
  S ping = params.get('ping);
  bool dynamic = eq(ping, 'dynamic);
  if (!dynamic && nempty(ping)) ret "";
  
  S textHtml = htmlEncode_nlToBr(dropAllTags(ctxDropEmotions(text)));
  bool include = nempty(params.get('include));
  S scrollCmd = "setTimeout(function() { document.body.scrollTop = 167; }, 200);";
  // "document.getElementById('theinput').scrollIntoView(false);"
  //S inner = himg("http://www.web-woody-lab.de/IMG_1460%20herz.jpg", width := 180, onload := scrollCmd);
  S emo;
  if (!_loaded) emo = loadingEmotion;
  else emo = or2(ctxGetLastEmotion(text), defaultEmotion);
  S imageName = firstStartingWith(imageNames, emo);
  //print("emo=" + emo + ", imageName=" + imageName);
  S inner = "";
  if (imageName != null) {
    S img = imagesPath + imageName;
    inner = himg(img, width := 180, height := 225/*, onload := scrollCmd*/);
  }
  
  if (!_loaded)
    inner += p(textHtml, style := "text-align: center");
  else {
    // loaded
    S suggestion = "";
    if (l(conversation->msgs) <= 1)
      suggestion = random(suggestions);
    /*else
      suggestion = sfu(collect(conversation->msgs, text));*/
      
    bool redirect = msg != null && nempty(msg.newURL) && msg == msgMade;
    inner += p(textHtml);
    inner +=
      redirect
        ? hjs_redirectWindowOrParent(msg.newURL.replaceAll("\\.html$", ".php"))
        // no redirect
        : (!enableDynamic ? "" : loadJQuery2()
        + jsJoinHack()
        + hjavascript([[
          function submitDynamic() {
            var url = #BOTURL# + "?ping=dynamic&message="
              + encodeURIComponent(document.getElementById('theinput').value);
            alert(url);
            /*$.get(url, function(src) {
              alert(src);
              $("#botdiv").html(src);
            }).fail(function() {
              alert("error");
            });*/
  $.ajax({
    type: "GET",
    url: url,
    success: function (response) {
        $('#botdiv').html(response.responseText);
    },
    error: function (jqXHR, exception, error) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = '0 ' + jqXHR.join();
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#botdiv').html(msg);
    }
  });
}
        ]].replace("#BOTURL#", jsQuote(botURL))))
        + hformPOST(
          htextinput("message", style := "width: 180px", autofocus := 1, id := "theinput", onkeydown := enableDynamic ? "if (event.keyCode != 13) return true; submitDynamic(); return false;" : null)
        + (!_loaded ? "" : p(nempty(suggestion)
          ? htmlencode(suggestion)
          : ahref("#", htmlencode("Neues Gespräch ") + "&nbsp;" + b("X"), style := "font-size: 14px; color: #299397", onClick := "theinput.value = 'NEU'; document.getElementById('theform').submit(); return false;")
          , style := "color: #299397; font-style: italic" + (nempty(suggestion) ? "" : "; text-align: right")))
          , "accept-charset" := "UTF-8", id := "theform");
  }
      
  S loadingRefresher = _loaded ? "" :
    //hrefresh(5, include ? "" : fullSelfLink(params));
    hjs_reloadWindowIn(5);
      
  if (dynamic) ret loadingRefresher + inner;
  if (include)
    if (alwaysIframe)
      ret tag("iframe", "", src := rawBotLink_newServer(), width := 180, height := 600, frameBorder := 0);
    else
      ret loadingRefresher + div(inner, id := 'botdiv);
  
  // deliver iframe contents
  ret hhtml(hhead(
    loadingRefresher
    + hcss([[
      body { background-color:white; }
      p { font:normal 14px Arial, Helvetica; color:black; line-height:18px; }
    ]]))
    + hbody(inner, style := "margin: 0px", onload := "document.getElementById('theinput').focus();");
}

static bool lastUserMessageWas(Conversation conv, S message) {
  Msg m = last(conv.msgs);
  ret m != null && m.fromUser && eq(m.text, message);
}

static Msg botAnswerMsg() {
  // S reply = "Ich habe Sie leider nicht verstanden";
  ctxDefaultOnEmptyOutput();
  S output = ctxGetOutput();
  S reply = output;
  Msg _msg = new Msg(false, reply);
  _msg.newURL = last(ctxContext().urlsToOpen);
  ret _msg;
}

svoid NEU {
  Conversation conv = conversation!;
  conv.oldDialogs.add(conv.msgs);
  cset(conv, msgs := new L);
  cset(conv, woody := new NewWoody);
  newContext(conv.cookie);
}

Author comment

Began life as a copy of #1008855

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1018442
Snippet name: New Woody Web Interface [dev.]
Eternal ID of this version: #1018442/6
Text MD5: 74a167f09542de7b09ebb111c8e0602a
Transpilation MD5: c8cb7de788d37a654e20e310bd49ec28
Author: stefan
Category: javax / a.i.
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-09-30 23:27:15
Source code size: 9844 bytes / 329 lines
Pitched / IR pitched: No / No
Views / Downloads: 394 / 676
Version history: 5 change(s)
Referenced in: [show references]